You are on page 1of 2074

OPERATIONS GUIDE | INTERNAL

SAP IQ 16.1 SP 03
Document Version: 1.0.0 – 2018-11-20

SAP IQ SQL Reference


© 2018 SAP SE or an SAP affiliate company. All rights reserved.

THE BEST RUN


Content

1 SAP IQ SQL Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2 SQL Language Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30


2.1 Keywords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Reserved Words. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.2 Identifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Database Server Naming Restrictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.3 Mutexes and semaphores. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.4 Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.5 Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Constants in Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Column Names in Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Subqueries in Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
SQL Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
IF Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
CASE Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Compatibility of Expressions and Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.6 Search Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
Comparison Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Three-Valued Logic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Subqueries in Search Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62
ALL or ANY Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66
BETWEEN Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Conditions with Logical Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
CONTAINS Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
EXISTS Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68
IN Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
IS DISTINCT FROM Search Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69
IS NULL Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
LIKE Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70
NOT Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Truth Value Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
User-Supplied Condition Hints. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.7 Special Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
CURRENT DATABASE Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
CURRENT DATE Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
CURRENT PUBLISHER Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86

SAP IQ SQL Reference


2 INTERNAL Content
CURRENT TIME Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86
CURRENT TIMESTAMP Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
CURRENT USER Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
EXECUTING USER special value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
INVOKING USER special value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
LAST USER Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
PROCEDURE OWNER special value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
SESSION USER special value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
SQLCODE Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
SQLSTATE Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
TIMESTAMP Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
USER Special Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
2.8 %TYPE and %ROWTYPE attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
%TYPE attribute syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
%ROWTYPE attribute syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
2.9 SQL variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
2.10 Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Local Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104
Connection-Level Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Global Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
2.11 Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
2.12 NULL Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

3 SQL Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115


3.1 Character Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Storage Sizes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Character Sets and Code Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Indexes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
VARCHAR Data and Trailing Blanks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118
Restriction on CHAR and VARCHAR Data Over 255 Bytes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Long Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
3.2 Numeric Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Usage for Numeric Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
3.3 Binary Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Usage for Binary Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
3.4 Bit Data Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
3.5 Date and Time Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Usage for Date and Time Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
3.6 TABLE REF data type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
3.7 Domains. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138
Simple Domains. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
CREATE DOMAIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140

SAP IQ SQL Reference


Content INTERNAL 3
Domain Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
3.8 Data Type Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
3.9 Compatibility of String to Datetime Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144
Compatibility of Exported Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145
Conversion of BIT to BINARY Data Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Conversion Between BIT and CHAR/VARCHAR Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . 147

4 Differences from Other SQL Dialects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149


4.1 Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
4.2 Integrity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
4.3 Joins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.4 Updates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.5 Altering Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
4.6 Subqueries Not Always Allowed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.7 Additional Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
4.8 Cursors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

5 Compatibility with Other SAP Database Products. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153


5.1 About SAP SQL Anywhere. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5.2 An Overview of Transact-SQL Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5.3 SAP ASE, SAP SQL Anywhere, and SAP IQ Architectures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155
Servers and Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Space Allocation and Device Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
System Tables, Catalog Store, and IQ Main Store. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156
5.4 Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Bit Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Character Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158
Binary Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Date, Time, Datetime, and Timestamp Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Numeric Data Types Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Text Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Image Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Java Data Type Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162
5.5 Data Definition Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Creating a Transact-SQL Compatible Database Using the CREATE DATABASE statement. . . . . . 163
Case-Sensitivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Ensuring Compatible Object Names. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164
CREATE TABLE Statement Usage Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
CREATE DEFAULT, CREATE RULE, and CREATE DOMAIN Statements Usage Considerations
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
CREATE TRIGGER Statement Usage Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
CREATE INDEX Statement Usage Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

SAP IQ SQL Reference


4 INTERNAL Content
Users, Groups/Roles, and Permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Load Formats. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Options for Transact-SQL Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
5.6 Data Manipulation Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
General Guidelines for Writing Portable SQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Criteria for Writing Compatible Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174
Subquery Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
GROUP BY Clause Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
COMPUTE Clause Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
WHERE Clause Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Transact-SQL Outer Joins Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
ANSI Joins Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Null Comparisons Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Zero-Length Strings Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
HOLDLOCK, SHARED, and FOR BROWSE Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
SQL Function Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
OLAP Function Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
System Function Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
User-Defined Function Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Differences Interpreting Arithmetic Expressions on Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
SELECT INTO Statement Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Updatable Views Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Support for FROM Clause in UPDATE and DELETE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
5.7 Transact-SQL Procedure Language Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Transact-SQL Stored Procedure Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Transact-SQL Batch Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
SQL Statements in Procedures and Batches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
5.8 Automatic Translation of Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.9 Result Sets from Transact-SQL Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.10 Variables in Transact-SQL Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
5.11 Error Handling in Transact-SQL Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Using the RAISERROR Statement in Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Transact-SQL-Like Error Handling in the Watcom-SQL Dialect. . . . . . . . . . . . . . . . . . . . . . . . . 188
5.12 SAP SQL Anywhere and SAP IQ Differences and Shared Functionality. . . . . . . . . . . . . . . . . . . . . . 188
SAP SQL Anywhere Server and Database Startup and Administration. . . . . . . . . . . . . . . . . . . . 189
SAP SQL Anywhere Data Definition Language (DDL) Differences. . . . . . . . . . . . . . . . . . . . . . . 189
SAP SQL Anywhere Data Manipulation Language (DML) Differences. . . . . . . . . . . . . . . . . . . . .190
5.13 Differences and Shared Functionality Between SAP ASE and SAP IQ. . . . . . . . . . . . . . . . . . . . . . . . 191
SAP ASE Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
SAP ASE System Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

6 SQL Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193

SAP IQ SQL Reference


Content INTERNAL 5
6.1 Aggregate Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
6.2 Analytical Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Windowing Aggregate Function Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Ranking Functions Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Statistical Aggregate Analytic Function Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .199
Distribution Functions Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .199
Interrow Functions Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
6.3 Data Type Conversion Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
6.4 Date and Time Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Date Parts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .205
6.5 HTTP Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
6.6 Numeric Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
6.7 String Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
6.8 System Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
SAP ASE System Function Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Connection Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Properties Available for the Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Properties Available for Each Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
6.9 SQL and External Environment User-Defined Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
User-Defined Functions in SQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
User-Defined Functions in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
6.10 Miscellaneous Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
6.11 Alphabetical List of Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
ABS Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266
ACOS Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267
AES_ENCRYPT Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
AES_DECRYPT Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
ARGN Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .271
ASCII Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
ASIN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
ATAN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
ATAN2 Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
AVG Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
BFILE Function [Data Extraction]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .278
BIGINTTOHEX Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .280
BIT_LENGTH Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
BYTE_LENGTH Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
BYTE_LENGTH64 Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284
BYTE_REPLACE function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
BYTE_SUBSTR function [String] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
BYTE_SUBSTR64 and BYTE_SUBSTR Functions [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . .287

SAP IQ SQL Reference


6 INTERNAL Content
CAST Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
CEIL Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
CEILING Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
CHAR function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
CHAR_LENGTH Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
CHAR_LENGTH64 Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
CHARINDEX Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
COALESCE Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
COL_LENGTH Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
COL_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
CONNECTION_PROPERTY Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
CONVERT Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
CORR Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
COS Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
COT Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
COVAR_POP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
COVAR_SAMP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
COUNT Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
CUME_DIST Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
DATALENGTH Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .316
DATE Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
DATEADD Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
DATECEILING Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
DATEDIFF Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
DATEFLOOR Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
DATEFORMAT Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
DATENAME Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
DATEPART Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
DATEROUND Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
DATETIME Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
DAY Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
DAYNAME Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
DAYS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .338
DB_ID Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
DB_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
DB_PROPERTY Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
DEGREES Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .344
DENSE_RANK Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
DIFFERENCE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
DOW Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
ENCRYPT function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349

SAP IQ SQL Reference


Content INTERNAL 7
ERRORMSG Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
EVENT_CONDITION Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
EVENT_CONDITION_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
EVENT_PARAMETER Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
EXP Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
EXP_WEIGHTED_AVG Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .359
FIRST_VALUE Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
FLOOR Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .363
GETDATE Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
GRAPHICAL_PLAN Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
GROUPING Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
GROUP_MEMBER Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
HEXTOBIGINT Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
HEXTOINT Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
HOUR Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
HOURS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
HTML_DECODE function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .375
HTML_ENCODE function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
HTML_PLAN Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
HTTP_DECODE function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
HTTP_ENCODE function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
HTTP_HEADER function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
HTTP_RESPONSE_HEADER function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
HTTP_VARIABLE function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
IFNULL Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
INDEX_COL Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
INSERTSTR Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
INTTOHEX Function [Data Type Conversion]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391
ISDATE Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
ISNULL Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
ISNUMERIC Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
LAG Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
LAST_VALUE Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
LCASE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
LEAD Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
LEFT Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
LEN Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
LENGTH Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
LN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .408
LOCATE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
LOG Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412

SAP IQ SQL Reference


8 INTERNAL Content
LIST Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .413
LOG10 Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
LOWER Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
LPAD Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
LTRIM Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
MAX Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
MEDIAN Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
MIN Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .423
MINUTE Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
MINUTES Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
MOD Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
MONTH Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .428
MONTHNAME Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
MONTHS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
NEWID Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .432
NEXT_CONNECTION Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
NEXT_DATABASE Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .435
NEXT_HTTP_HEADER function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .437
NEXT_HTTP_VARIABLE function [Web service]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
NOW Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
NTILE Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
NULLIF Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
NUMBER Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
OBJECT_ID Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
OBJECT_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
OCTET_LENGTH Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
PATINDEX Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
PERCENT_RANK Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
PERCENTILE_CONT Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
PERCENTILE_DISC Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
PI Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
POWER Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
PROPERTY Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
PROPERTY_DESCRIPTION Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
PROPERTY_IS_TRACKABLE function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .461
PROPERTY_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
PROPERTY_NUMBER Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
QUARTER Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
QUARTERSTR Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
RADIANS Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
RAND Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468

SAP IQ SQL Reference


Content INTERNAL 9
RANK Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
READ_SERVER_FILE function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
REGR_AVGX Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
REGR_AVGY Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
REGR_COUNT Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
REGR_INTERCEPT Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
REGR_R2 Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
REGR_SLOPE Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
REGR_SXX Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .482
REGR_SXY Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .484
REGR_SYY Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
REMAINDER Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .487
REPEAT Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .488
REPLACE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
REPLICATE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
REVERSE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
RIGHT Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
ROUND Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
ROW_NUMBER Function [Analytical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
ROWID Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
RPAD Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .501
RTRIM Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .502
SECOND Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
SECONDS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
SIGN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
SIMILAR Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
SIN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
SORTKEY Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
SOUNDEX Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
SP_HAS_ROLE Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
SPACE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
SQLFLAGGER Function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
SQRT Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .520
SQUARE Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
STACK_TRACE function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
STDDEV Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
STDDEV_POP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
STDDEV_SAMP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
STR Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .529
STR_REPLACE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
STRING Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532

SAP IQ SQL Reference


10 INTERNAL Content
STRTOUUID Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
STUFF Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
SUBSTRING Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .536
SUBSTRING64 Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .539
SUM Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
SUSER_ID Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
SUSER_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
TAN Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
TODAY Function [Date and time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
TRIM Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
TRUNCNUM Function [Numeric]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
UCASE Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
UPPER Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
USER_ID Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
USER_NAME Function [System]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
UUIDTOSTR Function [String]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
VAR_POP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
VAR_SAMP Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
VAREXISTS function [Miscellaneous]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
VARIANCE Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
WEEKS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
WEIGHTED_AVG Function [Aggregate]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
WIDTH_BUCKET Function [Numerical]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
YEAR Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
YEARS Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
YMD Function [Date and Time]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570

7 System Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572


7.1 Managing Privileged System Procedure Execution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Implications of Migrating Compatibility Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Granting the Ability to Run a Privileged System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Revoking the Ability to Run a Privileged System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
Determining the Security Model Used by a Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
Pre-16.x Privileged System Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
7.2 Syntax Rules for Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
7.3 Understanding Statistics Reported by Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
7.4 Procedures Supported bySAP SQL Anywhere. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
7.5 Alphabetical List of System Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
(Deprecated) sp_iqaddlogin Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
sp_iqbackupdetails Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
sp_iqbackupsummary Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
sp_iqcalcbaserlvstore Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

SAP IQ SQL Reference


Content INTERNAL 11
(Deprecated) sp_iqcardinality_analysis Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
sp_iqcheckdb Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
sp_iqcheckfpconsistency Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
sp_iqcheckoptions Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .608
sp_iqclient_lookup Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
sp_iqcolumn Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
sp_iqcolumnmetadata Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
sp_iqcolumnuse Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
sp_iqconnection Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .618
sp_iqconstraint Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
sp_iqcontext Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
sp_iqcopyloginpolicy Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
sp_iqcursorinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
sp_iqdatatype Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
sp_iqdbsize Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
sp_iqdbspace Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
sp_iqdbspaceinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .639
sp_iqdbspaceobjectinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
sp_iqdbstatistics Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
sp_iqdroplogin Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .648
sp_iqemptyfile Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .650
sp_iqestdbspaces Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
sp_iqestspace Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
sp_iqevent Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .656
sp_iqfile Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
sp_iqhelp Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
sp_iqindex and sp_iqindex_alt Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
sp_iqindexadvice Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
sp_iqindexfragmentation Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
sp_iqindexinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
sp_iqindexmetadata Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
sp_iqindexrebuildwidedata Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
sp_iqindexsize Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
sp_iqindexuse Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
sp_iqlmconfig Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
sp_iqlocks Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
sp_iqmergerlvstore Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
sp_iqmergerlvtables Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
sp_iqmodifyadmin Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
sp_iqmodifylogin Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
sp_iqmovetablefromfile Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704

SAP IQ SQL Reference


12 INTERNAL Content
sp_iqmpxcheckdqpconfig Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
sp_iqmpxdumptlvlog Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
sp_iqmpxfilestatus Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
sp_iqmpxincconnpoolinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
sp_iqmpxincheartbeatinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
sp_iqmpxincstatistics Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
sp_iqmpxinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
sp_iqmpxsuspendedconninfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
sp_iqmpxvalidate Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
sp_iqmpxversioninfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
sp_iqobjectinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722
(Deprecated) sp_iqpassword Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
sp_iqpkeys Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .727
sp_iqprocedure Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
sp_iqprocparm Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .732
sp_iqpurgebackuphistory Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
sp_iqrebuildindex Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
sp_iqrebuildindexwide Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
sp_iqrename Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
sp_iq_reset_identity Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746
sp_iqrestoreaction Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
sp_iqrlvmemory Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .750
sp_iqrowdensity Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
sp_iqsetcompression Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
sp_iqsharedtempdistrib Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
sp_iqshowcompression Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .757
sp_iqshowpsexe Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
sp_iqspaceinfo Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .760
sp_iqspaceused Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
sp_iqstatistics Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
sp_iqstatus Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 768
sp_iqsysmon Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
sp_iqtable Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
sp_iqtablesize Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
sp_iqtableuse Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
sp_iqtransaction Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
sp_iqunusedcolumn Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
sp_iqunusedindex Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
sp_iqunusedtable Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
sp_iqversionuse Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
sp_iqview Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809

SAP IQ SQL Reference


Content INTERNAL 13
sp_iqwho Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
sp_iqworkmon Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
sp_iqzonemapenable Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
7.6 Alphabetical List of Catalog Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
sa_ansi_standard_packages system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
sa_audit_string system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
sa_char_terms system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
sa_checkpoint_execute System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .826
sa_conn_activity system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
sa_conn_info system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830
sa_conn_list System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .834
sa_conn_properties system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
sa_db_info system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
sa_db_option system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
sa_db_properties system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
sa_dependent_views system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 843
sa_describe_shapefile System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
sa_disable_auditing_type system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .847
sa_disk_free_space system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .849
sa_enable_auditing_type system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 850
sa_eng_properties system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 852
sa_external_library_unload System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
sa_flush_cache system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
sa_get_ldapserver_status System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
sa_get_user_status system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
sa_http_header_info system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
sa_list_external_library System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 860
sa_list_statements system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 861
sa_locks System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863
sa_make_object system procedure (deprecated). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866
sa_nchar_terms System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
sa_performance_diagnostics System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .869
sa_procedure_profile System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
sa_procedure_profile_summary System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .876
sa_report_deadlocks System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879
sa_rowgenerator system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
sa_server_option System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 882
sa_set_http_header system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
sa_set_http_option system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
sa_stack_trace system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901
sa_table_page_usage system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904

SAP IQ SQL Reference


14 INTERNAL Content
sa_text_index_stats System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
sa_text_index_vocab System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .907
sa_validate system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .909
sa_verify_password system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
sp_alter_secure_feature_key System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
sp_auth_sys_role_info System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
sp_create_secure_feature_key System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
sp_displayroles System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .915
sp_drop_secure_feature_key System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
sp_expireallpasswords System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
sp_find_top_statements system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
sp_http_listeners system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923
sp_list_mutexes_semaphores system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
sp_list_secure_feature_keys System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
sp_login_environment system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
sp_objectpermission System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
sp_proc_priv System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932
sp_property_history system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934
sp_remote_columns system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936
sp_remote_exported_keys system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .938
sp_remote_imported_keys system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940
sp_remote_primary_keys system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 942
sp_remote_tables system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
sp_servercaps system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
sp_start_listener system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
sp_stop_listener system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949
sp_sys_priv_role_info System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 950
sp_top_k_statements system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951
sp_tsql_environment system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .954
sp_use_secure_feature_key System Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .955
xp_cmdshell system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .956
xp_get_mail_error_code system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
xp_get_mail_error_text system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
xp_getenv system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
xp_msver system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
xp_read_file system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
xp_scanf system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 963
xp_sendmail system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .965
xp_sprintf system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 969
xp_startmail system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 970
xp_startsmtp system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 971

SAP IQ SQL Reference


Content INTERNAL 15
xp_stopmail system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 974
xp_stopsmtp system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
xp_write_file system procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976
7.7 SAP ASE System and Catalog Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977
SAP ASE System Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
SAP ASE Catalog Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 979

8 System Tables and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981


8.1 System Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
SYS.DUMMY Table Versus IQ_DUMMY Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .983
ISYSIQINFO System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .984
ISYSIQLOGICALSERVER System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
ISYSIQLOGINPOLICYLSINFO System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
ISYSIQLSLOGINPOLICYOPTION System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
ISYSIQLSMEMBER System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
ISYSIQLSPOLICY System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
ISYSIQLSPOLICYOPTION System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
ISYSIQMPXSERVER System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
ISYSIQMPXSERVERAGENT System Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .987
8.2 System Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
Consolidated Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
Compatibility Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 988
Alphabetical List of System Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 988

9 SQL Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1117


9.1 Common Elements in SQL Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1117
9.2 Syntax Conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1118
9.3 Statement Applicability Indicators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1119
9.4 Alphabetical List of Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1119
ALLOCATE DESCRIPTOR Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1131
ALTER AGENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1133
ALTER DATABASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1134
ALTER DBSPACE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1136
ALTER DOMAIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1141
ALTER EVENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1142
ALTER FUNCTION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1144
ALTER INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1147
ALTER LDAP SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1151
ALTER LOGICAL SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1153
ALTER LOGIN POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1155
ALTER LS POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1158
ALTER MULTIPLEX RENAME Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1160

SAP IQ SQL Reference


16 INTERNAL Content
ALTER MULTIPLEX SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1161
ALTER PROCEDURE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1163
ALTER ROLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1166
ALTER SEQUENCE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1168
ALTER SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1170
ALTER SERVICE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1173
ALTER SPATIAL REFERENCE SYSTEM Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1176
ALTER TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1181
ALTER TEXT CONFIGURATION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196
ALTER TEXT INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1199
ALTER TRIGGER statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1201
ALTER USER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1203
ALTER VIEW Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1207
BACKUP DATABASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1212
BEGIN … END Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218
BEGIN PARALLEL IQ … END PARALLEL IQ Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1221
BEGIN TRANSACTION Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1223
CALL Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1225
CASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1228
CHECKPOINT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229
CLEAR Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1230
CLOSE Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1231
COMMENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
COMMIT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1238
CONFIGURE Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1240
CONNECT Statement [ESQL] [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1241
CREATE AGENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1244
CREATE DATABASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1245
CREATE DBSPACE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1254
CREATE DOMAIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1259
CREATE EVENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1262
CREATE EXISTING TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1267
CREATE EXTERNLOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1271
CREATE FUNCTION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1273
CREATE INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294
CREATE LDAP SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1301
CREATE LOGICAL SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1305
CREATE LOGIN POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1307
CREATE LS POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1313
CREATE MESSAGE Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1315
CREATE MULTIPLEX SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1317

SAP IQ SQL Reference


Content INTERNAL 17
CREATE MUTEX statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1319
CREATE PROCEDURE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1321
CREATE ROLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1354
CREATE SCHEMA Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1357
CREATE SEMAPHORE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1358
CREATE SEQUENCE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1361
CREATE SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1363
CREATE SERVICE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1365
CREATE SPATIAL REFERENCE SYSTEM Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1368
CREATE SPATIAL UNIT OF MEASURE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1375
CREATE TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1377
CREATE TEXT CONFIGURATION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
CREATE TEXT INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1393
CREATE TRIGGER statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1395
CREATE USER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1402
CREATE VARIABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1404
CREATE VIEW Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1408
DEALLOCATE DESCRIPTOR Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1411
Declaration Section [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1412
DECLARE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1413
DECLARE CURSOR Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1415
DECLARE CURSOR Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1420
DECLARE LOCAL TEMPORARY TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1422
DELETE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1424
DELETE (Positioned) Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1427
DESCRIBE Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1429
DISCONNECT Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1432
DROP Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1433
DROP AGENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1437
DROP CONNECTION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1438
DROP DATABASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1439
DROP EXTERNLOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1441
DROP LDAP SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1443
DROP LOGICAL SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1444
DROP LOGIN POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1445
DROP LS POLICY Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1446
DROP MULTIPLEX SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1447
DROP MUTEX statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1449
DROP ROLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1450
DROP SEMAPHORE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1452
DROP SEQUENCE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1454

SAP IQ SQL Reference


18 INTERNAL Content
DROP SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1455
DROP SERVICE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1456
DROP SPATIAL REFERENCE SYSTEM Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1457
DROP SPATIAL UNIT OF MEASURE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1458
DROP STATEMENT Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1459
DROP TEXT CONFIGURATION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1460
DROP TEXT INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1462
DROP TRIGGER statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1463
DROP USER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1464
DROP VARIABLE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1466
EXECUTE Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1467
EXECUTE Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1469
EXECUTE IMMEDIATE Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1471
EXIT Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1473
FETCH Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1475
FOR Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1479
FORWARD TO Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1481
FROM Clause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1483
GET DESCRIPTOR Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1491
GOTO Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1492
GRANT CHANGE PASSWORD Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1494
GRANT CONNECT Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1496
GRANT CREATE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1498
GRANT EXECUTE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1499
GRANT INTEGRATED LOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1500
GRANT KERBEROS LOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1501
GRANT Object-Level Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1502
GRANT ROLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1504
GRANT SET USER Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1509
GRANT System Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1511
GRANT USAGE ON SEQUENCE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1528
IF Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1529
IF Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1531
INCLUDE Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1532
INSERT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1534
INSTALL JAVA Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1541
IQ UTILITIES Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544
LEAVE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1547
LOAD TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1549
LOCK MUTEX statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1570
LOCK TABLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1572

SAP IQ SQL Reference


Content INTERNAL 19
LOOP Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1576
MESSAGE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1577
NOTIFY SEMAPHORE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1580
OPEN Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1582
OUTPUT Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1585
PARAMETERS Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1589
PREPARE Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1590
PRINT Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1593
PUT Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1595
RAISERROR Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1597
READ Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1598
REFRESH TEXT INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1601
RELEASE MUTEX statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1603
RELEASE SAVEPOINT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1604
REMOVE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1605
RESIGNAL Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1607
RESTORE DATABASE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1608
RESUME Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1618
RETURN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1620
REVOKE CHANGE PASSWORD Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1621
REVOKE CONNECT Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1623
REVOKE CREATE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1624
REVOKE EXECUTE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1625
REVOKE INTEGRATED LOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1626
REVOKE KERBEROS LOGIN Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1627
REVOKE Object-Level Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1628
REVOKE ROLE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1630
REVOKE SET USER Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1633
REVOKE System Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1635
REVOKE USAGE ON SEQUENCE Privilege Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1653
ROLLBACK Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1654
ROLLBACK TO SAVEPOINT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1655
ROLLBACK TRANSACTION Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1656
SAVE TRANSACTION Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1657
SAVEPOINT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1658
SELECT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1659
SET Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1670
SET Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1673
SET CONNECTION Statement [ESQL] [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . .1675
SET DESCRIPTOR Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1676
SET OPTION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1677

SAP IQ SQL Reference


20 INTERNAL Content
SET OPTION Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1680
SET SQLCA Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1681
SETUSER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1682
SIGNAL Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1684
START DATABASE Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1685
START ENGINE Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1687
START EXTERNAL ENVIRONMENT statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1688
START JAVA Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1689
STOP DATABASE Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1690
STOP ENGINE Statement [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1691
STOP EXTERNAL ENVIRONMENT statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1692
STOP JAVA Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1694
TRIGGER EVENT Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1694
TRUNCATE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1695
TRUNCATE TEXT INDEX Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1697
UNION Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1699
UPDATE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1700
UPDATE (Positioned) Statement [ESQL] [SP]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1705
VALIDATE Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1707
VALIDATE LDAP SERVER Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1709
WAITFOR Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1713
WAITFOR SEMAPHORE statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1715
WHENEVER Statement [ESQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1717
WHILE Statement [T-SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1718

10 Database Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1720


10.1 Introduction to Database Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1720
Current Option Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1722
Scope and Duration of Database Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1723
Temporary Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1724
PUBLIC Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1724
SECURITY Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1724
SYSTEM Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1725
Delete an Option Setting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1725
Initial Option Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1726
Deprecated Database Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1727
10.2 Set a Database Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1727
10.3 General Database Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1728
Data Extraction Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1733
10.4 Transact-SQL Compatibility Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1733
Transact-SQL Option Settings for SAP ASE Compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1734
10.5 Interactive SQL Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1735

SAP IQ SQL Reference


Content INTERNAL 21
10.6 Alphabetical List of Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1736
AES_ENCRYPT_HEADER_FORMAT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1752
AFFINITY_AUTOEXCLUDE_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1753
AGGREGATION_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1754
ALLOW_NULLS_BY_DEFAULT Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1756
ALLOW_READ_CLIENT_FILE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1757
ALLOW_SNAPSHOT_VERSIONING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1758
ANSI_CLOSE_CURSORS_ON_ROLLBACK Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1759
ANSI_PERMISSIONS Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1760
ANSI_SUBSTRING Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1761
ANSI_UPDATE_CONSTRAINTS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1762
ANSINULL Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1764
ASE_BINARY_DISPLAY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1766
ASE_FUNCTION_BEHAVIOR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1767
AUDITING Option [Database]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1768
auto_commit option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1769
BASE_TABLES_IN_RLV_STORE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1771
BIT_VECTOR_PINNABLE_CACHE_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1772
BLOCKING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1773
BLOCKING_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1774
BT_PREFETCH_MAX_MISS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1775
BT_PREFETCH_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1776
BTREE_PAGE_SPLIT_PAD_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1777
CACHE_AFFINITY_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1779
CACHE_PARTITIONS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1780
CHAINED Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1781
CHECKPOINT_TIME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1782
CIS_ROWSET_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1783
CLOSE_ON_ENDTRANS Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1784
COLLECT_IQ_PERFORMANCE_STATS option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1785
CONTINUE_AFTER_RAISERROR Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1786
CONVERSION_ERROR Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1787
CONVERSION_MODE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1789
CONVERT_VARCHAR_TO_1242 Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1796
COOPERATIVE_COMMIT_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1797
COOPERATIVE_COMMITS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1798
CREATE_HG_AND_FORCE_PHYSICAL_DELETE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1799
CREATE_HG_WITH_EXACT_DISTINCTS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1800
CURSOR_WINDOW_ROWS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1801
DATE_FIRST_DAY_OF_WEEK Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1803
DATE_FORMAT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1804

SAP IQ SQL Reference


22 INTERNAL Content
DATE_ORDER Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1806
DBCC_LOG_PROGRESS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1807
DBCC_PINNABLE_CACHE_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1808
DEBUG_MESSAGES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1809
DEDICATED_TASK Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1811
DEFAULT_DBSPACE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1812
DEFAULT_DISK_STRIPING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1814
DEFAULT_HAVING_SELECTIVITY_PPM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1815
DEFAULT_ISQL_ENCODING Option [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1816
DEFAULT_KB_PER_STRIPE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1817
DEFAULT_LIKE_MATCH_SELECTIVITY_PPM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1818
DEFAULT_LIKE_RANGE_SELECTIVITY_PPM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1819
DEFAULT_PROXY_TABLE_ROW_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1820
DEFAULT_TABLE_UDF_ROW_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1821
DELAYED_COMMIT_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1822
DELAYED_COMMITS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1823
DISABLE_RI_CHECK Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1824
DIVIDE_BY_ZERO_ERROR Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1825
DML_OPTIONS90 Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1826
DQP_ENABLED Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1827
(Deprecated) DQP_ENABLED_OVER_NETWORK Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1829
DQP_OPTIONS13 Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1830
DQP_TCP_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1832
EARLY_PREDICATE_EXECUTION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1833
ENABLE_ASYNC_IO Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1834
ENABLE_LOB_VARIABLES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1835
EXTENDED_JOIN_SYNTAX Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1836
FILE_PREALLOCATE_SAMPLING_THRESHOLD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1837
FLOATING_POINT_ACCUMULATOR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1838
FORCE_DROP Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1840
FORCE_NO_SCROLL_CURSORS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1841
FORCE_UPDATABLE_CURSORS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1842
FP_LOOKUP_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1843
FP_LOOKUP_SIZE_PPM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1844
FP_NBIT_AUTOSIZE_LIMIT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1845
FP_NBIT_ENFORCE_LIMITS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1847
FP_NBIT_IQ15_COMPATIBILITY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1849
FP_NBIT_LOOKUP_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1850
FP_NBIT_ROLLOVER_MAX_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1852
FP_PREDICATE_WORKUNIT_PAGES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1854
FPL_EXPRESSION_MEMORY_KB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1855

SAP IQ SQL Reference


Content INTERNAL 23
GARRAY_FILL_FACTOR_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1856
GARRAY_INSERT_PREFETCH_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1857
GARRAY_PAGE_SPLIT_PAD_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1858
GARRAY_RO_PREFETCH_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1859
HASH_PINNABLE_CACHE_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1860
HASH_THRASHING_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1861
HG_DELETE_METHOD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1862
HG_SEARCH_RANGE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1864
HTTP_SESSION_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1865
IDENTITY_ENFORCE_UNIQUENESS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1866
IDENTITY_INSERT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1867
IN_SUBQUERY_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1868
INDEX_ADVISOR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1870
INDEX_ADVISOR_MAX_ROWS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1872
INDEX_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1873
INFER_SUBQUERY_PREDICATES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1875
IQ_LOG_MAX_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1876
IQ_LOG_THRESHOLD_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1877
IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL Option. . . . . . . . . . . . . . . . . . . . . 1878
IQ_POINT_IN_TIME_RECOVERY_LOGGING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1879
IQ_SYSTEM_MAIN_ALLOCATION_RATIO Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1880
IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1881
IQGOVERN_MAX_PRIORITY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1882
IQGOVERN_PRIORITY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1883
IQGOVERN_PRIORITY_TIME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1884
ISOLATION_LEVEL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1885
JAVA_LOCATION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1886
JAVA_VM_OPTIONS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1887
JOIN_EXPANSION_FACTOR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1888
JOIN_OPTIMIZATION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1889
JOIN_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1891
JOIN_SIMPLIFICATION_THRESHOLD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1893
LF_BITMAP_CACHE_KB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1894
LOAD_ZEROLENGTH_ASNULL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1895
LOG_CONNECT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1897
LOG_CURSOR_OPERATIONS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1898
LOG_DEADLOCKS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1899
LOGIN_MODE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1900
LOGIN_PROCEDURE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1901
MAIN_RESERVED_DBSPACE_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1902
MAX_CARTESIAN_RESULT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1903

SAP IQ SQL Reference


24 INTERNAL Content
MAX_CLIENT_NUMERIC_PRECISION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1904
MAX_CLIENT_NUMERIC_SCALE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1906
MAX_CUBE_RESULT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1907
MAX_CURSOR_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1908
MAX_HASH_ROWS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1909
MAX_IQ_THREADS_PER_CONNECTION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1910
MAX_IQ_THREADS_PER_TEAM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1911
MAX_JOIN_ENUMERATION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1912
MAX_PARTITIONED_HASH_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1914
MAX_PREFIX_PER_CONTAINS_PHRASE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1915
MAX_QUERY_PARALLELISM Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1916
MAX_QUERY_TIME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1917
MAX_RV_REMOTE_TRANSFER_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1918
MAX_STATEMENT_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1919
MAX_TEMP_SPACE_PER_CONNECTION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1920
MIN_NUMERIC_DIVISION_SCALE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1922
min_password_length option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1922
MIN_ROLE_ADMINS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1924
MINIMIZE_STORAGE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1925
MONITOR_OUTPUT_DIRECTORY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1926
MPX_AUTOEXCLUDE_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1928
MPX_DAS_COMMUNICATION_ENABLED Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1929
MPX_GTR_ENABLED Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1930
MPX_HEARTBEAT_FREQUENCY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1931
MPX_IDLE_CONNECTION_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1931
MPX_LIVENESS_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1932
MPX_MAX_CONNECTION_POOL_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1933
MPX_MAX_UNUSED_POOL_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1935
MPX_MIPC_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1935
MPX_WORK_UNIT_TIMEOUT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1936
NEAREST_CENTURY Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1938
NOEXEC Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1939
NON_ANSI_NULL_VARCHAR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1940
NON_KEYWORDS Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1941
NOTIFY_MODULUS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1942
ODBC_DISTINGUISH_CHAR_AND_VARCHAR Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1943
ON_CHARSET_CONVERSION_FAILURE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1944
ON_ERROR Option [Interactive SQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1945
ON_TSQL_ERROR Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1946
POST_LOGIN_PROCEDURE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1947
PRECISION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1949

SAP IQ SQL Reference


Content INTERNAL 25
PREFETCH Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1950
PREFETCH_BUFFER_LIMIT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1951
PREFETCH_BUFFER_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1952
PREFETCH_FP_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1953
PREFETCH_GARRAY_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1954
PREFETCH_HASH_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1955
PREFETCH_LOB_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1956
PREFETCH_SORT_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1957
PREFETCH_TEXTPOST_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1958
PRESERVE_SOURCE_FORMAT Option [Database]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1959
PROGRESS_MESSAGES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1960
QUERY_DETAIL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1962
QUERY_NAME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1963
QUERY_PLAN Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1964
QUERY_PLAN_AFTER_RUN Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1965
QUERY_PLAN_AS_HTML Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1966
QUERY_PLAN_AS_HTML_DIRECTORY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1969
QUERY_PLAN_MIN_TIME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1970
QUERY_PLAN_TEXT_ACCESS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1971
QUERY_PLAN_TEXT_CACHING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1973
QUERY_ROWS_RETURNED_LIMIT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1974
QUERY_TEMP_SPACE_LIMIT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1975
QUERY_TIMING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1976
QUOTED_IDENTIFIER Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1977
RECOVERY_TIME Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1978
reserved_connections option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1979
RESERVED_KEYWORDS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1981
RETURN_DATE_TIME_AS_STRING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1982
REVERT_TO_V15_OPTIMIZER Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1983
ROUND_TO_EVEN Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1984
ROW_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1986
RV_AUTO_MERGE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1987
RV_AUTO_MERGE_EVAL_INTERVAL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1988
RV_BLOCK_SIZE_ALLOCATION_STRATEGY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1989
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . .1991
RV_FIX_DATA_BLOCKSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1992
RV_INITIAL_FIX_DATA_BLOCKSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1994
RV_MAX_ACTIVE_SUBFRAGMENT_COUNT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1995
RV_MAX_LOOKUP_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1996
RV_MAX_TOKEN Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1997
RV_MERGE_NODE_MEMSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1999

SAP IQ SQL Reference


26 INTERNAL Content
RV_MERGE_TABLE_COMMIT_AGE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2000
RV_MERGE_TABLE_DELPERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2001
RV_MERGE_TABLE_MEMPERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2002
RV_MERGE_TABLE_NUMROWS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2003
RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . 2004
RV_RESERVED_DBSPACE_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2005
RV_VAR_DATA_BLOCKSIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2006
SCALE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2008
SIGNIFICANTDIGITSFORDOUBLEEQUALITY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2009
SNAPSHOT_VERSIONING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2010
SORT_COLLATION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2011
SORT_PINNABLE_CACHE_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2013
SQL_FLAGGER_ERROR_LEVEL Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2014
SQL_FLAGGER_WARNING_LEVEL Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2015
STRING_RTRUNCATION Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2016
SUBQUERY_CACHING_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2017
SUBQUERY_FLATTENING_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2019
SUBQUERY_FLATTENING_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2020
SUBQUERY_PLACEMENT_PREFERENCE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2021
SUPPRESS_TDS_DEBUGGING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2022
SWEEPER_THREADS_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2023
TABLE_UDF_ROW_BLOCK_CHUNK_SIZE_KB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2024
TDS_EMPTY_STRING_IS_NULL Option [Database]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2025
TEMP_EXTRACT_APPEND Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2026
TEMP_EXTRACT_BINARY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2027
TEMP_EXTRACT_COLUMN_DELIMITER Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2029
TEMP_EXTRACT_COMPRESS Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2030
TEMP_EXTRACT_DIRECTORY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2031
TEMP_EXTRACT_ESCAPE_QUOTES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2032
TEMP_EXTRACT_FILE_EXTENSION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2034
TEMP_EXTRACT_FILE_PREFIX Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2035
TEMP_EXTRACT_GZ_COMPRESSION_LEVEL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2036
TEMP_EXTRACT_LENGTH_PREFIX Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2038
TEMP_EXTRACT_MAX_PARALLEL_DEGREE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2039
TEMP_EXTRACT_NAMEn Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2040
TEMP_EXTRACT_NULL_AS_EMPTY Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2042
TEMP_EXTRACT_NULL_AS_ZERO Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2043
TEMP_EXTRACT_QUOTE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2044
TEMP_EXTRACT_QUOTES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2046
TEMP_EXTRACT_QUOTES_ALL Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2047
TEMP_EXTRACT_ROW_DELIMITER Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2048

SAP IQ SQL Reference


Content INTERNAL 27
TEMP_EXTRACT_SIZE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2049
TEMP_EXTRACT_SIZEn Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2050
TEMP_EXTRACT_SWAP Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2052
TEMP_EXTRACT_VARYING Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2053
TEMP_RESERVED_DBSPACE_MB Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2054
TEMP_SPACE_LIMIT_CHECK Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2055
TEXT_DELETE_METHOD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2057
TIME_FORMAT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2058
TIMESTAMP_FORMAT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2059
TOP_NSORT_CUTOFF_PAGES Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2061
TRIM_PARTIAL_MBC Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2062
TRUSTED_CERTIFICATES_FILE Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2063
TSQL_VARIABLES Option [TSQL]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2064
USER_RESOURCE_RESERVATION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2065
VERIFY_PASSWORD_FUNCTION Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2066
WAIT_FOR_COMMIT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2068
WASH_AREA_BUFFERS_PERCENT Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2069
WD_DELETE_METHOD Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2071

SAP IQ SQL Reference


28 INTERNAL Content
1 SAP IQ SQL Reference

This book provides SAP IQ users with reference material for SQL statements, language elements, data types,
functions, system procedures, system tables, SQL statements, and database options.

Other books provide more context on how to perform particular tasks. Use this book to get information about
SQL syntax, parameters, and options. For command line utility start-up parameters, see the SAP IQ Utility
Reference.

SAP IQ SQL Reference


SAP IQ SQL Reference INTERNAL 29
2 SQL Language Elements

These topics provide detailed descriptions of the language elements and conventions of SAP IQ SQL.

In this section:

Keywords [page 31]


Each SQL statement contains one or more keywords.

Identifiers [page 34]


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

Mutexes and semaphores [page 36]


Use mutexes and semaphores in your application logic to achieve locking behavior and control and
communicate the availability of resources.

Strings [page 38]


Strings are either literal strings, or expressions with CHAR or VARCHAR data types.

Expressions [page 40]


Expressions are formed from several different kinds of elements, such as constants, column names,
SQL operators, and subqueries.

Search Conditions [page 57]


Conditions are used to choose a subset of the rows from a table, or in a control statement such as an
IF statement to determine control of flow.

Special Values [page 84]


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

%TYPE and %ROWTYPE attributes [page 93]


In addition to explicitly setting the data type for an object, you can also set the data type by specifying
the %TYPE and %ROWTYPE attributes.

SQL variables [page 101]


The supported variables can be grouped by scope: connection, database, and global.

Variables [page 103]


SAP IQ supports local variables, connection-level variables, and global variables.

Comments [page 111]


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

NULL Value [page 112]


Use NULL to specify a value that is unknown, missing, or not applicable.

SAP IQ SQL Reference


30 INTERNAL SQL Language Elements
2.1 Keywords

Each SQL statement contains one or more keywords.

SQL is not case-sensitive to keywords, but throughout the SAP IQ documentation, keywords are indicated in
uppercase. For example, in this statement, SELECT and FROM are keywords:

SELECT *
FROM Employees

The following statements are equivalent to the one above:

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

In this section:

Reserved Words [page 31]


Some keywords in SQL are also reserved words.

2.1.1 Reserved Words

Some keywords in SQL are also reserved words.

To use a reserved word in a SQL statement as an identifier, you enclose the word in double quotes. Many, but
not all, of the keywords that appear in SQL statements are reserved words. For example, you must use the
following syntax to retrieve the contents of a table named SELECT:

SELECT *
FROM "SELECT"

If you are using Embedded SQL, you can use the database library function sql_needs_quotes to determine
whether a string requires quotation marks. A string requires quotes if it is a reserved word or if it contains a
character not ordinarily allowed in an identifier.

This table lists the SQL reserved words in SAP IQ. Because SQL is not case-sensitive with respect to keywords,
each of the words in this table may appear in uppercase, lowercase, or any combination of the two. All strings
that differ only in capitalization from these words are reserved words.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 31
● add ● foreign ● reference
● all ● forward ● references
● alter ● from ● refresh
● and ● full ● release
● any ● goto ● remote
● array ● grant ● remove
● as ● group ● rename
● asc ● having ● reorganize
● attach ● holdlock ● resource
● backup ● identified ● restore
● begin ● if ● restrict
● between ● in ● return
● bigint ● index ● revoke
● binary ● inner ● right
● bit ● inout ● rollback
● bottom ● insensitive ● rollup
● break ● insert ● row
● by ● inserting ● rowtype
● call ● install ● save
● capability ● instead ● savepoint
● cascade ● int ● scroll
● case ● integer ● select
● cast ● integrated ● sensitive
● char ● intersect ● session
● char_convert ● into ● set
● character ● is ● setuser
● check ● isolation ● share
● checkpoint ● join ● smallint
● close ● json ● some
● comment ● kerberos ● spatial
● commit ● key ● sqlcode
● compressed ● lateral ● sqlstate
● conflict ● left ● start
● connect ● like ● stop
● constraint ● limit ● subtrans
● contains ● lock ● subtransaction
● continue ● login ● synchronize
● convert ● long ● table
● create ● match ● temporary
● cross ● membership ● then
● cube ● merge ● time
● current ● message ● timestamp
● current_timestamp ● mode ● tinyint

SAP IQ SQL Reference


32 INTERNAL SQL Language Elements
● current_user ● modify ● to
● cursor ● natural ● top
● date ● nchar ● tran
● datetimeoffset ● new ● treat
● dbspace ● no ● trigger
● deallocate ● noholdlock ● truncate
● dec ● not ● tsequal
● decimal ● notify ● unbounded
● declare ● null ● union
● default ● numeric ● unique
● delete ● nvarchar ● uniqueidentifier
● deleting ● of ● unknown
● desc ● off ● unnest
● detach ● on ● unsigned
● distinct ● open ● update
● do ● openstring ● updating
● double ● openxml ● user
● drop ● option ● using
● dynamic ● options ● validate
● else ● or ● values
● elseif ● order ● varbinary
● encrypted ● others ● varbit
● end ● out ● varchar
● endif ● outer ● variable
● escape ● over ● varray
● except ● passthrough ● varying
● exception ● precision ● view
● exec ● prepare ● wait
● execute ● primary ● waitfor
● existing ● print ● when
● exists ● privileges ● where
● externlogin ● proc ● while
● fetch ● procedure ● window
● first ● publication ● with
● float ● raiserror ● within
● for ● readtext ● work
● force ● real ● writetext
● xml

Related Information

Identifiers [page 34]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 33
The quoted_identifier Option [page 55]
Subqueries in Search Conditions [page 62]
Column Names in Expressions [page 42]

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

Identifiers have a maximum length of 128 bytes. They must be enclosed in double quotes or square brackets if
any of these conditions are true:

● The identifier contains spaces.


● The first character of the identifier is not an alphabetic character (as defined below).
● The identifier contains a reserved word.
● The identifier contains characters other than alphabetic characters and digits.
Alphabetic characters include the alphabet, as well as the underscore character (_), at sign (@), number
sign (#), and dollar sign ($). The database collation sequence dictates which characters are considered
alphabetic or digit characters.

These characters are not allowed inside an identifier:

● Double quotes (")


● Control characters (any character less than 0x20)
● Backslashes (/)
● Square bracket, open ([)
● Square bracket, close (])
● Back quote/grave accent (`)

You can represent an apostrophe/single quote (') inside an identifier by following it with another apostrophe.

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 always use square brackets 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.

Limitations

Identifiers have the following limitations:

● Table names cannot contain double quotes.


● User names cannot contain double quote or semi-colon characters (single quote characters are allowed).
● Database names cannot contain double quote, single quote, and semi-colon characters.
● User names and database names cannot start or end with a space.
● Dbspace names are always case-insensitive, regardless of the CREATE DATABASE...CASE IGNORE or CASE
RESPECT specification.

SAP IQ SQL Reference


34 INTERNAL SQL Language Elements
Database server naming restrictions exist when using the -n start_iq server option.

Examples

The following are all valid identifiers:

Surname
"Surname"
[Surname]
SomeBigName
"Client Number"

In this section:

Database Server Naming Restrictions [page 35]


If you use the -n switch in start_iq [ <server-options> ], certain naming restrictions apply.

Related Information

Reserved Words [page 31]


The quoted_identifier Option [page 55]
Subqueries in Search Conditions [page 62]
Column Names in Expressions [page 42]

2.2.1 Database Server Naming Restrictions

If you use the -n switch in start_iq [ <server-options> ], certain naming restrictions apply.

No character set is conversion performed on the server name. If the client character set and the database
server character set differ, using extended characters in the server name can cause the server to not be found.
If clients and servers run on different operating systems or locales, use 7-bit ASCII characters in the server
name.

Database server names must be valid identifiers. Long database server names are truncated to different
lengths depending on the protocol. Database server names cannot have the following properties:

● Begin with white space, single quotes, or double quotes.


● End with white space.
● Contain semicolons.
● Exceed 128 bytes.

The server name specifies the name to be used on client application connection strings or profiles. Running
multiple database servers with the same name is not recommended.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 35
2.3 Mutexes and semaphores
Use mutexes and semaphores in your application logic to achieve locking behavior and control and
communicate the availability of resources.

Mutexes and semaphores are locking and signaling mechanisms that control the availability or use of a shared
resource such as an external library or a procedure. You can include mutexes and semaphores to achieve the
type of locking behavior your application requires. Choosing whether to use mutexes or semaphores depends
on the requirements of your application.

Mutexes provide the application with a concurrency control mechanism; for example, they can be used to allow
only one connection at a time to execute a critical section in a stored procedure, user-defined function, trigger,
or event. Mutexes can also lock an application resource that does not directly correspond to a database object.
Semaphores provide support for producer/consumer application logic in the database or for access to limited
application resources.

Mutexes and semaphores benefit from the same deadlock detection as database row and table locks.

UPDATE ANY MUTEX SEMAPHORE allows locking/releasing of mutexes and notifying/waiting for semaphores,
CREATE ANY MUTEX SEMAPHORE is necessary to create/replace, and DROP ANY MUTEX SEMAPHORE is
necessary to drop/replace. To have a finer level of control on who can update a mutex or semaphore, you can
grant privileges on the objects they are used in instead. For example, you can grant EXECUTE privilege on a
system procedure that contains a mutex.

More about mutexes

A mutex is a lock and release mechanism that limits the availability of a critical section of a shared resource
such as an external library or a stored procedure. Locking and unlocking a mutex is achieved by executing
LOCK MUTEX and RELEASE MUTEX statements, respectively.

The scope of a mutex can be either transaction or connection. In transaction-scope mutexes, the lock is held
until the end of the transaction that has locked the mutex. In connection-scope mutexes, the lock is held until a
RELEASE MUTEX statement is executed by the connection or until the connection terminates.

The mode of a mutex can be either exclusive or shared. In exclusive mode, only the transaction or connection
holding the lock can use the resource. In shared mode, multiple transactions or connections can lock the
mutex.

You can recursively lock a mutex (that is, you can nest LOCK MUTEX statements for the same mutex inside
your code). However, with connection-scope mutexes, an equal number of RELEASE MUTEX statements are
required to release the mutex.

If a connection locks a mutex in shared mode, and then (recursively) locks it again in exclusive mode, then the
lock remains held in exclusive mode until it is released twice, or until the end of the transaction.

Here is a simple scenario showing how you can use a mutex to protect a critical section of a stored procedure.
In this scenario, the critical section can only be executed by one connection at a time (but can span multiple
transactions):

1. The following statement creates a new mutex to protect the critical section:

CREATE MUTEX protect_my_cr_section SCOPE CONNECTION;

SAP IQ SQL Reference


36 INTERNAL SQL Language Elements
2. The following statement locks the critical section in exclusive mode so that no other connection can access
it:

LOCK MUTEX protect_my_cr_section IN EXCLUSIVE MODE;

3. The following statement releases the critical section:

RELEASE MUTEX protect_my_cr_section;

4. The following statement removes the mutex when the critical section no longer needs protection:

DROP MUTEX protect_my_cr_section;

More about semaphores

A semaphore is a signaling mechanism that uses a counter to communicate the availability of a resource.
Incrementing and decrementing the semaphore counter is achieved by executing NOTIFY SEMAPHORE and
WAITFOR SEMAPHORE statements, respectively. Use semaphores in a resource availability model or a in a
producer-consumer model. Regardless of model, a semaphore cannot go below 0. That way, the counter is
used to limit the availability of the resource (a license, in this example).

The resource availability model is when a counter is used to limit the availability of a resource. For example,
suppose you have a license that restricts application use to 10 users at a time. You set the semaphore counter
to 10 at create time using the START WITH clause. When a user logs in, a WAITFOR SEMAPHORE statement is
executed, and the count is decremented by one. If the count is 0, then the user waits for up to the specified
timeout period. If the counter goes above 0 before the timeout, then they log in. If not, then the users login
attempt times out. When the user logs out, a NOTIFY SEMAPHORE statement is executed, incrementing the
count by one. Each time a user logs in, the count is decremented; each time they log out, the count is
incremented.

The producer-consumer model is when a counter is used to signal the availability of a resource. For example,
suppose there is a procedure that consumes what another procedure produces. The consumer executes a
WAITFOR SEMAPHORE statement and waits for something to process. When the producer has created output,
it executes a NOTIFY SEMAPHORE statement to signal that work is available. This statement increments the
counter associated with the semaphore. When the waiting consumer gets the work, the counter is
decremented. In the producer-consumer model, the counter cannot go below 0, but it can go as high as the
producers increment the counter.

Here is a simple scenario showing how you can use a semaphore to control the number of licenses for an
application. The scenario assumes there is a total of three licenses available, and that each successful log in to
the application consumes one license:

1. The following statement creates a new semaphore with the number of licenses specified as the initial
count:

CREATE SEMAPHORE license_counter START WITH 3;

2. The following statement obtains a license using the license_counter semaphore:

WAITFOR SEMAPHORE license_counter;

3. The following statement releases the license:

NOTIFY SEMAPHORE license_counter INCREMENT BY 1;

SAP IQ SQL Reference


SQL Language Elements INTERNAL 37
4. The following statement removes the semaphore when the application no longer needs to be limited by the
license:

DROP SEMAPHORE license_counter;

So, a common way to use semaphores in a producer-consumer model might look something like this:

CREATE SEMAPHORE producer_counter;


CREATE SEMAPHORE consumer_counter START WITH 100;
CREATE PROCEDURE DBA.MyProducer( )
BEGIN
WHILE 1 = 1 LOOP
WAITFOR SEMAPHORE consumer_counter;
-- produce some data and put it somewhere (e.g. a table)
NOTIFY SEMAPHORE producer_counter;
END LOOP
END
go
CREATE PROCEDURE DBA.MyConsumer( )
BEGIN
WHILE 1 = 1 LOOP
WAITFOR SEMAPHORE producer_counter;
-- read the next bit of data and do something with it
NOTIFY SEMAPHORE consumer_counter;
END LOOP
END
go

In this example, MyProducer and MyConsumer run in different connections. MyProducer just fetches data and
can get at most 100 iterations ahead of MyConsumer. If MyConsumer goes faster than MyProducer,
producer_counter will eventually reach 0. At that point, MyConsumer will block until MyProducer can make
more data. If MyProducer goes faster than MyConsumer, consumer_counter will eventually reach 0. At that
point, MyProducer will block until MyConsumer can consume some data.

2.4 Strings

Strings are either literal strings, or expressions with CHAR or VARCHAR data types.

A literal string is any sequence of characters enclosed in apostrophes ('single quotes'). A SQL variable of
character data type can hold a string. This is a simple example of a literal string:

'This is a string.'

An expression with a CHAR data type might be a built-in or user-defined function, or one of the many other
kinds of expressions available.

SAP IQ SQL Reference


38 INTERNAL SQL Language Elements
Special Characters in Strings

Represent special characters in strings by escape sequences, as follows:

● To represent an apostrophe inside a string, use two apostrophes ('') in a row. For example:

'John''s database'

● To represent a newline character, use a backslash followed by n (\n). For example:

'First line:\nSecond line:'

● To represent a backslash character, use two backslashes in a row (\\). For example:

'c:\\temp'

● Hexadecimal escape sequences can be used for any character, printable or not. A hexadecimal escape
sequence is a backslash followed by an x followed by two hexadecimal digits (for example, \x6d represents
the letter m). For example:

'\x00\x01\x02\x03'

Compatibility

For compatibility with SAP Adaptive Server Enterprise, you can set the QUOTED_IDENTIFIER database option
to OFF. With this setting, you can also use double quotes to mark the beginning and end of strings. The option
is ON by default.

Related Information

Comparison Conditions [page 59]


Expressions [page 40]
NULL Value [page 112]
Search Conditions [page 57]
Three-Valued Logic [page 60]
SQL Operators [page 44]
Subqueries in Search Conditions [page 62]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 39
2.5 Expressions

Expressions are formed from several different kinds of elements, such as constants, column names, SQL
operators, and subqueries.

 Syntax

expression:
<case-expression>
| <constant>
| [ <correlation-name>. ] <column-name >[ <java-ref> ]
| - <expression>
| <expression operator> <expression>
| ( <expression> )
| <function-name> ( <expression>, … )
| <if-expression>
| [ <java-package-name>. ] <java-class-name java-ref>
| ( <subquery> )
| <variable-name> [ <java-ref> ]

<case-expression> ::=
{ CASE <search-condition>
... WHEN <expression> THEN <expression> [ , … ]
... [ ELSE <expression> ]
END
| CASE
... WHEN <search-condition> THEN <expression> [ , … ]
... [ ELSE <expression> ]
END }

<constant> ::=
{ <integer> | <number> | '<string>'
| <special-constant> | <host-variable> }

<special-constant> ::=
{ CURRENT { DATE | TIME | TIMESTAMP | USER }
| LAST USER
| NULL
| SQLCODE
| SQLSTATE }

<if-expression> ::=
IF <condition>
... THEN <expression>
... [ ELSE <expression> ]
ENDIF

<java-ref> ::=
{ .<field-name> [ <java-ref> ]
| >> <field-name> [ <java-ref> ]
| .<method-name> ( [ <expression> ] [ , … ] ) [ <java-ref> ]
| >> <method-name> ( [ <expression >] [ , … ] ) [ <java-ref> ] }

<operator> ::=
{ + | - | * | / | || | % }

SAP IQ SQL Reference


40 INTERNAL SQL Language Elements
Remarks

Anywhere

Authorization

Must be connected to the database.

Side Effects

None.

Compatibility

● The IF condition is not supported in SAP Adaptive Server Enterprise.


● JAVA expressions are not currently supported in SAP ASE.
● For other differences, see the separate descriptions of each class of expression, in the following sections.

In this section:

Constants in Expressions [page 42]


Constants are numbers or strings.

Column Names in Expressions [page 42]


A column name is an identifier preceded by an optional correlation name. A correlation name is usually
a table name.

Subqueries in Expressions [page 43]


A subquery is a SELECT statement enclosed in parentheses. The SELECT statement can contain one
and only one select list item. When used as an expression, a scalar subquery is allowed to return only
zero or one value.

SQL Operators [page 44]


These topics describe the arithmetic, string, and bitwise operators available in SAP IQ.

IF Expressions [page 51]


The IF expression provides IF-THEN-ELSE SQL expressions.

CASE Expressions [page 52]


The CASE expression provides conditional SQL expressions.

Compatibility of Expressions and Constants [page 53]


These topics describe the compatibility of expressions and constants between SAP Adaptive Server
Enterprise and SAP IQ.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 41
Related Information

Comparison Conditions [page 59]


NULL Value [page 112]
Search Conditions [page 57]
Strings [page 38]
Three-Valued Logic [page 60]
SQL Operators [page 44]
Subqueries in Search Conditions [page 62]
Special Values [page 84]
CASE Statement Support [page 183]

2.5.1 Constants in Expressions

Constants are numbers or strings.

String constants are enclosed in apostrophes. An apostrophe is represented inside the string by two
apostrophes in a row.

Parent topic: Expressions [page 40]

Related Information

Column Names in Expressions [page 42]


Subqueries in Expressions [page 43]
SQL Operators [page 44]
IF Expressions [page 51]
CASE Expressions [page 52]
Compatibility of Expressions and Constants [page 53]

2.5.2 Column Names in Expressions

A column name is an identifier preceded by an optional correlation name. A correlation name is usually a table
name.

If a column name has characters other than letters, digits, and underscores, the name must be surrounded by
quotation marks (“”). For example, the following are valid column names:

Employees.Surname
City
"StartDate"

SAP IQ SQL Reference


42 INTERNAL SQL Language Elements
Parent topic: Expressions [page 40]

Related Information

Constants in Expressions [page 42]


Subqueries in Expressions [page 43]
SQL Operators [page 44]
IF Expressions [page 51]
CASE Expressions [page 52]
Compatibility of Expressions and Constants [page 53]
Subqueries in Search Conditions [page 62]
Reserved Words [page 31]
Identifiers [page 34]

2.5.3 Subqueries in Expressions

A subquery is a SELECT statement enclosed in parentheses. The SELECT statement can contain one and only
one select list item. When used as an expression, a scalar subquery is allowed to return only zero or one value.

Within the SELECT list of the top level SELECT, or in the SET clause of an UPDATE statement, you can use a
scalar subquery anywhere that you can use a column name. However, the subquery cannot appear inside a
conditional expression:

● CASE
● IF
● NULLIF
● ARGN
● COALESCE
● ISNULL

For example, the following statement returns the number of employees in each department, grouped by
department name:

SELECT DepartmentName, COUNT(*), ‘out of’,


(SELECT COUNT(*) FROM Employees)
FROM Departments AS D, Employees AS E
WHERE D.DepartmentID = E.DepartmentID
GROUP BY DepartmentName;

Parent topic: Expressions [page 40]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 43
Related Information

Constants in Expressions [page 42]


Column Names in Expressions [page 42]
SQL Operators [page 44]
IF Expressions [page 51]
CASE Expressions [page 52]
Compatibility of Expressions and Constants [page 53]

2.5.4 SQL Operators

These topics describe the arithmetic, string, and bitwise operators available in SAP IQ.

The normal precedence of operations applies. Expressions in parentheses are evaluated first; then
multiplication and division before addition and subtraction. String concatenation occurs after addition and
subtraction.

In this section:

Arithmetic Operators [page 45]


These arithmetic operators are available in SAP IQ.

String Operators [page 46]


These string operators are available in SAP IQ.

Bitwise Operators [page 46]


You can use these bitwise operators on all unscaled integer data types, in both SAP IQ and SAP
Adaptive Server Enterprise.

Join Operators [page 50]


The Transact-SQL outer join operators *= and =* are supported in SAP IQ, in addition to the ISO/ANSI
SQL join syntax using a table expression in the FROM clause.

Operator Precedence [page 50]


Follow this recommendation to make the order of operation explicit.

Parent topic: Expressions [page 40]

Related Information

Constants in Expressions [page 42]


Column Names in Expressions [page 42]
Subqueries in Expressions [page 43]
IF Expressions [page 51]
CASE Expressions [page 52]
Compatibility of Expressions and Constants [page 53]

SAP IQ SQL Reference


44 INTERNAL SQL Language Elements
Comparison Conditions [page 59]
Expressions [page 40]
NULL Value [page 112]
Search Conditions [page 57]
Strings [page 38]
Three-Valued Logic [page 60]

2.5.4.1 Arithmetic Operators

These arithmetic operators are available in SAP IQ.

Operator Description

<expression> + Addition. If either expression is the NULL value, the result is the NULL value.
<expression>

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

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

<expression> * Multiplication. If either expression is the NULL value, the result is the NULL value.
<expression>

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

<expression> % Modulo finds the integer remainder after a division involving two whole numbers. For
<expression> example, 21 % 11 = 10 because 21 divided by 11 equals 1 with a remainder of 10.

Parent topic: SQL Operators [page 44]

Related Information

String Operators [page 46]


Bitwise Operators [page 46]
Join Operators [page 50]
Operator Precedence [page 50]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 45
2.5.4.2 String Operators

These string operators are available in SAP IQ.

Operator Description

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

<expression> + Alternative string concatenation. When using the + concatenation operator, you must en­
<expression> sure the operands are explicitly set to character data types rather than relying on implicit
data conversion.

The result data type of a string concatenation operator is a LONG VARCHAR. If you use string concatenation
operators in a SELECT INTO statement, you must have an Unstructured Data Analytics Option license or use
CAST and set LEFT to the correct data type and size.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. The || operator is the ISO/ANSI SQL string concatenation operator.
● SAP Database Products – The + operator is supported by SAP Adaptive Server Enterprise.

Parent topic: SQL Operators [page 44]

Related Information

Arithmetic Operators [page 45]


Bitwise Operators [page 46]
Join Operators [page 50]
Operator Precedence [page 50]
REVERSE Function [String] [page 493]

2.5.4.3 Bitwise Operators

You can use these bitwise operators on all unscaled integer data types, in both SAP IQ and SAP Adaptive Server
Enterprise.

Operator Description

& AND

| OR

SAP IQ SQL Reference


46 INTERNAL SQL Language Elements
Operator Description

^ EXCLUSIVE OR

~ NOT

In this section:

The AND Operator (&) [page 47]


The AND operator compares 2 bits. If they are both 1, the result is 1.

Bitwise OR ( | ) [page 48]


The OR operator compares 2 bits. If one or the other bit is 1, the result is 1.

EXCLUSIVE OR (^) [page 48]


The EXCLUSIVE OR operator results in a 1 when either, but not both, of its two operands is 1.

NOT (~) [page 49]


The NOT operator is a unary operator that returns the inverse of its operand.

Parent topic: SQL Operators [page 44]

Related Information

Arithmetic Operators [page 45]


String Operators [page 46]
Join Operators [page 50]
Operator Precedence [page 50]

2.5.4.3.1 The AND Operator (&)

The AND operator compares 2 bits. If they are both 1, the result is 1.

Bit 1 Bit 2 Bit 1 & Bit 2

0 0 0

0 1 0

1 0 0

1 1 1

Parent topic: Bitwise Operators [page 46]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 47
Related Information

Bitwise OR ( | ) [page 48]


EXCLUSIVE OR (^) [page 48]
NOT (~) [page 49]

2.5.4.3.2 Bitwise OR ( | )

The OR operator compares 2 bits. If one or the other bit is 1, the result is 1.

Bit 1 Bit 2 Bit 1 | Bit 2

0 0 0

0 1 1

1 0 1

1 1 1

Parent topic: Bitwise Operators [page 46]

Related Information

The AND Operator (&) [page 47]


EXCLUSIVE OR (^) [page 48]
NOT (~) [page 49]

2.5.4.3.3 EXCLUSIVE OR (^)

The EXCLUSIVE OR operator results in a 1 when either, but not both, of its two operands is 1.

Bit 1 Bit 2 Bit 1 ^Bit 2

0 0 0

0 1 1

1 0 1

SAP IQ SQL Reference


48 INTERNAL SQL Language Elements
Bit 1 Bit 2 Bit 1 ^Bit 2

1 1 0

Parent topic: Bitwise Operators [page 46]

Related Information

The AND Operator (&) [page 47]


Bitwise OR ( | ) [page 48]
NOT (~) [page 49]

2.5.4.3.4 NOT (~)

The NOT operator is a unary operator that returns the inverse of its operand.

Bit ~ Bit

1 0

0 1

Parent topic: Bitwise Operators [page 46]

Related Information

The AND Operator (&) [page 47]


Bitwise OR ( | ) [page 48]
EXCLUSIVE OR (^) [page 48]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 49
2.5.4.4 Join Operators

The Transact-SQL outer join operators *= and =* are supported in SAP IQ, in addition to the ISO/ANSI SQL join
syntax using a table expression in the FROM clause.

Compatibility

● Modulo – The default value is OFF for new databases.


● String concatenation – When you are using the + concatenation operator in SAP IQ, ensure the operands
are explicitly set to strings rather than relying on implicit data conversion. For example, the following query
returns the integer value 579:

SELECT 123 + 456

The following query, on the other hand, returns the character string 123456:

SELECT '123' + '456'

You can use the CAST or CONVERT function to explicitly convert data types.

 Note

When used with BINARY or VARBINARY data types, the + operator is concatenation, not addition.

The || concatenation operator is not supported by SAP Adaptive Server Enterprise.

Parent topic: SQL Operators [page 44]

Related Information

Arithmetic Operators [page 45]


String Operators [page 46]
Bitwise Operators [page 46]
Operator Precedence [page 50]

2.5.4.5 Operator Precedence

Follow this recommendation to make the order of operation explicit.

When you are using more than one operator in an expression, use parentheses to make the order of operation
explicit, rather than relying on an identical operator precedence between SAP Adaptive Server Enterprise and
SAP IQ.

SAP IQ SQL Reference


50 INTERNAL SQL Language Elements
Parent topic: SQL Operators [page 44]

Related Information

Arithmetic Operators [page 45]


String Operators [page 46]
Bitwise Operators [page 46]
Join Operators [page 50]

2.5.5 IF Expressions

The IF expression provides IF-THEN-ELSE SQL expressions.

The syntax of the IF expression is as follows:

IF <condition>
THEN <expression1>
[ ELSE <expression2> ]
ENDIF

This expression returns:

● If <condition> is TRUE – the IF expression returns <expression1>.


● If <condition> is FALSE – the IF expression returns <expression2>.
● If <condition> is FALSE – and there is no <expression2>, the IF expression returns NULL.
● If <condition> is NULL – the IF expression returns NULL.

 Note

IF statement is different from IF expression.

Do not confuse the syntax of the IF expression with that of the IF statement.

Parent topic: Expressions [page 40]

Related Information

Constants in Expressions [page 42]


Column Names in Expressions [page 42]
Subqueries in Expressions [page 43]
SQL Operators [page 44]
CASE Expressions [page 52]
Compatibility of Expressions and Constants [page 53]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 51
2.5.6 CASE Expressions

The CASE expression provides conditional SQL expressions.

You can use case expressions anywhere you can use an expression. The syntax of the CASE expression is as
follows:

CASE <expression>
WHEN <expression> THEN <expression> [, …]
[ ELSE <expression> ] END

You cannot use a subquery as a value expression in a CASE statement.

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

For example, the following code uses a case expression as the second clause in a SELECT statement:

SELECT ID,
(CASE name
WHEN 'Tee Shirt' THEN 'Shirt'
WHEN 'Sweatshirt' THEN 'Shirt'
WHEN 'Baseball Cap' THEN 'Hat'
ELSE 'Unknown'
END) as Type
FROM "GROUPO".Products

An alternative syntax is:

CASE
WHEN <search-condition> THEN <expression> [, …]
[ ELSE <expression> ] END

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

The following example uses a case expression as the third clause of a SELECT statement to associate a string
with a search condition:

SELECT ID, name,


(CASE
WHEN name='Tee Shirt' THEN 'Sale'
WHEN quantity >= 50 THEN 'Big Sale'
ELSE 'Regular price'
END) as Type
FROM "GROUPO".Products

In this section:

NULLIF Function for Abbreviated CASE Expressions [page 53]


The NULLIF function provides a way to write some CASE statements in short form.

Parent topic: Expressions [page 40]

SAP IQ SQL Reference


52 INTERNAL SQL Language Elements
Related Information

Constants in Expressions [page 42]


Column Names in Expressions [page 42]
Subqueries in Expressions [page 43]
SQL Operators [page 44]
IF Expressions [page 51]
Compatibility of Expressions and Constants [page 53]
NULLIF Function [Miscellaneous] [page 442]
NULLIF Function for Abbreviated CASE Expressions [page 53]

2.5.6.1 NULLIF Function for Abbreviated CASE Expressions

The NULLIF function provides a way to write some CASE statements in short form.

The syntax for NULLIF is as follows:

NULLIF ( <expression-1>, <expression-2> )

NULLIF compares the values of the two expressions. If the first expression equals the second expression,
NULLIF returns NULL. If the first expression does not equal the second expression, NULLIF returns the first
expression.

Related Information

CASE Expressions [page 52]


NULLIF Function [Miscellaneous] [page 442]

2.5.7 Compatibility of Expressions and Constants

These topics describe the compatibility of expressions and constants between SAP Adaptive Server Enterprise
and SAP IQ.

In this section:

Compatibility of Expressions [page 54]


This table describes the compatibility of expressions between SAP Adaptive Server Enterprise and SAP
IQ.

Compatibility of Constants [page 55]


This table describes the compatibility of constants between SAP Adaptive Server Enterprise and SAP
IQ.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 53
Parent topic: Expressions [page 40]

Related Information

Constants in Expressions [page 42]


Column Names in Expressions [page 42]
Subqueries in Expressions [page 43]
SQL Operators [page 44]
IF Expressions [page 51]
CASE Expressions [page 52]

2.5.7.1 Compatibility of Expressions

This table describes the compatibility of expressions between SAP Adaptive Server Enterprise and SAP IQ.

This table is a guide only, and a marking of Both may not mean that the expression performs in an identical
manner for all purposes under all circumstances. For detailed descriptions, see the SAP ASE documentation
and the SAP IQ documentation on the individual expression.

In this table, expr represents an expression, and op represents an operator.

Expression Supported By

constant Both

column name Both

variable name Both

function ( expr ) Both

- expr Both

expr op expr Both

( expr ) Both

( subquery ) Both

if-expression SAP IQ only

SAP IQ SQL Reference


54 INTERNAL SQL Language Elements
2.5.7.2 Compatibility of Constants

This table describes the compatibility of constants between SAP Adaptive Server Enterprise and SAP IQ.

Constant Supported By

integer Both

number Both

'string' Both

special-constant Both

host-variable SAP IQ

This table is a guide only, and a marking of Both may not mean that the expression performs in an identical
manner for all purposes under all circumstances. For detailed descriptions, see the SAP ASE documentation
and the SAP IQ documentation on the individual expression.

In this section:

Default Interpretation of Delimited Strings [page 55]


By default, SAP Adaptive Server Enterprise and SAP IQ give different meanings to delimited strings —
strings enclosed in apostrophes (single quotes) and in quotation marks (double quotes).

The quoted_identifier Option [page 55]


Both SAP Adaptive Server Enterprise and SAP IQ provide a quoted_identifier option that allows
the interpretation of delimited strings to be changed. By default, the quoted_identifier option is
set to OFF in SAP ASE, and to ON in SAP IQ.

2.5.7.2.1 Default Interpretation of Delimited Strings

By default, SAP Adaptive Server Enterprise and SAP IQ give different meanings to delimited strings — strings
enclosed in apostrophes (single quotes) and in quotation marks (double quotes).

SAP IQ employs the SQL92 convention, in which strings enclosed in apostrophes are constant expressions, and
strings enclosed in quotation marks (double quotes) are delimited identifiers (names for database objects).
SAP ASE employs the convention that strings enclosed in quotation marks are constants, whereas delimited
identifiers are not allowed by default and are treated as strings.

2.5.7.2.2 The quoted_identifier Option

Both SAP Adaptive Server Enterprise and SAP IQ provide a quoted_identifier option that allows the
interpretation of delimited strings to be changed. By default, the quoted_identifier option is set to OFF in
SAP ASE, and to ON in SAP IQ.

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

SAP IQ SQL Reference


SQL Language Elements INTERNAL 55
Although the Transact-SQL SET statement is not supported for most SAP ASE connection options, SET is
supported for the quoted_identifier option.

The following statement in either SAP IQ or SAP ASE changes the setting of the quoted_identifier option
to ON:

SET quoted_identifier ON

With the quoted_identifier option set to ON, SAP ASE allows table, view, and column names to be
delimited by quotes. Other object names cannot be delimited in SAP ASE.

The following statement in SAP IQ or SAP ASE changes the setting of the quoted_identifier option to OFF:

SET quoted_identifier OFF

You can choose to use either the SQL92 or the default Transact-SQL convention in both SAP ASE and SAP IQ as
long as the quoted_identifier option is set to the same value in each DBMS.

Examples

If you operate with the quoted_identifier option ON (the default SAP IQ setting), the following statements
involving the SQL keyword user are valid for both types of DBMS:

CREATE TABLE "user" (


col1 char(5)
) ;
INSERT "user" ( col1 )
VALUES ( 'abcde' ) ;

If you operate with the quoted_identifier option OFF (the default SAP ASE setting), the following
statements are valid for both types of DBMS:

SELECT *
FROM Employees
WHERE Surname = "Chin"

Related Information

Reserved Words [page 31]


Identifiers [page 34]

SAP IQ SQL Reference


56 INTERNAL SQL Language Elements
2.6 Search Conditions

Conditions are used to choose a subset of the rows from a table, or in a control statement such as an IF
statement to determine control of flow.

SQL conditions do not follow Boolean logic, where conditions are either true or false. In SQL, every condition
evaluates as one of TRUE, FALSE, or UNKNOWN. This is called three-valued logic. The result of a comparison is
UNKNOWN if either value being compared is the NULL value.

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

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

The different types of search conditions are discussed in the following sections.

You specify a search condition for a WHERE clause, a HAVING clause, a CHECK clause, a JOIN clause, or an IF
expression.

 Syntax

{ <expression> <compare> <expression>


| <expression> <compare> { ANY | SOME| ALL } ( <subquery> )
| <expression> IS [ NOT ] NULL <expression>
| <expression1> IS [ NOT ] DISTINCT FROM <expression2>
| <expression> [ NOT ] BETWEEN <expression> AND <expression>
| <expression> [ NOT ] LIKE <expression> [ ESCAPE <expression> ]
| <expression> [ NOT ] IN ( { <expression>| <subquery> |
… <value-expr1>, <value-expr2> [, <value-expr3> ] … } )
| <column-name> [ NOT ] CONTAINS ( … <word1 >[, <word2> ] [, <word3> ] … )
| CONTAINS ( <column-name> [, <… >], <contains-query string>)
| EXISTS ( <subquery> )
| NOT <condition>
| <condition> AND <condition>
| <condition> OR <condition>
| ( <condition> )
| ( <condition>, <estimate> )
| <condition> IS [ NOT ] { TRUE | FALSE | UNKNOWN }

<compare> ::=
{ = | > | < | >= | <= | <> | != | !< | !> }

Remarks

Anywhere

Authorization

Must be connected to the database

SAP IQ SQL Reference


SQL Language Elements INTERNAL 57
Side Effects

None

Example

The following query retrieves the names and birth years of the oldest employees:

SELECT Surname, BirthDate


FROM Employees
WHERE BirthDate <= ALL (SELECT BirthDate FROM Employees);

The subqueries that provide comparison values for quantified comparison predicates might retrieve multiple
rows but can have only one column.

In this section:

Comparison Conditions [page 59]


Comparison conditions in search conditions use a comparison operator.

Three-Valued Logic [page 60]


The AND, OR, NOT, and IS logical operators of SQL work in three-valued logic.

Subqueries in Search Conditions [page 62]


A subquery is a SELECT statement enclosed in parentheses. Such a SELECT statement must contain
one and only one select list item.

ALL or ANY Conditions [page 66]


Use ALL or ANY conditions in subqueries in search conditions.

BETWEEN Conditions [page 67]


Use BETWEEN conditions in subqueries to retrieve values within a range.

Conditions with Logical Operators [page 67]


Combine search conditions in subqueries using AND, OR, and NOT.

CONTAINS Conditions [page 68]


Use CONTAINS conditions in subqueries to define text-matching.

EXISTS Conditions [page 68]


An EXISTS condition is met if the subquery returns at least one row.

IN Conditions [page 69]


Use IN conditions in subqueries to reduce the need to use multiple OR conditions:

IS DISTINCT FROM Search Conditions [page 69]


Use the IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions as comparison operators.

IS NULL Conditions [page 70]


Use IS NULL conditions in subqueries to NULL values represent missing unknown data.

LIKE Conditions [page 70]


Use LIKE conditions in subqueries to use wildcards in the WHERE clause to perform pattern matching.

NOT Conditions [page 75]

SAP IQ SQL Reference


58 INTERNAL SQL Language Elements
The NOT condition can be either TRUE, FALSE, or UNKNOWN.

Truth Value Conditions [page 75]


The truth value of a condition is either TRUE or FALSE.

User-Supplied Condition Hints [page 75]


The selectivity of a condition is the fraction of the table’s rows that satisfy that condition.

Related Information

Comparison Conditions [page 59]


Expressions [page 40]
NULL Value [page 112]
Strings [page 38]
Three-Valued Logic [page 60]
SQL Operators [page 44]
Subqueries in Search Conditions [page 62]

2.6.1 Comparison Conditions

Comparison conditions in search conditions use a comparison operator.

The syntax for comparison conditions is as follows, where <compare> is a comparison operator:

<expression> <compare> <expression>

This table lists the comparison operators available in SAP IQ.

Operator Description

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

!= Not equal to

<> Not equal to

!> Not greater than

!< Not less than

SAP IQ SQL Reference


SQL Language Elements INTERNAL 59
Example

For example, the following query retrieves the names and birth years of the oldest employees:

SELECT Surname, BirthDate


FROM Employees
WHERE Surname <= ALL (SELECT MIN(BirthDate) FROM Employees);

The subqueries that provide comparison values for quantified comparison predicates, as in the preceding
example, might retrieve multiple rows but can only have one column.

 Note

All string comparisons are:

● Case-sensitive if the database was created as case respect (the default)


● Case-insensitive if the database was created as case ignore

Compatibility

● Trailing blanks – any trailing blanks in character data are ignored for comparison purposes by SAP
Adaptive Server Enterprise. The behavior of SAP IQ when comparing strings is controlled by the Ignore
Trailing Blanks in String Comparisons database creation option.
● Case sensitivity – by default, SAP IQ databases, like SAP ASE databases, are created as case-sensitive.
Comparisons are carried out with the same attention to case as the database they are operating on. You
can control the case sensitivity of SAP IQ databases when creating the database.

Related Information

Expressions [page 40]


NULL Value [page 112]
Search Conditions [page 57]
Strings [page 38]
Three-Valued Logic [page 60]
SQL Operators [page 44]
Subqueries in Search Conditions [page 62]

2.6.2 Three-Valued Logic

The AND, OR, NOT, and IS logical operators of SQL work in three-valued logic.

These tables show the three-valued logic.

SAP IQ SQL Reference


60 INTERNAL SQL Language Elements
AND Operator

AND TRUE FALSE UNKNOWN

TRUE TRUE FALSE UNKNOWN

FALSE FALSE FALSE FALSE

UNKNOWN UNKNOWN FALSE UNKNOWN

OR Operator

OR TRUE FALSE UNKNOWN

TRUE TRUE TRUE TRUE

FALSE TRUE FALSE UNKNOWN

UNKNOWN TRUE UNKNOWN UNKNOWN

NOT Operator

TRUE FALSE UNKNOWN

FALSE TRUE UNKNOWN

IS Operator

IS TRUE FALSE UNKNOWN

TRUE TRUE FALSE FALSE

FALSE FALSE TRUE FALSE

UNKNOWN FALSE FALSE TRUE

SAP IQ SQL Reference


SQL Language Elements INTERNAL 61
Related Information

Comparison Conditions [page 59]


Expressions [page 40]
NULL Value [page 112]
Search Conditions [page 57]
Strings [page 38]
SQL Operators [page 44]
Subqueries in Search Conditions [page 62]

2.6.3 Subqueries in Search Conditions

A subquery is a SELECT statement enclosed in parentheses. Such a SELECT statement must contain one and
only one select list item.

A column can be compared to a subquery in a comparison condition (for example, >,<, or !=) as long as the
subquery returns no more than one row. If the subquery (which must have one column) returns one row, the
value of that row is compared to the expression. If a subquery returns no rows, its value is NULL.

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

SAP IQ supports UNION only in uncorrelated subquery predicates, not in scalar value subqueries or correlated
subquery predicates.

Subqueries cannot be used inside a CONTAINS or LIKE predicate.

SAP IQ does not support multiple subqueries in a single OR clause. For example, the following query has two
subqueries joined by an OR:

CREATE VARIABLE @ln int;


SELECT @ln = 1;
SELECT COUNT(*) FROM lineitem WHERE
l_shipdate IN (SELECT l_shipdate FROM lineitem WHERE l_orderkey IN (2,4,6))OR
l_shipdate IN (SELECT l_shipdate FROM lineitem WHERE l_orderkey IN (1,3,5))OR
l_linenumber = @ln;

Similar subqueries joined by AND and BETWEEN are allowed.

In this section:

Disjunction of Subquery Predicates [page 63]


The SQL89 standard allows for several forms of subquery predicates.

Related Information

Column Names in Expressions [page 42]

SAP IQ SQL Reference


62 INTERNAL SQL Language Elements
Reserved Words [page 31]
Identifiers [page 34]
Comparison Conditions [page 59]
Expressions [page 40]
NULL Value [page 112]
Search Conditions [page 57]
Strings [page 38]
Three-Valued Logic [page 60]

2.6.3.1 Disjunction of Subquery Predicates

The SQL89 standard allows for several forms of subquery predicates.

Each subquery can appear within the WHERE or HAVING clause with other predicates, and can be combined
using the AND or OR operators. SAP IQ supports these subqueries, which can be correlated (contain
references to a table that appears in the outer query and cannot be evaluated independently) and uncorrelated
(do not contain references to remote tables).

The forms of subquery predicates include:

● Unquantified comparison predicates:

<scalar-expression> <comparison-operator> <subquery>

The comparison operator is =, <>, >, >=, <, or <=.


Unquantified comparison subqueries return exactly one value. If the subquery returns more than one
value, an error message appears. This type of query is also called a scalar subquery predicate.
● IN predicates:

<scalar-expression> [NOT] IN <subquery>

The IN subquery predicate returns a list of values or a single value. This type is also called a quantified
subquery predicate.
● Existence predicates:

[NOT] EXISTS <subquery>

The EXISTS predicate represents the existence of the subquery. The expression EXISTS <subquery>
evaluates to true only if the subquery result is not empty. The EXISTS predicate does not compare results
with any column or expressions in the outer query block, and is typically used with correlated subqueries.
● Quantified comparison predicates:

<scalar-expression> <comparison-operator> [ANY | ALL] <subquery>

A quantified comparison predicate compares one or a collection of values returned from a subquery.

The types of queries you can run include:

● Disjunction of uncorrelated scalar subqueries or IN subqueries that cannot be executed vertically within
the WHERE or HAVING clause.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 63
● Disjunction of correlated or uncorrelated EXISTS subqueries within the WHERE or HAVING clause.
● Disjunction of arbitrary correlated or uncorrelated scalar subqueries, IN or EXISTS subqueries, or
quantified comparison subqueries within the WHERE or HAVING clause.
● Arbitrary uncorrelated or correlated subquery predicates combined with AND/OR (conjunct/disjunct) and
simple predicates or subquery predicates.
● Conjunction or disjunction of subquery predicates on top of a view/derived table.
● Disjunction of subquery predicates in UPDATE, DELETE, and SELECT INTO statements.

The SUBQUERY_CACHING_PREFERENCE option lets experienced DBAs choose which subquery caching method
to use.

Examples

Example 1

Disjunction of uncorrelated EXISTS and IN subqueries:

SELECT COUNT(*)
FROM supplier
WHERE s_suppkey IN (SELECT MAX(l_suppkey)
FROM lineitem
GROUP BY l_linenumber)
OR EXISTS (SELECT p_brand
FROM part
WHERE p_brand = 'Brand#43');

Example 2

Disjunction of uncorrelated EXISTS subqueries:

SELECT COUNT(*)
FROM supplier
WHERE EXISTS (SELECT l_suppkey
FROM lineitem
WHERE l_suppkey = 12345)
OR EXISTS (SELECT p_brand
FROM part
WHERE p_brand = 'Brand#43');

Example 3

Disjunction of uncorrelated scalar or IN subquery predicates:

SELECT COUNT(*)
FROM supplier
WHERE s_acctbal*10 > (SELECT MAX(o_totalprice)
FROM orders
WHERE o_custkey = 12345)
OR substring(s_name, 1, 6) IN (SELECT c_name
FROM Customers
WHERE c_nationkey = 10);

SAP IQ SQL Reference


64 INTERNAL SQL Language Elements
Example 4
Disjunction of correlated/uncorrelated quantified comparison subqueries:

SELECT COUNT(*)
FROM lineitem
WHERE l_suppkey > ANY (SELECT MAX(s_suppkey)
FROM supplier
WHERE s_acctbal >100
GROUP BY s_nationkey)
OR l_partkey >= ANY (SELECT MAX(p_partkey)
FROM part
GROUP BY p_mfgr);

Example 5
Disjunction of any correlated subquery predicates:

SELECT COUNT(*)
FROM supplier S
WHERE EXISTS (SELECT l_suppkey
FROM lineitem
WHERE l_suppkey = S.s_suppkey)
OR EXISTS (SELECT p_brand FROM part
WHERE p_brand = 'Brand#43'
AND p_partkey > S.s_suppkey);

Example 6
Before support for disjunction of subqueries, users were required to write queries in two parts, and then use
UNION to merge the final results.

The following query illustrates a merged query that gets the same results as the example for disjunction of any
correlated subquery predicates:

SELECT COUNT(*)
FROM (SELECT s_suppkey FROM supplier S
WHERE EXISTS (SELECT l_suppkey
FROM lineitem
WHERE l_suppkey = S.s_suppkey)
UNION
SELECT s_suppkey
FROM supplier S
WHERE EXISTS (SELECT p_brand
FROM part
WHERE p_brand = 'Brand#43'
AND p_partkey > S.s_suppkey)) as UD;

Performance of the merged query is suboptimal because it scans the supplier table twice and then merges the
results from each UNION to return the final result.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 65
2.6.4 ALL or ANY Conditions

Use ALL or ANY conditions in subqueries in search conditions.

Syntax

The syntax for ALL conditions is as follows, where <compare> is a comparison operator:

<expression> <compare> ALL ( <subquery> )

The syntax for ANY conditions is as follows, where <compare> is a comparison operator:

<expression> <compare> ANY ( <subquery> )

For example, an ANY condition with an equality operator is TRUE if <expression> is equal to any of the values
in the result of the subquery, and FALSE if the expression is not NULL and does not equal any of the columns of
the subquery:

<expression> = ANY ( <subquery> )

The ANY condition is UNKNOWN if <expression> is the NULL value, unless the result of the subquery has no
rows, in which case the condition is always FALSE.

You can use the keyword SOME instead of ANY.

Restrictions

If there is more than one expression on either side of a quantified comparison predicate, an error message is
returned. For example:

Subquery allowed only one select list item

Queries of this type can always be expressed in terms of IN subqueries or scalar subqueries using MIN and MAX
set functions.

Compatibility

ANY and ALL subqueries are compatible between SAP Adaptive Server Enterprise and SAP IQ. Only SAP IQ
supports SOME as a synonym for ANY.

SAP IQ SQL Reference


66 INTERNAL SQL Language Elements
2.6.5 BETWEEN Conditions

Use BETWEEN conditions in subqueries to retrieve values within a range.

The syntax for BETWEEN conditions is as follows:

<expr> [ NOT ] BETWEEN <start-expr> AND <end-expr>

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

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

<expr> >= <start-expr> AND <expr> <= <end-expr>

A BETWEEN predicate is of the form “A between B and C.” Either “B” or “C” or both “B” and “C” can be
subqueries. “A” must be a value expression or column.

Compatibility

The BETWEEN condition is compatible between SAP IQ and SAP Adaptive Server Enterprise.

2.6.6 Conditions with Logical Operators

Combine search conditions in subqueries using AND, OR, and NOT.

Conditions are combined using AND as follows:

<condition1> AND <condition2>

If both conditions are TRUE, the combined condition is TRUE. If either condition is FALSE, the combined
condition is FALSE. If otherwise, the combined condition is UNKNOWN.

Conditions are combined using OR as follows:

<condition1> OR <condition2>

If both conditions are TRUE, the combined condition is TRUE. If either condition is FALSE, the combined
condition is FALSE. If otherwise, the combined condition is UNKNOWN. There is no guaranteed order as to
which condition, <condition1> or <condition2>, is evaluated first.

Compatibility

The AND and OR operators are compatible between SAP IQ and SAP Adaptive Server Enterprise.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 67
2.6.7 CONTAINS Conditions

Use CONTAINS conditions in subqueries to define text-matching.

The syntax for CONTAINS conditions for a column with a WD index is as follows:

{ <column-name> [ NOT ] CONTAINS ( ( <word1> [ , <word2> ] [ , <word3> ] … )

The <column-name> must be a CHAR, VARCHAR, or LONG VARCHAR (CLOB) column in a base table, and must
have a WD index. The <word1>, <word2> and <word3> expressions must be string constants no longer than
255 bytes, each containing exactly one word. The length of that word cannot exceed the maximum permitted
word length of the word index of the column.

Without the NOT keyword, the CONTAINS condition is TRUE if <column-name> contains each of the words,
UNKNOWN if <column-name> is the NULL value, and FALSE otherwise. The NOT keyword reverses these
values but leaves UNKNOWN unchanged.

For example, the following search condition is TRUE if the value of <varchar_col> is The cat is on the
mat:

varchar_col CONTAINS ('cat', 'mat')

This condition is FALSE, however, if the value of <varchar_col> is The cat chased the mouse.

When SAP IQ executes a statement containing both LIKE and CONTAINS, the CONTAINS condition takes
precedence.

Avoid using the CONTAINS predicate in a view that has a user-defined function, because the CONTAINS criteria
are ignored. Use the LIKE predicate with wildcards instead, or issue the query outside of a view.

For information on using CONTAINS conditions with TEXT indexes, see SAP IQ Administration: Unstructured
Data Analytics.

2.6.8 EXISTS Conditions

An EXISTS condition is met if the subquery returns at least one row.

The syntax for EXISTS conditions is as follows:

EXISTS( <subquery> )

The EXISTS condition is TRUE if the subquery result contains at least one row, and FALSE if the subquery
result does not contain any rows. The EXISTS condition cannot be UNKNOWN.

Compatibility

The EXISTS condition is compatible between SAP Adaptive Server Enterprise and SAP IQ.

SAP IQ SQL Reference


68 INTERNAL SQL Language Elements
2.6.9 IN Conditions

Use IN conditions in subqueries to reduce the need to use multiple OR conditions:

The syntax for IN conditions is:

{ <expression> [ NOT ] IN ( <subquery> )


| <expression> [ NOT ] IN ( <expression> )
| <expression> [ NOT ] IN ( <value-expr1> , <value-expr2>
[ , <value-expr3> ] … ) }

Without the NOT keyword, the IN condition is TRUE if <expression> equals any of the listed values,
UNKNOWN if <expression> is the NULL value, and FALSE otherwise. The NOT keyword reverses the meaning
of the condition but leaves UNKNOWN unchanged.

The maximum number of values allowed in an IN condition list is 250,000.

Compatibility

IN conditions are compatible between SAP Adaptive Server Enterprise and SAP IQ.

2.6.10 IS DISTINCT FROM Search Conditions

Use the IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions as comparison operators.

Syntax

<expression1> IS [ NOT ] DISTINCT FROM <expression2>

Remarks

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

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

expression1 = expression2 OR ( expression1 IS NULL AND expression2 IS NULL )

SAP IQ SQL Reference


SQL Language Elements INTERNAL 69
The IS DISTINCT FROM syntax reverses the meaning. That is, IS DISTINCT FROM evaluates to TRUE if
<expression1> is not equal to <expression2>, and at least one of the expressions is not NULL. This is
equivalent to the following:

NOT( expression1 = expression2 OR ( expression1 IS NULL AND expression2 IS


NULL ))

Standards and Compatibility

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

2.6.11 IS NULL Conditions

Use IS NULL conditions in subqueries to NULL values represent missing unknown data.

The syntax for IS NULL conditions is:

<expression> IS [ NOT ] NULL

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

Compatibility

The IS NULL condition is compatible between SAP Adaptive Server Enterprise and SAP IQ.

2.6.12 LIKE Conditions

Use LIKE conditions in subqueries to use wildcards in the WHERE clause to perform pattern matching.

The syntax for LIKE conditions is:

<expression> [ NOT ] LIKE <pattern> [ ESCAPE <escape-expr> ]

The LIKE condition can evaluate as TRUE, FALSE, or UNKNOWN. You can use LIKE only on string data.

You cannot use subqueries inside a LIKE predicate.

LIKE predicates that start with characters other than wildcard characters may execute faster if an HG index is
available.

SAP IQ SQL Reference


70 INTERNAL SQL Language Elements
Certain LIKE predicates execute faster, if either of the following conditions is true:

● A WD index is available, provided the LIKE pattern contains at least one word bounded on the left end by
whitespace or the end of the pattern
● An NGRAM TEXT index is available, provided the LIKE pattern contains at least <N> contiguous non-
wildcard characters

Without the NOT keyword, the condition evaluates as TRUE if <expression> matches the <pattern>. If either
<expression> or <pattern> is the NULL value, this condition is UNKNOWN. The NOT keyword reverses the
meaning of the condition but leaves UNKNOWN unchanged.

The pattern might contain any number of wildcard characters. The wildcard characters are:

Wildcard Matches

_ (underscore) Any one character

% (percent) Any string of zero or more characters

[] Any single character in the specified range or set

[^] Any single character not in the specified range or set

All other characters must match exactly.

For example, the following search condition is TRUE for any row where name starts with the letter a and has the
letter b as its second-to-last character:

name LIKE 'a%b_'

If you specify an <escape-expr>, it must evaluate to a single character. The character can precede a percent,
an underscore, a left square bracket, or another escape character in the <pattern> to prevent the special
character from having its special meaning. When escaped in this manner, a percent matches a percent, and an
underscore matches an underscore.

Supported Patterns

All patterns of 126 characters or less are supported.

Some patterns between 127 and 254 characters are supported, but only under certain circumstances. See the
following subsections for examples.

All patterns 255 characters or greater are not supported.

Examples – Patterns Between 127 and 254 Characters

Example 1

Under specific circumstances where adjacent constant characters exist in your pattern, patterns of length
between 127 and 254 characters are supported. Each constant character in the string pattern requires two

SAP IQ SQL Reference


SQL Language Elements INTERNAL 71
bytes, even if the character is a single-byte character. The string pattern in the LIKE predicate must be less
than 256 bytes (or 255/2 characters) or else the following error appears:

There was an error reading the results of the SQL statement.


The displayed results may be incorrect or incomplete.
Cannot compile Like pattern: either bad pattern or
pattern too long.

SAP IQ collapses adjacent constant characters into a single character. For example, consider the following
LIKE predicate with a string length of 130 characters:

select col2 from tablen where col2 like

'12345678901234567890123456789012345678901234567890123456789012345678901234567890
1234567890123456789012345678901234567890123456%%%%' ;

SAP IQ collapses the four adjacent constant characters %%%% at the end of the string into one % character,
thereby reducing the length of the string from 130 characters to 127. This is less than the maximum of 256
bytes (or 255/2 characters), and no error is generated.

Therefore, if your LIKE predicate contains adjacent constants in the string, patterns of length between 127 and
254 characters are supported as long as the total length of the collapsed string is less than 256 bytes (or 255/2
characters).

Example 2
In this example, the constant characters 7890 replace the four adjacent constant characters %%%% at the end of
the 130-character LIKE predicate:

select col2 from tablen where col2 like

'12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890' ;

In this case, no characters are collapsed. The character string length remains at 130 characters and SAP IQ
generates an error.

Example 3
In this example, four adjacent underscores ____ (special characters) replace the four constant characters %%%
% at the end of the 130-character LIKE predicate:

select col2 from tablen where col2 like

'12345678901234567890123456789012345678901234567890123456789012345678901234567890
1234567890123456789012345678901234567890123456____' ;

SAP IQ does not collapse adjacent special characters. The string length remains at 130 characters and SAP IQ
generates an error.

Example 4
In this example, the range [1-3] replaces the four constant characters %%%% at the end of the 130-character
LIKE predicate:

select col2 from tablen where col2 like

'12345678901234567890123456789012345678901234567890123456789012345678901234567890
1234567890123456789012345678901234567890123456[1-3]' ;

SAP IQ SQL Reference


72 INTERNAL SQL Language Elements
The length of the LIKE predicate in bytes is calculated as follows: 126 (for the constant characters) * 2 + 1 (for
the 1 in brackets) + 1 ( for the 3 in brackets) + 2 ( for the Set state and Range state expression).

This equals 256 bytes, and therefore SAP IQ generates an error.

Searching for One of a Set of Characters

You can specify a set of characters to look for by listing the characters inside square brackets. For example, the
following condition finds the strings smith and smyth:

LIKE 'sm[iy]th'

Searching for One of a Range of Characters

Specify a range of characters to look for by listing the ends of the range inside square brackets, separated by a
hyphen. For example, the following condition finds the strings bough and rough, but not tough:

LIKE '[a-r]ough'

The range of characters [a-z] is interpreted as “greater than or equal to a, and less than or equal to z,” where
the greater than and less than operations are carried out within the collation of the database. For information
on ordering of characters within a collation, see How the Collation Sequence Sorts Characters in SAP IQ
Administration: Globalization.

The lower end of the range must precede the higher end of the range. For example, a LIKE condition containing
the expression [z-a] returns no rows, because no character matches the [z-a] range.

Unless the database is created as case-sensitive, the range of characters is case-insensitive. For example, the
following condition finds the strings Bough, rough, and TOUGH:

LIKE '[a-z]ough'

If the database is created as a case-sensitive database, the search condition is case-sensitive also.

Combining Searches for Ranges and Sets

You can combine ranges and sets within square brackets. For example, the following condition finds the strings
bough, rough, and tough:

LIKE '[a-rt]ough'

The bracket [a-mpqs-z] is interpreted as “exactly one character that is either in the range a to m inclusive, or
is p, or is q, or is in the range s to z inclusive.”

SAP IQ SQL Reference


SQL Language Elements INTERNAL 73
Searching for One Character Not in a Range

Use the caret character (^) to specify a range of characters that is excluded from a search. For example, the
following condition finds the string tough, but not the strings rough, or bough:

LIKE '[^a-r]ough'

The caret negates the entire contents of the brackets. For example, the bracket [^a-mpqs-z] is interpreted as
“exactly one character that is not in the range a to m inclusive, is not p, is not q, and is not in the range s to z
inclusive.”

Special Cases of Ranges and Sets

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

Other special cases are:

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


● The expression [] is never matched and always returns no rows.
● The expressions [ or [abp-q are ill-formed expressions, and give syntax errors.
● You cannot use wildcard characters inside square brackets. The expression [a%b] finds one of a, %, or b.
● You cannot use the caret character to negate ranges except as the first character in the bracket. The
expression [a^b] finds one of a, ^, or b.

Compatibility

The ESCAPE clause is supported by SAP IQ only.

 Note

For information on support of the LIKE predicate with large object data and variables, see Unstructured
Data Queries in SAP IQ Administration: Unstructured Data Analytics.

Users must be specifically licensed to use the large object data types LONG BINARY and LONG VARCHAR.
For details on the Unstructured Data Analytics Option, see SAP IQ Administration: Unstructured Data
Analytics.

Related Information

LOCATE Function [String] [page 409]

SAP IQ SQL Reference


74 INTERNAL SQL Language Elements
PATINDEX Function [String] [page 448]

2.6.13 NOT Conditions

The NOT condition can be either TRUE, FALSE, or UNKNOWN.

The syntax for NOT conditions is:

NOT <condition1>

The NOT condition is TRUE if <condition1> is FALSE, FALSE if <condition1> is TRUE, and UNKNOWN if
<condition1> is UNKNOWN.

2.6.14 Truth Value Conditions

The truth value of a condition is either TRUE or FALSE.

The syntax for truth value conditions is:

IS [ NOT ] <truth-value>

Without the NOT keyword, the condition is TRUE if the <condition> evaluates to the supplied <truth-
value>, which must be one of TRUE, FALSE, or UNKNOWN. Otherwise, the value is FALSE. The NOT keyword
reverses the meaning of the condition but leaves UNKNOWN unchanged.

Compatibility

Truth-valued conditions are supported by SAP IQ only.

2.6.15 User-Supplied Condition Hints

The selectivity of a condition is the fraction of the table’s rows that satisfy that condition.

The SAP IQ query optimizer uses information from available indexes to select an appropriate strategy for
executing a query. For each condition in the query, the optimizer decides whether the condition can be
executed using indexes, and if so, the optimizer chooses which index and in what order with respect to the
other conditions on that table. The most important factor in these decisions is the selectivity of the condition;
that is, the fraction of the table’s rows that satisfy that condition.

The optimizer normally decides without user intervention, and it generally makes optimal decisions. In some
situations, however, the optimizer might not be able to accurately determine the selectivity of a condition
before it has been executed. These situations normally occur only where either the condition is on a column

SAP IQ SQL Reference


SQL Language Elements INTERNAL 75
with no appropriate index available, or where the condition involves some arithmetic or function expression and
is, therefore, too complex for the optimizer to accurately estimate.

If you have a query that is run frequently, then you may want to experiment to see whether you can improve the
performance of that query by supplying the optimizer with additional information to aid it in selecting the
optimal execution strategy.

In this section:

User-Supplied Condition Selectivity [page 76]


The simplest form of condition hint is to supply a selectivity value that will be used instead of the value
the optimizer would have computed.

User-Supplied Condition Hint Strings [page 77]


You can supply additional hint information to the optimizer through a condition hint string.

User-Supplied Hints on Join Equality Conditions [page 82]


Users can specify a join algorithm preference that does not affect every join in the query.

Guidelines for Usage of User-Supplied Condition Hints [page 84]


Condition hints are generally appropriate only within frequently run queries.

2.6.15.1 User-Supplied Condition Selectivity

The simplest form of condition hint is to supply a selectivity value that will be used instead of the value the
optimizer would have computed.

Selectivity hints are supplied within the text of the query by wrapping the condition within parentheses. Then
within the parentheses, after the condition, you add a comma and a numeric value to be used as the selectivity.

This selectivity value is expressed as a percentage of the table’s rows, which satisfy the condition. Possible
numeric values for selectivity thus range from 100.0 to 0.0.

 Note

In query plans, selectivity is expressed as a fraction instead of as a percentage; so a user-supplied


selectivity of 35.5 appears in that query’s plan as a selectivity of 0.355000.

Examples

● The following query provides an estimate that one and one half percent of the ship_date values are
earlier than 1994/06/30:

SELECT ShipDate
FROM SalesOrderItems
WHERE ( ShipDate < '2001/06/30', 1.5 )
ORDER BY ShipDate DESC

● The following query estimates that half a percent of the rows satisfy the condition:

SELECT *

SAP IQ SQL Reference


76 INTERNAL SQL Language Elements
FROM Customers c, SalesOrders o
WHERE (o.SalesRepresentative > 1000.0, 0.5)
AND c.ID = o.customerID

Fractional percentages enable more precise user estimates to be specified and can be particularly important
for large tables.

Compatibility

SAP SQL Anywhere supports user-supplied selectivity estimates.

SAP Adaptive Server Enterprise does not support user-supplied selectivity estimates.

Related Information

Selectivity Hints [page 78]

2.6.15.2 User-Supplied Condition Hint Strings

You can supply additional hint information to the optimizer through a condition hint string.

These per-condition hint strings let users specify additional execution preferences for a condition, which the
optimizer follows, if possible. These preferences include which index to use for the condition, the selectivity of
the condition, the phase of execution when the condition is executed, and the usefulness of the condition,
which affects its ordering among the set of conditions executed within one phase of execution.

Condition hint strings, like the user-supplied selectivity estimates, are supplied within the text of the query by
wrapping the condition within parentheses. Then within the parentheses and after the condition, you add a
comma and a supply a quoted string containing the desired hints. Within that quoted string each hint appears
as a hint type identifier, followed by a colon and the value for that hint type. Multiple hints within the same hint
string are separated from each other by a comma, and multiple hints can appear in any order. White space is
allowed between any of two elements within a hint string.

In this section:

Selectivity Hints [page 78]


The first hint type that can appear within a hint string is a selectivity hint. A selectivity hint is identified
by a hint type identifier of either “S” or “s”.

Index Preference Hints [page 78]


The second supported hint type is an index preference hint, which is identified by a hint type identifier
of either “I” or “i”.

INDEX_PREFERENCE Option [page 79]


Controls the choice of indexes to use for queries.

Execution Phase Hints [page 80]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 77
The third supported hint type is the execution phase hint, which is identified with a hint type identifier
of either "E" or "e".

Usefulness Hints [page 81]


The final supported hint type is the usefulness hint, which is identified by a hint type identifier of either
“U” or “u”.

2.6.15.2.1 Selectivity Hints

The first hint type that can appear within a hint string is a selectivity hint. A selectivity hint is identified by a hint
type identifier of either “S” or “s”.

Like user-supplied selectivity estimates, the selectivity value is always expressed as a percentage of the table’s
rows, which satisfy the condition.

 Example

The following example is exactly equivalent to the second user-supplied condition selectivity example:

SELECT *
FROM Customers c, SalesOrders o
WHERE (o.SalesRepresentative > 1000.0, 's: 0.5)
AND c.ID = o.CustomerID

Related Information

User-Supplied Condition Selectivity [page 76]

2.6.15.2.2 Index Preference Hints

The second supported hint type is an index preference hint, which is identified by a hint type identifier of either
“I” or “i”.

The value for an index preference hint can be any integer between -10 and 10. The meaning of each positive
integer value is to prefer a specific index type, while negative values indicate that the specific index type is to be
avoided.

The effect of an index preference hint is the same as that of the INDEX_PREFERENCE option, except that the
preference applies only to the condition it is associated with rather than all conditions within the query. An
index preference can only affect the execution of a condition if the specified index type exists on that column
and that index type is valid for use when evaluating the associated condition; not all index types are valid for
use with all conditions.

SAP IQ SQL Reference


78 INTERNAL SQL Language Elements
 Example

The following example specifies a 3 percent selectivity and indicates that, if possible, the condition should
be evaluated using an HG index:

SELECT *
FROM Customers c, SalesOrders o
WHERE (o.SalesRepresentative > 1000.0, 'S:3.00, I:+2')
AND c.ID = o.CustomerID

 Example

The next example specifies a 37.5 percent selectivity and indicates that if possible the condition should not
be evaluated using an HG index:

SELECT *
FROM Customers c, SalesOrders o
WHERE (o.SalesRepresentative > 1000.0, 'i:-2, s:37.500')
AND c.ID = o.CustomerID

2.6.15.2.3 INDEX_PREFERENCE Option

Controls the choice of indexes to use for queries.

Allowed Values

The values control the following:

● -10 – avoid DTTM indexes


● -9 – avoid TIME indexes
● -8 – avoid DATE indexes
● -6 – avoid WD indexes
● -5 – avoid the default index
● -4 – avoid CMP indexes
● -3 – avoid HNG indexes
● -2 – avoid HG indexes
● -1 – avoid LF indexes
● 0 – (default) let the optimizer choose
● 1 – prefer LF indexes
● 2 – prefer HG indexes
● 3 – prefer HNG indexes
● 4 – prefer CMP indexes
● 5 – prefer the default index
● 6 – prefer WD indexes

SAP IQ SQL Reference


SQL Language Elements INTERNAL 79
● 8 – prefer DATE indexes
● 9 – prefer TIME indexes
● 10 – prefer DTTM indexes

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The SAP IQ optimizer normally chooses the best index available to process local WHERE clause predicates and
other operations that can be done within an IQ index. INDEX_PREFERENCE is used to override the optimizer
choice for testing purposes; under most circumstances, it should not be changed.

2.6.15.2.4 Execution Phase Hints

The third supported hint type is the execution phase hint, which is identified with a hint type identifier of either
"E" or "e".

Within the SAP IQ query engine, there are four distinct phases of execution where conditions can be evaluated.

By default, the optimizer chooses to evaluate each condition within the earliest phase of execution where all the
information needed to evaluate that condition is available. Every condition. therefore, has a default execution
phase where it is evaluated.

Because no condition can be evaluated before the information it needs is available, the execution phase hint
can only be used to delay the execution of a condition to a phase after its default phase. It cannot be used to
force a condition to be evaluated within any phase earlier than its default phase.

The four phases of condition execution, from earliest to latest, are as follows:

● Invariant – a condition that refers to only one column (or two columns from the same table) and that can
be evaluated using an index is generally referred to as a simple invariant condition. Simple invariant

SAP IQ SQL Reference


80 INTERNAL SQL Language Elements
conditions are normally evaluated early within the optimization process. This means that the number of
rows satisfying all of those invariant conditions is available to guide the optimizer’s decisions on the best
join order and join algorithms to use. Because this is the earliest phase of execution, a user can never force
a condition into this phase, but conditions can be forced out of this phase into later phases
● Delayed – some conditions cannot be evaluated until some other part of a query has been executed. These
delayed conditions are evaluated once when the query node to which they are attached is first fetched.
These conditions fall into two categories: uncorrelated subquery conditions, and IN or PROBABLY_IN
pushdown join conditions created by the optimizer.
● Bound – some conditions require multiple evaluations. These conditions generally fall into two categories:
conditions containing outer references within a correlated subquery, and pushdown equality join
conditions created by the optimizer. The outer reference conditions, for example, are re-evaluated each
time the outer reference value changes during the query's execution.
● Horizontal – some conditions, such as those that contain more than two columns from a table, can only be
evaluated one row at a time, rather than by using an index.

An execution phase hint accepts a value that identifies in which execution phase the user wants the condition
to be evaluated. Each value is a case-insensitive single character:

● D – Delayed
● B – Bound
● H – Horizontal

Example

The following example shows a condition hint string which indicates that the condition should be moved into
the “Delayed” phase of execution, and it indicates that if possible the condition should be evaluated using an
HG index:

SELECT *
FROM Customers c, SalesOrders o
WHERE (o.SalesRepresentative > 10000.0, 'E:D, I:2')
AND c.id = o.CustomerID

2.6.15.2.5 Usefulness Hints

The final supported hint type is the usefulness hint, which is identified by a hint type identifier of either “U” or
“u”.

The value for a usefulness hint can be any numeric value between 0.0 and 10.0. Within the optimizer a
usefulness value is computed for every condition, and the usefulness value is then used to determine the order
of evaluation among the set of conditions to be evaluated within the same phase of execution. The higher the
usefulness value, the earlier it appears in the order of evaluation. Supplying a usefulness hint lets users place a
condition at a particular point within the order of evaluation, but it cannot change the execution phase within
which the condition is evaluated.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 81
Example

The following example shows a condition hint string which indicates that the condition should be moved into
the “Delayed” phase of execution, and that its usefulness should be set to 3.25 within that “Delayed” phase:

SELECT *
FROM Customers c, SalesOrders o
WHERE (co.SalesRepresentative > 10000.0, 'U: 3.25, E: D')
AND c.id = o.CustomerID

Compatibility

SAP SQL Anywhere does not support user-supplied condition hint strings.

SAP Adaptive Server Enterprise does not support user-supplied condition hint strings.

2.6.15.3 User-Supplied Hints on Join Equality Conditions

Users can specify a join algorithm preference that does not affect every join in the query.

Simple equality join predicates can be tagged with a predicate hint that allows a join preference to be specified
for just that one join. If the same join has more than one join condition with a local join preference, and if those
hints are not the same value, then all local preferences are ignored for that join. Local join preferences do not
affect the join order chosen by the optimizer.

The values and their actions are as follows:

Value Action

0 Let the optimizer choose

1 Prefer sort-merge

2 Prefer nested-loop

3 Prefer nested-loop push-down

4 Prefer hash

5 Prefer hash push-down

6 Prefer asymmetric sort-merge join

7 Prefer sort-merge push-down

8 Prefer asymmetric sort-merge push-down join

9 Prefer partitioned hash join if the join keys include all the partition keys of a hash partitioned
table

10 Prefer partitioned hash-push down join if the join keys include all the partition keys of a hash
partitioned table

SAP IQ SQL Reference


82 INTERNAL SQL Language Elements
Value Action

11 Prefer partitioned sort-merge join if the join keys include all the partition keys of a hash par­
titioned table

12 Prefer partitioned sort-merge push-down join if the join keys include all the partition keys of
a hash partitioned table

-1 Avoid sort-merge

-2 Avoid nested-loop

-3 Avoid nested-loop push-down

-4 Avoid hash

-5 Avoid hash push-down

-6 Avoid asymmetric sort-merge join

-7 Avoid sort-merge push-down

-8 Avoid asymmetric sort-merge push-down join

-9 Avoid partitioned hash join if the join keys include all the partition keys of a hash partitioned
table

10 Avoid partitioned hash-push down join if the join keys include all the partition keys of a hash
partitioned table

11 Avoid partitioned sort-merge join if the join keys include all the partition keys of a hash parti­
tioned table

12 Avoid partitioned sort-merge push-down join if the join keys include all the partition keys of
a hash partitioned table

Example

The following example requests a hash join:

AND (T.X = 10 * R.x, 'J:4')

Related Information

JOIN_PREFERENCE Option [page 1891]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 83
2.6.15.4 Guidelines for Usage of User-Supplied Condition
Hints

Condition hints are generally appropriate only within frequently run queries.

Only advanced users should experiment with condition hints. The optimizer generally makes optimal decisions,
except where it cannot infer accurate information about a condition from the available indexes.

The optimizer often rewrites or simplifies the original conditions, and it also infers new conditions from the
original conditions. Condition hints are not carried through new to conditions inferred by the optimizer, nor are
they carried through to simplified conditions.

2.7 Special Values

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

In this section:

CURRENT DATABASE Special Value [page 85]


CURRENT DATABASE returns the name of the current database.

CURRENT DATE Special Value [page 85]


CURRENT DATE returns the current year, month and day.

CURRENT PUBLISHER Special Value [page 86]


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

CURRENT TIME Special Value [page 86]


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

CURRENT TIMESTAMP Special Value [page 87]


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

CURRENT USER Special Value [page 87]


CURRENT USER returns a string that contains the user ID of the current connection.

EXECUTING USER special value [page 88]


SQL special value that returns the current effective user.

INVOKING USER special value [page 89]


SQL special value that returns the user that invoked the current procedure, or returns the current
logged in user if no procedure is executing.

LAST USER Special Value [page 89]


LAST USER returns the name of the user who last modified the row.

PROCEDURE OWNER special value [page 90]


SQL special value that returns the owner of the current procedure, or NULL if queried outside of a
procedure context.

SESSION USER special value [page 91]

SAP IQ SQL Reference


84 INTERNAL SQL Language Elements
SQL special value that stores the user that is currently logged in.

SQLCODE Special Value [page 91]


SQLCODE returns the current SQLCODE value.

SQLSTATE Special Value [page 92]


SQLSTATE returns the current SQLSTATE value.

TIMESTAMP Special Value [page 92]


TIMESTAMP indicates when each row in the table was last modified.

USER Special Value [page 93]


USER returns a string that contains the user ID of the current connection.

Related Information

Expressions [page 40]

2.7.1 CURRENT DATABASE Special Value

CURRENT DATABASE returns the name of the current database.

Data Type

STRING

2.7.2 CURRENT DATE Special Value

CURRENT DATE returns the current year, month and day.

Data Type

DATE

Related Information

TIMESTAMP Special Value [page 92]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 85
CURRENT TIMESTAMP Special Value [page 87]
CURRENT TIME Special Value [page 86]
Date and Time Data Types [page 130]
Retrieve Dates and Times [page 133]

2.7.3 CURRENT PUBLISHER Special Value

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

Data Type

STRING

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

2.7.4 CURRENT TIME Special Value

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

Data Type

TIME

Description

The fraction of a second is stored to 6 decimal places, but the accuracy of the current time is limited by the
accuracy of the system clock.

Related Information

TIMESTAMP Special Value [page 92]


CURRENT TIMESTAMP Special Value [page 87]
CURRENT DATE Special Value [page 85]
Date and Time Data Types [page 130]

SAP IQ SQL Reference


86 INTERNAL SQL Language Elements
Retrieve Dates and Times [page 133]

2.7.5 CURRENT TIMESTAMP Special Value

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

As with CURRENT TIME, the accuracy of the fraction of a second is limited by the system clock.

CURRENT TIMESTAMP defaults to 3 digits.

Data Type

TIMESTAMP

Related Information

TIMESTAMP Special Value [page 92]


CURRENT TIME Special Value [page 86]
CURRENT DATE Special Value [page 85]
Date and Time Data Types [page 130]
Retrieve Dates and Times [page 133]
CURRENT USER Special Value [page 87]
LAST USER Special Value [page 89]
USER Special Value [page 93]

2.7.6 CURRENT USER Special Value

CURRENT USER returns a string that contains the user ID of the current connection.

On UPDATE, columns with a default value of CURRENT USER are not changed.

Data Type

STRING

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

SAP IQ SQL Reference


SQL Language Elements INTERNAL 87
Related Information

CURRENT TIMESTAMP Special Value [page 87]


LAST USER Special Value [page 89]
USER Special Value [page 93]

2.7.7 EXECUTING USER special value

SQL special value that returns the current effective user.

Data type

STRING

Remarks

Use EXECUTING USER, INVOKING USER, SESSION USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of
nesting a particular procedure call has, and based on whether the previous and current procedure are SQL
SECURITY DEFINER or SQL SECURITY INVOKER, the EXECUTING USER, and INVOKING USER can and do
change.

EXECUTING_USER is equivalent to EXECUTING USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SAP IQ SQL Reference


88 INTERNAL SQL Language Elements
2.7.8 INVOKING USER special value

SQL special value that returns the user that invoked the current procedure, or returns the current logged in
user if no procedure is executing.

Data type

STRING

Remarks

Use INVOKING USER, SESSION USER, EXECUTING USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of
nesting a particular procedure call has, and based on whether the previous and current procedure are SQL
SECURITY DEFINER or SQL SECURITY INVOKER, the INVOKING USER and EXECUTING USER can and do
change.

INVOKING_USER is equivalent to INVOKING USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

2.7.9 LAST USER Special Value

LAST USER returns the name of the user who last modified the row.

On INSERT and LOAD, this constant has the same effect as CURRENT USER. On UPDATE, if a column with a
default value of LAST USER is not explicitly modified, it is changed to the name of the current user.

When combined with the DEFAULT TIMESTAMP, a default value of LAST USER can be used to record (in
separate columns) both the user and the date and time a row was last changed.

Data Type

STRING

SAP IQ SQL Reference


SQL Language Elements INTERNAL 89
LAST USER can be used as a default value in columns with character data types.

Related Information

CURRENT USER Special Value [page 87]


CURRENT TIMESTAMP Special Value [page 87]
USER Special Value [page 93]

2.7.10 PROCEDURE OWNER special value

SQL special value that returns the owner of the current procedure, or NULL if queried outside of a procedure
context.

Data type

STRING

Remarks

Use PROCEDURE OWNER, INVOKING USER, SESSION USER, and EXECUTING USER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of
nesting a particular procedure call has, and based on whether the previous and current procedure are SQL
SECURITY DEFINER or SQL SECURITY INVOKER, the EXECUTING USER and INVOKING USER can and do
change.

PROCEDURE_OWNER is equivalent to PROCEDURE OWNER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SAP IQ SQL Reference


90 INTERNAL SQL Language Elements
2.7.11 SESSION USER special value

SQL special value that stores the user that is currently logged in.

Data type

STRING

Remarks

Use SESSION USER, INVOKING USER, EXECUTING USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of
nesting a particular procedure call has, and based on whether the previous and current procedure are SQL
SECURITY DEFINER or SQL SECURITY INVOKER, the INVOKING USER, and EXECUTING USER can and do
change. However, SESSION USER always remains the logged in user.

SESSION_USER is equivalent to SESSION USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

2.7.12 SQLCODE Special Value

SQLCODE returns the current SQLCODE value.

The SQLCODE value is set after each statement. You can check the SQLCODE to see whether or not the
statement succeeded.

Data Type

STRING

SAP IQ SQL Reference


SQL Language Elements INTERNAL 91
2.7.13 SQLSTATE Special Value

SQLSTATE returns the current SQLSTATE value.

The SQLSTATE value is set after each statement. You can check the SQLSTATE to see whether or not the
statement succeeded.

Data Type

STRING

2.7.14 TIMESTAMP Special Value

TIMESTAMP indicates when each row in the table was last modified.

When a column is declared with DEFAULT TIMESTAMP, a default value is provided for insert and load
operations. The value is updated with the current date and time whenever the row is updated.

On INSERT and LOAD, DEFAULT TIMESTAMP has the same effect as CURRENT TIMESTAMP. On UPDATE, if a
column with a default value of TIMESTAMP is not explicitly modified, the value of the column is changed to the
current date and time.

 Note

SAP IQ does not support DEFAULT values of UTC TIMESTAMP or CURRENT UTC TIMESTAMP, nor does it
support the database option DEFAULT_TIMESTAMP_INCREMENT. SAP IQ generates an error every time an
attempt is made to insert or update the DEFAULT value of a column of type UTC TIMESTAMP or CURRENT
UTC TIMESTAMP.

Data Type

TIMESTAMP

Related Information

CURRENT TIMESTAMP Special Value [page 87]


CURRENT TIME Special Value [page 86]
CURRENT DATE Special Value [page 85]
Date and Time Data Types [page 130]
Retrieve Dates and Times [page 133]

SAP IQ SQL Reference


92 INTERNAL SQL Language Elements
2.7.15 USER Special Value

USER returns a string that contains the user ID of the current connection.

On UPDATE, columns with a default value of USER are not changed.

Data Type

STRING

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

Related Information

CURRENT USER Special Value [page 87]


CURRENT TIMESTAMP Special Value [page 87]
LAST USER Special Value [page 89]

2.8 %TYPE and %ROWTYPE attributes

In addition to explicitly setting the data type for an object, you can also set the data type by specifying the
%TYPE and %ROWTYPE attributes.

Use the %TYPE and %ROWTYPE attributes when creating or declaring variables, converting values, creating or
altering tables, and creating procedures, to define the data type(s) based on the data type of a column or row in
a table, view, or cursor. The %TYPE attribute sets the data type to that of a column in the specified object,
while the %ROWTYPE attribute sets the data types to those of a row in the specified object.

When %TYPE or %ROWTYPE is specified for a schema object, the database server derives the actual data type
information from system tables. For example, if a %TYPE attribute specifies a table column, the data type is
retrieved from the ISYSTABCOL system table.

Once the data types have been derived and the object (variable, column, and so on) is created, there is no
further link or dependency to the object referenced in the %TYPE and %ROWTYPE attribute. However, in the
case of procedures that use %TYPE and %ROWTYPE to define parameters and return types, the procedure
can return different results if the underlying referenced objects change. This is because %TYPE and
%ROWTYPE are evaluated when the procedure is executed, not when it is created.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 93
Tables and views

Specify the %TYPE attribute to set the data type of a column to the data type of a column in another table or
view. For example:

● myColumnName <other-table-name>.<column-name>%TYPE

The second statement in the following example creates a table, myT2, and sets the data type of its column,
myColumn, to the data type of the last_name column in myT1. Since additional attributes such as nullability are
not applied, myT2.myColumn will not have the same NOT NULL restriction that myT1.last_name does.

CREATE TABLE myT1


( first_name CHAR(20),
last_name VARCHAR NOT NULL );
CREATE TABLE myT2
( myColumn myT1.last_name%TYPE );

Procedures and functions

Specify the %TYPE or %ROWTYPE attribute to set the data type(s) of the parameters to the data type(s) of a
column or row in a specified table or view.

The following statement creates a procedure, DepartmentsCloseToCustomerLocation, and sets its IN


parameter to the data type of the ID column in the Customers table:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN customer_ID


Customers.ID%TYPE )
BEGIN
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

The following statement creates a function called fullname and sets the data types of the firstname and
lastname parameters to the data types of the Surname and Givenname column of the Employees table:

CREATE OR REPLACE FUNCTION fullname(


firstname Employees.Surname%TYPE,
lastname Employees.GivenName%TYPE )
RETURNS LONG VARCHAR
BEGIN
RETURN ( firstname || ' ' || lastname );
END;
SELECT fullname ( Surname, GivenName )FROM GROUPO.Employees;

SAP IQ SQL Reference


94 INTERNAL SQL Language Elements
Casting and converting values

Specify the %TYPE attribute when to cast or convert a value to the data type of another database object.

The following statement casts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:

SELECT CAST ( '1966-10-30' AS Employees.BirthDate%TYPE );

Domains

Specify the %TYPE attribute to set the domain data type to the data type of a column in a specified table or
view.

In the following example, the second two CREATE DOMAIN statements in the following set of statements
create domains based on the data types of the Surname and GivenName columns of the Customers table.

CREATE DOMAIN identifier UNSIGNED INT


DEFAULT AUTOINCREMENT;
CREATE DOMAIN customers_surname Customers.Surname%TYPE;
CREATE DOMAIN customers_givenname Customers.GivenName%TYPE;

CREATE TABLE Customers3 (


ID identifier PRIMARY KEY,
SurName customers_surname,
GivenName customers_givenname
);

Variables

Specify the %TYPE attribute to set the data type of a variable to the data type of a column in a specified table,
view, or cursor. When %TYPE is used, only the data type is derived from the referenced object. Other column
attributes such as default values, constraints, and whether NULLs are allowed, are not included and must be
specified separately. Use the %TYPE attribute to declare a variable with the same type as column data when
you want your application to be able to adjust to changes to an underlying table schema.

The following example creates a new variable, ProductID, and uses the %TYPE attribute to set its data type to
the data type of the ID column in the Products table:

CREATE VARIABLE ProductID Products.ID%TYPE;

Specify the %ROWTYPE attribute to set the data type of a set of columns to the data types of a row in a
specified table, view, or cursor. For example, use the %ROWTYPE attribute to define a variable that can store
row or array values.

When %ROWTYPE is specified, other column attributes such as default values, constraints, and whether
NULLs are allowed, are not included in the derivation.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 95
The following example uses the %ROWTYPE attribute to create a variable, @a_product, and then inserts data
from the Products table into the variable:

CREATE OR REPLACE PROCEDURE CheckStock (


IN @id Products.ID%TYPE
)
BEGIN
DECLARE @a_product Products%ROWTYPE;
SET (@a_product).ID = 200;
END;

You can also use the %TYPE attribute to set the data type of a variable to type of another variable, as shown in
the second DECLARE statement in this example:

DECLARE cust_rec Customers%ROWTYPE;


DECLARE cust_rec2 cust_rec%TYPE;

In this section:

%TYPE attribute syntax [page 96]


Sets the data type to that of a column in a specified object or variable when creating or declaring
variables, or creating or altering tables, views, procedures, and functions. It can also be used for casting
data from one type to another.

%ROWTYPE attribute syntax [page 98]


Sets the data type to the composite data type of a row in a specified table, view, table reference
variable, or cursor.

2.8.1 %TYPE attribute syntax

Sets the data type to that of a column in a specified object or variable when creating or declaring variables, or
creating or altering tables, views, procedures, and functions. It can also be used for casting data from one type
to another.

 Syntax

<type-source>%TYPE
| TYPE OF ( <type-source> )
<type-source> :
[ <owner>. ]{ <table-name>
| <view-name> }.<column-name>
| <variable-name>
| <variable-name>.<field-name>

Parameters

table-name

The name of a table.


view-name

SAP IQ SQL Reference


96 INTERNAL SQL Language Elements
The name of an enabled view (including materialized views). Materialized views must be initialized as well.
variable-name

The name of a variable.


column-name

The name of a column.

Remarks

When creating or altering procedures (parameters and return types), tables, views, and domains, an object
that is referenced in a %TYPE specification must be a permanent object. A reference to a temporary object,
such as a variable, cursor, or temporary table returns an error.

When %TYPE is specified in an IS OF search expression, a WITH <hint> expression in a FROM clause, or a
CAST or CONVERT function, the referenced item must be a permanent object. Specifying a correlation name
or a derived table returns an error.

When %TYPE is specified, other attributes, such as default values, constraints, and whether NULLs are
allowed, are not part of the definition that is inherited and must be specified separately.

When defining or declaring a variable, if the identifier portion of <type-source> is one of the following, then
the identifier portion must be quoted:

● IN
● OUT
● INOUT
● DYNAMIC
● SCROLL
● NO
● INSENSITIVE
● SENSITIVE
● TIMESTAMP
● a name that starts with #

For example, the statement below declares a variable called DYNAMIC. It then declares another variable called
var1, and sets its data type to that of DYNAMIC (INT). Since DYNAMIC is one of the keywords that must be
quoted, quotes are placed around it:

BEGIN
DECLARE dynamic INT;
DECLARE var1 "DYNAMIC"%TYPE;
SET var1 = 1;
MESSAGE var1;
END

Privileges

None.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 97
Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

In addition to the following examples, there are examples in the documentation for the SQL statements and
functions that support specifying the %TYPE attribute.

The following statement creates a procedure, DepartmentsCloseToCustomerLocation, and sets its IN


parameter to the data type of the ID column in the Customers table using a %TYPE attribute:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN


customer_ID Customers.ID%TYPE )
BEGIN
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

The following statement casts a value to the data type defined for the BirthDate column (DATE data type)
of the Employees table:

SELECT CAST ( '1966-10-30' AS Employees.BirthDate%TYPE );

2.8.2 %ROWTYPE attribute syntax

Sets the data type to the composite data type of a row in a specified table, view, table reference variable, or
cursor.

 Syntax

<rowtype-source>%ROWTYPE
| ROWTYPE OF ( <rowtype-source> )
<rowtype-source> :
[ <owner>. ]{ <table-name> | <view-name> }

SAP IQ SQL Reference


98 INTERNAL SQL Language Elements
| <cursor-name>
| TABLE REF ( <table-reference-variable> )

Parameters

table-name

The name of a table.

When specifying <table-name>, the data type of the %ROWTYPE variable is comprised of the data types
of the columns in <table-name>.
view-name

The name of an enabled view (including materialized views). Materialized views must be initialized as well.

When specifying <view-name>, the data type of the %ROWTYPE variable is comprised of the data types
of the columns in <view-name>.
cursor-name

The name of a cursor.

When specifying <cursor-name>, the data type of the %ROWTYPE variable is comprised of the data
types of the select items for the cursor.
table-reference-variable

The name of a table reference variable.

When specifying a table reference variable, the data type of the %ROWTYPE variable is comprised of the
data types of the columns in the table referenced in <table-reference-variable>.

Remarks

When creating a %ROWTYPE variable, other attributes, such as default values, constraints, and whether
NULLs are allowed, are not part of the definition that is inherited, and must be specified separately.

Restrictions when specifying %ROWTYPE with a table, view, or cursor reference:

When creating or altering procedures, views, and domains, an object referenced in a %ROWTYPE
specification must be a permanent object. A reference to a temporary table returns an error.

If you declare a row variable and the argument to the %ROWTYPE construct is a cursor which is not yet
opened, it is possible that the schema of the cursor will be different at open time if any of the underlying
objects have changed. It is safer to declare row variables based on cursors that are already open.

When %ROWTYPE is specified in an IS OF search expression, a WITH <hint> expression in a FROM


clause, or a CAST or CONVERT function, the referenced item must be a permanent object. Specifying a
temporary table, correlation name, or a derived table, returns an error.

When <rowtype-source> references a cursor, the names of the items in the cursor (for example, column
names) must be simple names, or an alias. If the select list item names in the cursor cannot be
successfully derived, then an error is returned.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 99
When defining or declaring a variable, if the identifier portion of <rowtype-source> is one of the
following, then the identifier portion must be quoted:

● IN
● OUT
● INOUT
● DYNAMIC
● SCROLL
● NO
● INSENSITIVE
● SENSITIVE
● TIMESTAMP
● identifiers that start with #
Restrictions when specifying %ROWTYPE with a table reference variable (TABLE REF (table-
reference-variable) %ROWTYPE):

Specifying %ROWTYPE with a table reference variable is not supported: when creating or altering
procedures, views, and domains. Similarly, specifying %ROWTYPE with a table reference variable is not
supported in an IS OF search expression, or in a WITH <hint> expression in a FROM clause, or in a CAST
or CONVERT function.

When <rowtype-source> references a table reference variable, the table reference variable must already
be initialized when the %ROWTYPE is processed. If TABLE REF (<table-reference-variable>)
%ROWTYPE is used in a statement that is in a batch or procedure, statement must be nested inside another
BEGIN...END block after the table reference variable has been assigned a value or passed as a parameter.

Privileges

None.

Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

In addition to the following examples, there are examples in the documentation for the SQL statements and
functions that support specifying the %ROWTYPE attribute.

SAP IQ SQL Reference


100 INTERNAL SQL Language Elements
The following example creates a new variable, ItemsForSale, and uses the %ROWTYPE attribute to set its
data type to a composite data type comprised of the columns defined for the Products table:

CREATE VARIABLE ItemsForSale Products%ROWTYPE;

The following statement declares a variable, cust_rec, and sets its data type to the composite data type of a
row in the Customers table:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN


customer_ID Customers.ID%TYPE )
BEGIN
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

2.9 SQL variables


The supported variables can be grouped by scope: connection, database, and global.

When a variable is created, the initial value is set to NULL unless a default is specified. The value can
subsequently be changed by using the SET statement, the UPDATE statement, or a SELECT statement with an
INTO clause.

Variables are not affected by COMMIT or ROLLBACK statements.

Connection-scope variables

Connection-scope variables are set and used in the context of a connection. They are not available to other
connections. There are two types of connection-scope variables: connection-level and local (also referred
to as declared). You can also create connection-scope variables of type TABLE REF to hold references to
tables; these are called table reference variables.

Connection-level variables

Connection-level variables are created by using the CREATE VARIABLE statement and are typically
used to make values available to any procedure executed by the connection.

Connection-level variables persist only for the duration of the connection or until the variable is
explicitly dropped by using the DROP VARIABLE statement

Local (declared) variables

Local variables are created by using the DECLARE statement inside of a BEGIN...END block, and are
typically used to store and modify values within the same compound statement that the local variable
is declared in. Local variable values are not available for use outside of the context of the BEGIN...END
block.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 101
Local variables persist only for the duration of the BEGIN...END block in which they are declared, and
they can also be dropped.
Database-scope variables

Database-scope variables are used in the context of the database (instead of connection), and are a great
way to share values across connections. Their intended use is to store small, infrequently changing, shared
values. Storing large or frequently changing values may affect the performance of your application, and is
not recommended. The initial values of database-scope variables persist after the database restarts (that
is, changes to their initial value do not persist between database restarts). Database-scope variables can
be used in the same manner as connection-scope and global variables, but they cannot be defined with the
data type ROW, ARRAY, or TABLE REF.

Database-scope variables owned by users

When a database-scope variable is owned by a user, only that user can select from, and update, that
variable, and can do so regardless of the connection.

Database-scope variables can also be owned by a role. However, the only access to a database-scope
variable owned by a role is through the stored procedures, user-defined functions, and events owned
by that role.
Database-scope variables owned by PUBLIC

Database variables owned by PUBLIC are available to all users and connections provided the users
have the right system privileges.

Access to, and administration of, database-scope variables requires system privileges that vary depending
on who owns the variable (self, another user, or PUBLIC). The following table summarizes the privileges
required to access and administer database-scope variables:

Table 1: Privileges required for administering database-scope variables


Action Owned by Privilege required

Create a database-scope variable self CREATE DATABASE VARIABLE or


MANAGE ANY DATABASE VARIABLE

Create a database-scope variable another user MANAGE ANY DATABASE VARIABLE

Create a database-scope variable PUBLIC MANAGE ANY DATABASE VARIABLE

Update a database-scope variable self none required

Update a database-scope variable another user not allowed

Update a database-scope variable PUBLIC UPDATE PUBLIC DATABASE VARIA­


BLE

Select from a database-scope variable self none

Select from a database-scope variable another user not allowed

Select from a database-scope variable PUBLIC SELECT PUBLIC DATABASE VARIA­


BLE

Drop a database-scope variable self none required

Drop a database-scope variable another user MANAGE ANY DATABASE VARIABLE

Drop a database-scope variable PUBLIC MANAGE ANY DATABASE VARIABLE

Global variables

SAP IQ SQL Reference


102 INTERNAL SQL Language Elements
Global variables are used in the context of the database, but can only be set by the database server.
Although you cannot directly set a global variable, some global variable values are indirectly set in response
to user activity. For example, some global variables, such as @@identity, hold connection-specific
information, while other variables, such as @@connections, have values that are common to all
connections.

Global variables are visually distinguished from other variables by having two @ signs preceding their
names. For example, @@error and @@rowcount are global variables.

Variables and aliases with identical names

It is possible to have a statement that has aliases and variables with identical names. This is the sequence the
database server follows when processing an identifier to help you know how the reference is resolved:

1. Match any aliases specified in the query SELECT list.


2. Match column names for any referenced tables.
3. Assume the name is a variable.

Standards

ANSI/ISO SQL Standard

Variables declared within SQL stored procedures or functions by using the DECLARE statement is
supported in the ANSI/ISO SQL Standard as SQL Language Feature P002, "Computational
completeness". CREATE VARIABLE, DROP VARIABLE, and global variables are not in the ANSI/ISO SQL
Standard.

2.10 Variables

SAP IQ supports local variables, connection-level variables, and global variables.

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.

In this section:

Local Variables [page 104]


Local variables are declared by the user, and can be used in procedures or in batches of SQL
statements to hold information.

Connection-Level Variables [page 105]


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 [page 106]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 103
Global variables are system-supplied variables that provide system-supplied values.

2.10.1 Local Variables

Local variables are declared by the user, and can be used in procedures or in batches of SQL statements to hold
information.

Local variables are declared using the DECLARE statement, which can be used only within a compound
statement (that is, bracketed by the BEGIN and END keywords). The variable is initially set as NULL. You can set
the value of the variable using the SET statement, or you can assign the value using a SELECT statement with
an INTO clause.

The syntax of the DECLARE statement is as follows:

DECLARE variable-name data-type

You can pass local variables 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 ;
END

Running this batch from ISQL displays this message on the server window:

local_var = 10

● The variable local_var does not exist outside the compound statement in which it is declared. The
following batch is invalid, and displays a "column not found" error:

-- This batch is invalid.


BEGIN
DECLARE local_var INT ;
SET local_var = 10 ;
MESSAGE 'local_var = ', local_var ;
END;
MESSAGE 'local_var = ', local_var ;

● The following example illustrates the use of SELECT with an INTO clause to set the value of a local variable:

BEGIN
DECLARE local_var INT ;
SELECT 10 INTO local_var ;
MESSAGE 'local_var = ', local_var ;
END

SAP IQ SQL Reference


104 INTERNAL SQL Language Elements
Running this batch from ISQL displays this message on the server window:

local_var = 10

Compatibility

● Names – Both SAP Adaptive Server Enterprise and SAP IQ support local variables. In SAP ASE, the all
variables require an @ sign as their prefix. In SAP IQ, the @ prefix is optional. To write compatible SQL,
ensure all your variables have the @ prefix.
● Scope – The scope of local variables differs between SAP IQ and SAP ASE. SAP IQ supports the use of the
DECLARE statement to declare local variables within a batch. However, if the DECLARE is executed within a
compound statement, the scope is limited to the compound statement.
● Declaration – Only one variable can be declared for each DECLARE statement in SAP IQ. In SAP ASE, more
than one variable can be declared in a single statement.

2.10.2 Connection-Level Variables

Connection-level variables are declared by the user, and can be used in procedures or in batches of SQL
statements to hold information.

Connection-level variables are declared with the CREATE VARIABLE statement. The CREATE VARIABLE
statement can be used anywhere except inside compound statements. Connection-level variables can be
passed as parameters to procedures.

The syntax for CREATE VARIABLE is:

CREATE VARIABLE variable-name data-type

When a variable is created, it is initially set to NULL. You can set the value of connection-level variables 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 you explicitly drop the variable 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;

SAP IQ SQL Reference


SQL Language Elements INTERNAL 105
Running this batch from ISQL displays this message on the server window:

con_var = 10

Compatibility

SAP Adaptive Server Enterprise does not support connection-level variables.

2.10.3 Global Variables

Global variables are system-supplied variables that provide system-supplied values.

SAP IQ sets the values of global variables. 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 two @ signs preceding their
names. For example, <@@error> is a global variable. Users cannot create global variables, and cannot update
the value of global variables directly.

Some global variables, such as <@@spid>, hold connection-specific information and therefore have
connection-specific values. Other variables, such as <@@connections>, have values that are common to all
connections.

Global Variable and Special Constants

The special constants such as CURRENT DATE, CURRENT TIME, USER, SQLSTATE, and so on, are similar to
global variables.

The following statement retrieves the value of the version global variable:

SELECT @@version

In procedures, global variables can be selected into a variable list. The following procedure returns the server
version number in the <ver> parameter:

CREATE PROCEDURE VersionProc ( OUT ver


VARCHAR ( 100) )
BEGIN
SELECT @@version
INTO ver;
END

In Embedded SQL, global variables can be selected into a host variable list.

SAP IQ SQL Reference


106 INTERNAL SQL Language Elements
List of Global Variables

This table lists the global variables available in SAP IQ.

Variable Name Meaning

<@@error> Commonly used to check the error status (succeeded or failed) of the most recently exe­
cuted statement. Contains 0 if the previous transaction succeeded; otherwise, contains the
last error number generated by the system. A statement such as if <@@error> != 0
return causes an exit if an error occurs. Every SQL statement resets <@@error>, so the sta­
tus check must immediately follow the statement whose success is in question.

<@@fetch_status> Contains status information resulting from the last fetch statement. <@@fetch_status>
may contain the following values:

● 0 – the fetch statement completed successfully


● -1 – the fetch statement resulted in an error
● -2 – there is no more data in the result set

This feature is the same as <@@sqlstatus>, except that it returns different values. It is for
Microsoft SQL Server compatibility.

<@@identity> The last value inserted into an Identity/Autoincrement column by an insert, load, or update
statement. <@@identity> is reset each time a row is inserted into a table. If a statement
inserts multiple rows, <@@identity> reflects the Identity/Autoincrement value for the last
row inserted. If the affected table does not contain an Identity/Autoincrement column,
<@@identity> is set to 0.

The value of <@@identity> is not affected by the failure of an insert, load, or update state­
ment, or the rollback of the transaction that contained the failed statement. <@@identity>
retains the last value inserted into an Identity/Autoincrement column, even if the statement
that inserted that value fails to commit.

<@@isolation> Current isolation level. <@@isolation> takes the value of the active level.

<@@procid> Stored procedure ID of the currently executing procedure.

<@@rowcount> Number of rows affected by the last statement. The value of <@@rowcount> should be
checked immediately after the statement. Inserts, updates, and deletes set <@@rowcount>
to the number of rows affected.

With cursors, <@@rowcount> represents the cumulative number of rows returned from the
cursor result set to the client, up to the last fetch request. The <@@rowcount> is not reset
to zero by any statement, which does not affect rows, such as an IF statement.

<@@servername> Name of the current database server.

<@@sqlstatus> Contains status information resulting from the last FETCH statement.

<@@version> Version number of the current version of SAP IQ.

In this section:

SAP IQ SQL Reference


SQL Language Elements INTERNAL 107
SAP ASE Global Variables Supported in SAP IQ [page 108]
This table includes all SAP Adaptive Server Enterprise global variables that are supported in SAP IQ.
SAP Adaptive Server Enterprise global variables that are not supported by SAP IQ are not included in
the list.

2.10.3.1 SAP ASE Global Variables Supported in SAP IQ

This table includes all SAP Adaptive Server Enterprise global variables that are supported in SAP IQ. SAP
Adaptive Server Enterprise global variables that are not supported by SAP IQ are not included in the list.

This list includes all global variables that return a value, including those for which the value is fixed at NULL, 1,
-1, or 0, and might not be meaningful.

@@char_convert

Returns 0.
@@client_csname

● In SAP ASE – the client's character set name. Set to NULL if client character set has never been
initialized; otherwise, contains the name of the most recently used character set.
● In SAP IQ – returns NULL.
@@client_csid

● In SAP ASE – the client's character set ID. Set to -1 if client character set has never been initialized;
otherwise, contains the most recently used client character set ID from syscharsets.
● In SAP IQ – returns -1.
@@connections

The number of logins since the server was last started.


@@cpu_busy

● In SAP ASE – the amount of time, in ticks, that the CPU has spent performing SAP ASE work since the
last time SAP ASE was started.
● In SAP IQ – returns 0.
@@error

Commonly used to check the error status (succeeded or failed) of the most recently executed statement.
Contains 0 if the previous transaction succeeded; otherwise, contains the last error number generated by
the system. A statement such as the following causes an exit if an error occurs:

if @@error != 0 return

Every statement resets <@@error>, including PRINT statements or IF tests, so the status check must
immediately follow the statement whose success is in question.
@@identity

In SAP ASE – the last value inserted into an IDENTITY column by an INSERT, LOAD, or SELECT INTO
statement. <@@identity> is reset each time a row is inserted into a table. If a statement inserts multiple
rows, <@@identity> reflects the IDENTITY value for the last row inserted. If the affected table does not
contain an IDENTITY column, <@@identity> is set to 0. The value of <@@identity> is not affected by
the failure of an INSERT or SELECT INTO statement, or the rollback of the transaction that contained the

SAP IQ SQL Reference


108 INTERNAL SQL Language Elements
failed statement. <@@identity> retains the last value inserted into an IDENTITY column, even if the
statement that inserted that value fails to commit.
@@idle

● In SAP ASE – the amount of time, in ticks, that SAP ASE has been idle since the server was last started.
● In SAP IQ – returns 0.
@@io_busy

● In SAP ASE – the amount of time, in ticks, that SAP ASE has spent performing input and output
operations since the server was last started.
● In SAP IQ – returns 0.
@@isolation

Current isolation level of the connection.

● In SAP ASE – takes the value of the active level.


@@langid

● In SAP ASE – defines the local language ID of the language currently in use.
● In SAP IQ – returns 0.
@@language

● In SAP ASE – defines the name of the language currently in use.


● In SAP IQ – returns “English.”
@@maxcharlen

● In SAP ASE – maximum length, in bytes, of a character in the SAP ASE default character set.
● In SAP IQ – returns 1.
@@max_connections

For the network server, the maximum number of active clients (not database connections, as each client
can support multiple connections).

● In SAP ASE – the maximum number of connections to the server.


@@ncharsize

● In SAP ASE – average length, in bytes, of a national character.


● In SAP IQ – returns 1.
@@nestlevel

● In SAP ASE – nesting level of current execution (initially 0). Each time a stored procedure or trigger
calls another stored procedure or trigger, the nesting level is incremented.
● In SAP IQ – returns -1.
@@pack_received

● In SAP ASE – number of input packets read by SAP ASE since the server was last started.
● In SAP IQ – returns 0.
@@pack_sent

● In SAP ASE – number of output packets written by SAP ASE since the server was last started.
● In SAP IQ – returns 0.
@@packet_errors

● In SAP ASE – number of errors that have occurred while SAP ASE was sending and receiving packets.

SAP IQ SQL Reference


SQL Language Elements INTERNAL 109
● In SAP IQ – returns 0.
@@procid

Stored procedure ID of the currently executing procedure.


@@servername

Name of the local SAP ASE or SAP IQ server.


@@spid

● In SAP ASE – server process ID number of the current process.


● In SAP IQ – the connection handle for the current connection. This is the same value as that displayed
by the sa_conn_info procedure.
@@sqlstatus

Contains status information resulting from the last FETCH statement. <@@sqlstatus> may contain the
following values:

● 0 – the FETCH statement completed successfully.


● 1 – the FETCH statement resulted in an error.
● 2 – there is no more data in the result set.
@@thresh_hysteresis

● In SAP ASE – change in free space required to activate a threshold.


● In SAP IQ – returns 0.
@@timeticks

● In SAP ASE – number of microseconds per tick. The amount of time per tick is machine-dependent.
● In SAP IQ – returns 0.
@@total_errors

● In SAP ASE – number of errors that have occurred while SAP ASE was reading or writing.
● In SAP IQ – returns 0.
@@total_read

● In SAP ASE – number of disk reads by SAP ASE since the server was last started.
● In SAP IQ – returns 0.
@@total_write

● In SAP ASE – number of disk writes by SAP ASE since the server was last started.
● In SAP IQ – returns 0.
@@tranchained

Current transaction mode of the Transact-SQL program. <@@tranchained> returns 0 for unchained or 1
for chained.
@@trancount

Nesting level of transactions. Each BEGIN TRANSACTION in a batch increments the transaction count.
@@transtate

● In SAP ASE – current state of a transaction after a statement executes.


● In SAP IQ – returns -1.
@@version

Information about the current version of SAP ASE or SAP IQ.

SAP IQ SQL Reference


110 INTERNAL SQL Language Elements
2.11 Comments

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

These comment indicators are available in SAP IQ:

Comment Indicator Description

-- (Double hyphen) The database server ignores any remaining characters on the line. This is the SQL92 com­
ment indicator.

// (Double slash) The double slash has the same meaning as the double hyphen.

/* … */ (Slash-asterisk) Any characters between the two comment markers are ignored. The two comment markers
might be on the same or different lines. Comments indicated in this style can be nested.
This style of commenting is also called C-style comments.

% (Percent sign) The percent sign has the same meaning as the double hyphen. You should not use % as a
comment indicator.

 Note

The double-hyphen and the slash-asterisk comment styles are compatible with SAP Adaptive Server
Enterprise.

Examples

This example illustrates the use of double-dash comments:

CREATE FUNCTION fullname (firstname CHAR(30),


lastname CHAR(30))
RETURNS CHAR(61)
-- fullname concatenates the firstname and lastname
-- arguments with a single space between.
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ' ' || lastname;
RETURN ( name );
END

This example illustrates the use of C-style comments:

/*
Lists the names and employee IDs of employees
who work in the sales department.
*/
CREATE VIEW SalesEmployee AS
SELECT emp_id, emp_lname, emp_fname
FROM "GROUPO".Employees
WHERE DepartmentID = 200

SAP IQ SQL Reference


SQL Language Elements INTERNAL 111
2.12 NULL Value

Use NULL to specify a value that is unknown, missing, or not applicable.

The NULL value 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. These are two separate and distinct cases where NULL is used:

Situation Description

missing The field does have a value, but that value is unknown.

inapplicable The field does not apply for this particular row.

SQL allows columns to be created with the NOT NULL restriction. This means that those particular columns
cannot contain the NULL value.

The NULL value introduces the concept of three valued logic to SQL. The NULL value compared using any
comparison operator with any value including the NULL value is UNKNOWN. The only search condition that
returns TRUE is the IS NULL predicate. In SQL, rows are selected only if the search condition in the WHERE
clause evaluates to TRUE; rows that evaluate to UNKNOWN or FALSE are not selected.

You can also use the IS [ NOT ] <truth-value> clause, where <truth-value> is one of TRUE, FALSE or
UNKNOWN, to select rows where the NULL value is involved.

In the following examples, the column Salary contains the NULL value.

Condition Truth Value Selected?

Salary = NULL UNKNOWN NO

Salary <> NULL UNKNOWN NO

NOT (Salary = NULL) UNKNOWN NO

NOT (Salary <> NULL) UNKNOWN NO

Salary = 1000 UNKNOWN NO

Salary IS NULL TRUE YES

Salary IS NOT NULL FALSE NO

Salary = 1000 IS UNKNOWN TRUE YES

The same rules apply when comparing columns from two different tables. Therefore, joining two tables
together does not select rows where any of the columns compared contain the NULL value.

The NULL value also has an interesting property when used in numeric expressions. The result of any numeric
expression involving the NULL value is the NULL value. This means that if the NULL value is added to a number,
the result is the NULL value—not a number. If you want the NULL value to be treated as 0, you must use the
ISNULL( expression, 0 ) function.

SAP IQ SQL Reference


112 INTERNAL SQL Language Elements
Many common errors in formulating SQL queries are caused by the behavior of NULL. Be careful to avoid these
problem areas. Note the effect of three-valued logic when combining search conditions.

 Syntax

NULL

Remarks

Anywhere

Permissions

Must be connected to the database

Side Effects

None

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' )

Related Information

Comparison Conditions [page 59]


Expressions [page 40]
Search Conditions [page 57]
Strings [page 38]
Three-Valued Logic [page 60]
SQL Operators [page 44]

SAP IQ SQL Reference


SQL Language Elements INTERNAL 113
Subqueries in Search Conditions [page 62]

SAP IQ SQL Reference


114 INTERNAL SQL Language Elements
3 SQL Data Types

SQL data types define the type of data to be stored, such as character strings, numbers, and dates.

In this section:

Character Data Types [page 115]


Use character data types for storing strings of letters, numbers and symbols.

Numeric Data Types [page 119]


Use numeric data types for storing numerical data.

Binary Data Types [page 123]


Use binary data types for storing raw binary data, such as pictures, in a hexadecimal-like notation, up
to a length of (32 K – 1) bytes.

Bit Data Type [page 129]


Use the BIT data type for storing Boolean values.

Date and Time Data Types [page 130]


Use date and time data types for storing dates and times.

TABLE REF data type [page 135]


The TABLE REF data type stores a reference to a base table, temporary table, or view. This data type is
only for use with connection-scope variables.

Domains [page 138]


Domains are aliases for built-in data types, including precision and scale values where applicable.

Data Type Conversions [page 143]


Type conversions happen automatically, or you can explicitly request them using the CAST or CONVERT
function.

Compatibility of String to Datetime Conversions [page 144]


There are some differences in behavior between SAP IQ and SAP Adaptive Server Enterprise when
converting strings to date and time data types.

3.1 Character Data Types

Use character data types for storing strings of letters, numbers and symbols.

The character data types and their descriptions are:

● CHAR [ ( <max-length> ) ]

Character data of maximum length <max-length> bytes. If <max-length> is omitted, the default is 1.
The maximum size allowed is 32KB – 1. See Notes for restrictions on CHAR data greater than 255 bytes.
See the notes below on character data representation in the database, and on storage of long strings.

SAP IQ SQL Reference


SQL Data Types INTERNAL 115
All CHAR values are blank padded up to <max-length>, regardless of whether the BLANK PADDING option
is specified. When multibyte character strings are held as a CHAR type, the maximum length is still in bytes,
not characters.

● CHARACTER [ ( <max-length> ) ]

Same as CHAR.

● CHARACTER VARYING [ ( <max-length> ) ]

Same as VARCHAR.

● TEXT

This is a user-defined data type. It is implemented as a LONG VARCHAR allowing NULL.

● VARCHAR [ ( <max-length> ) ]

Arbitrary length character data. The maximum size is limited by the maximum size of the database file
(currently 2 gigabytes).
VARCHAR is the same as CHAR, except that no blank padding is added to the storage of these strings, and
VARCHAR strings can have a maximum length of (32 KB – 1). See Notes for restrictions on VARCHAR data
greater than 255 bytes.

● UNIQUEIDENTIFIERSTR

Domain implemented as CHAR( 36 ). This data type is used for remote data access, when mapping
Microsoft SQL Server uniqueidentifier columns.

 Note

As a separately licensed option, SAP IQ supports character large object (CLOB) data with a length ranging
from zero (0) to 512 TB (terabytes) for an SAP IQ page size of 128 KB or 2 PB (petabytes) for an SAP IQ
page size of 512 KB. The maximum length is equal to 4 GB multiplied by the database page size. See SAP IQ
Administration: Unstructured Data Analytics.

In this section:

Storage Sizes [page 117]


The storage size of character data, given column definition size and input data size.

Character Sets and Code Pages [page 117]


Character data is placed in the database using the exact binary representation that is passed from the
application.

Indexes [page 118]


All index types, except DATE, TIME, and DTTM, are supported for CHAR data and VARCHAR data less than
or equal to 255 bytes in length.

VARCHAR Data and Trailing Blanks [page 118]


For a column of data type VARCHAR, trailing blanks within the data being inserted are handled
differently depending on whether or not the data is enclosed in quotes.

Restriction on CHAR and VARCHAR Data Over 255 Bytes [page 119]
Only the default index, WD, TEXT, and CMP index types are supported for CHAR and VARCHAR columns
over 255 bytes.

SAP IQ SQL Reference


116 INTERNAL SQL Data Types
Long Strings [page 119]
Values up to 254 characters are stored as short strings, with a preceding length byte. Any values that
are longer than 255 bytes are considered long strings. Characters after the 255th are stored separate
from the row containing the long string value.

Related Information

Binary Data Types [page 123]


NEWID Function [Miscellaneous] [page 432]
STRTOUUID Function [String] [page 533]
UUIDTOSTR Function [String] [page 553]
Binary Data Type Compatibility [page 159]
Character Data Type Compatibility [page 158]

3.1.1 Storage Sizes

The storage size of character data, given column definition size and input data size.

Data Type Column Definition Input Data Storage

CHARACTER, CHAR Width of (32K – 1) bytes (32K – 1) bytes (32K – 1) bytes

VARCHAR, CHARACTER Width of (32K – 1) bytes (32K – 1) bytes (32K – 1) bytes


VARYING

3.1.2 Character Sets and Code Pages

Character data is placed in the database using the exact binary representation that is passed from the
application.

This usually means that character data is stored in the database with the binary representation of the
character set used by your system. You can find documentation about character sets in the documentation for
your operating system.

On Windows, code pages are the same for the first 128 characters. If you use special characters from the top
half of the code page (accented international language characters), you must be careful with your databases. In
particular, if you copy the database to a different machine using a different code page, those special characters
are retrieved from the database using the original code page representation. With the new code page, they
appear on the window to be the wrong characters.

This problem also appears if you have two clients using the same multiuser server, but running with different
code pages. Data inserted or updated by one client might appear incorrect to another.

SAP IQ SQL Reference


SQL Data Types INTERNAL 117
This problem also shows up if a database is used across platforms. PowerBuilder and many other Windows
applications insert data into the database in the standard ANSI character set. If non-Windows applications
attempt to use this data, they do not properly display or update the extended characters.

This problem is quite complex. If any of your applications use the extended characters in the upper half of the
code page, make sure that all clients and all machines using the database use the same or a compatible code
page.

3.1.3 Indexes

All index types, except DATE, TIME, and DTTM, are supported for CHAR data and VARCHAR data less than or
equal to 255 bytes in length.

3.1.4 VARCHAR Data and Trailing Blanks

For a column of data type VARCHAR, trailing blanks within the data being inserted are handled differently
depending on whether or not the data is enclosed in quotes.

Data inserted using INSERT, UPDATE, or LOAD TABLE can be:

● Enclosed in quotes
● Not enclosed in quotes
● Binary

For a column of data type VARCHAR, trailing blanks within the data being inserted are handled as follows:

● For data enclosed in quotes, trailing blanks are never trimmed.


● For data not enclosed in quotes:
○ Trailing blanks always trimmed on insert and update.
○ For a LOAD statement, you can use the STRIP RTRIM/OFF LOAD option to specify whether to have the
trailing blanks trimmed. The STRIP RTRIM/OFF option applies only to variable-length non-binary
data. For example, assume the following schema:

CREATE TABLE t( c1 VARCHAR(3) );


LOAD TABLE t( c1 ',' ) ........ STRIP RTRIM // trailing blanks trimmed
LOAD TABLE t( c1 ',' ) ........ STRIP OFF // trailing blanks not
trimmed
LOAD TABLE t( c1 ASCII(3) ) ... STRIP RTRIM // trailing blanks not
trimmed
LOAD TABLE t( c1 ASCII(3) ) ... STRIP OFF // trailing blanks trimmed
LOAD TABLE t( c1 BINARY ) ..... STRIP RTRIM // trailing blanks trimmed
LOAD TABLE t( c1 BINARY ) ..... STRIP OFF // trailing blanks trimmed

○ For binary data, trailing blanks are always trimmed.

When you write your applications, do not depend on the existence of trailing blanks in VARCHAR columns. If an
application relies on trailing blanks, use a CHAR column instead of a VARCHAR column.

SAP IQ SQL Reference


118 INTERNAL SQL Data Types
3.1.5 Restriction on CHAR and VARCHAR Data Over 255
Bytes

Only the default index, WD, TEXT, and CMP index types are supported for CHAR and VARCHAR columns over 255
bytes.

You cannot create an HG, HNG, DATE, TIME, or DTTM index for these columns.

3.1.6 Long Strings

Values up to 254 characters are stored as short strings, with a preceding length byte. Any values that are longer
than 255 bytes are considered long strings. Characters after the 255th are stored separate from the row
containing the long string value.

SAP SQL Anywhere treats CHAR, VARCHAR, and LONG VARCHAR columns all as the same type.

There are several functions that will ignore the part of any string past the 255th character. They are soundex,
similar, and all of the date functions. Also, any arithmetic involving the conversion of a long string to a
number will work on only the first 255 characters. It would be extremely unusual to run in to one of these
limitations.

All other functions and all other operators work with the full length of long strings.

3.2 Numeric Data Types

Use numeric data types for storing numerical data.

 Syntax

[ UNSIGNED ] BIGINT

[ UNSIGNED ] { INT | INTEGER }

SMALLINT

TINYINT

DECIMAL [ ( <precision> [ , <scale> ] ) ]

NUMERIC [ ( <precision> [ , <scale >] ) ]

DOUBLE

FLOAT [ ( <precision> ) ]

SAP IQ SQL Reference


SQL Data Types INTERNAL 119
REAL

In this section:

Usage for Numeric Data Types [page 120]


Be aware of these points when using numeric data types.

3.2.1 Usage for Numeric Data Types

Be aware of these points when using numeric data types.

● The INTEGER, NUMERIC, and DECIMAL data types are sometimes called exact numeric data types, in
contrast to the approximate numeric data types FLOAT, DOUBLE, and REAL. Only exact numeric data is
guaranteed to be accurate to the least significant digit specified after arithmetic operations.
● Do not fetch TINYINT columns into Embedded SQL 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.
● A period is the only decimal separator (decimal point); comma is not supported as a decimal separator.

Numeric Data Type Description

BIGINT A signed 64-bit integer, requiring 8 bytes of storage.

You can specify integers as UNSIGNED. By default the data type is signed. Its range is be­
tween -9223372036854775808 and 9223372036854775807 (signed) or from 0 to
18446744073709551615 (unsigned).

INT or INTEGER A signed 32-bit integer with a range of values between -2147483648 and 2147483647 requir­
ing 4 bytes of storage.

The INTEGER data type is an exact numeric data type; its accuracy is preserved after arith­
metic operations.

You can specify integers as UNSIGNED; by default the data type is signed. The range of val­
ues for an unsigned integer is between 0 and 4294967295.

SMALLINT A signed 16-bit integer with a range between -32768 and 32767, requiring 2 bytes of storage.

The SMALLINT data type is an exact numeric data type; its accuracy is preserved after
arithmetic operations.

TINYINT An unsigned 8-bit integer with a range between 0 and 255, requiring 1 byte of storage.

The TINYINT data type is an exact numeric data type; its accuracy is preserved after arith­
metic operations.

SAP IQ SQL Reference


120 INTERNAL SQL Data Types
Numeric Data Type Description

DECIMAL A signed decimal number with <precision> total digits and with <scale> of the digits af­
ter the decimal point. The precision can equal 1 to 126, and the scale can equal 0 up to preci­
sion value. The defaults are scale = 38 and precision = 126. Results are calculated based on
the actual data type of the column to ensure accuracy, but you can set the maximum scale
of the result returned to the application using the MAX_CLIENT_NUMERIC_SCALE op­
tion.

NUMERIC Same as DECIMAL.

DOUBLE A signed double-precision floating-point number stored in 8 bytes. The range of absolute,
nonzero values is between 2.2250738585072014e-308 and 1.797693134862315708e+308.
Values held as DOUBLE are accurate to 15 significant digits, but might be subject to round­
ing errors beyond the 15th digit.

The DOUBLE data type is an approximate numeric data type; it is subject to rounding errors
after arithmetic operations.

FLOAT If <precision> is not supplied, the FLOAT data type is the same as the REAL data type. If
<precision> supplied, then the FLOAT data type is the same as the REAL or DOUBLE
data type, depending on the value of the precision. The cutoff between REAL and DOUBLE
is platform-dependent, and it is the number of bits used in the mantissa of single-precision
floating point number on the platform.

When a column is created using the FLOAT data type, columns on all platforms are guaran­
teed to hold the values to at least the specified minimum precision. In contrast, REAL and
DOUBLE do not guarantee a platform-independent minimum precision.

The FLOAT data type is an approximate numeric data type; it is subject to rounding errors
after arithmetic operations.

REAL A signed single-precision floating-point number stored in 4 bytes. The range of absolute,
nonzero values is 1.175494351e-38 to 3.402823466e+38. Values held as REAL are accurate
to 6 significant digits, but might be subject to rounding errors beyond the sixth digit.

The REAL data type is an approximate numeric data type; it is subject to rounding errors
after arithmetic operations.

This table lists the storage required for a decimal number.

Precision Storage

1 to 4 2 bytes

5 to 9 4 bytes

10 to 18 8 bytes

19 to 126 See below

SAP IQ SQL Reference


SQL Data Types INTERNAL 121
The storage requirement in bytes for a decimal value with a precision greater than 18 can be calculated using
the following formula, where <int> takes the integer portion of its argument:

4 + 2 * (int(((prec - scale) + 3) / 4) +
int((scale + 3) / 4) + 1)

The storage used by a column is based upon the precision and scale of the column. Each cell in the column has
enough space to hold the largest value of that precision and scale. For example:

NUMERIC(18,4) takes 8 bytes per cell


NUMERIC(19,4) takes 16 bytes per cell

The DECIMAL data type is an exact numeric data type; its accuracy is preserved to the least significant digit
after arithmetic operations. Its maximum absolute value is the number of nines defined by [<precision> -
<scale>], followed by the decimal point, and then followed by the number of nines defined by <scale>. The
minimum absolute nonzero value is the decimal point, followed by the number of zeros defined by [<scale> -
1], then followed by a single one. For example:

NUMERIC (3,2) Max positive = 9.99 Min non-zero = 0.01 Max negative = -9.99

If neither precision nor scale is specified for the explicit conversion of NULL to NUMERIC, the default is
NUMERIC(1,0). For example,

SELECT CAST( NULL AS NUMERIC ) A,


CAST( NULL AS NUMERIC(15,2) ) B

is described as:

A NUMERIC(1,0)
B NUMERIC(15,2)

 Note

The maximum value supported in SAP SQL Anywhere for the numeric function is 255. If the precision of the
numeric function exceeds the maximum value supported in SAP SQL Anywhere, the following error occurs:
"The result datatype for function '_funcname' exceeds the maximum
supported numeric precision of 255. Please set the proper value for
precision in numeric function, 'location'"

In this section:

Numeric Data Compatibility [page 123]


Numeric data compatibility differences exist between SAP IQ and SAP Adaptive Server Enterprise and
SAP SQL Anywhere.

Indexes [page 123]


This section describes the relationship between index types and numeric data types.

SAP IQ SQL Reference


122 INTERNAL SQL Data Types
3.2.1.1 Numeric Data Compatibility

Numeric data compatibility differences exist between SAP IQ and SAP Adaptive Server Enterprise and SAP
SQL Anywhere.

● In embedded SQL, fetch TINYINT columns into 2-byte or 4-byte integer columns. Also, to send a TINYINT
value to a database, the C variable should be an integer.
● You should avoid default precision and scale settings for NUMERIC and DECIMAL data types, as these differ
by product:

Database Default Precision Default Scale

SAP IQ 126 38

SAP ASE 18 0

SAP SQL Anywhere 30 6

● The FLOAT ( <p >) data type is a synonym for REAL or DOUBLE, depending on the value of <p>. For SAP
ASE, REAL is used for <p> less than or equal to 15, and DOUBLE for <p> greater than 15. For SAP IQ, the
cutoff is platform-dependent, but on all platforms, the cutoff value is greater than 22.
● SAP IQ includes two user-defined data types, MONEY and SMALLMONEY, which are implemented as
NUMERIC(19,4) and NUMERIC(10,4), respectively. They are provided primarily for compatibility with SAP
ASE.

3.2.1.2 Indexes

This section describes the relationship between index types and numeric data types.

● The CMP and HNG index types do not support the FLOAT, DOUBLE, and REAL data types, and the HG index
type is not recommended.
● The WD, DATE, TIME, and DTTM index types do not support the numeric data types.

3.3 Binary Data Types

Use binary data types for storing raw binary data, such as pictures, in a hexadecimal-like notation, up to a
length of (32 K – 1) bytes.

 Syntax

BINARY [ ( <length> ) ]

VARBINARY [ ( <max-length> ) ]

UNIQUEIDENTIFIER

SAP IQ SQL Reference


SQL Data Types INTERNAL 123
In this section:

Usage for Binary Data Types [page 124]


Binary data begins with the characters “0x” or “0X” and can include any combination of digits and the
uppercase and lowercase letters A through F.

Related Information

NEWID Function [Miscellaneous] [page 432]


STRTOUUID Function [String] [page 533]
UUIDTOSTR Function [String] [page 553]
Character Data Types [page 115]
Binary Data Type Compatibility [page 159]

3.3.1 Usage for Binary Data Types

Binary data begins with the characters “0x” or “0X” and can include any combination of digits and the
uppercase and lowercase letters A through F.

You can specify the column length in bytes, or use the default length of 1 byte. Each byte stores 2 hexadecimal
digits. Even though the default length is 1 byte, it is recommended that you always specify an even number of
characters for BINARY and VARBINARY column length. If you enter a value longer than the specified column
length, SAP IQ truncates the entry to the specified length without warning or error.

Binary Data Type Description

BINARY Binary data of length <length> bytes. If <length> is omitted, the default is 1 byte. The maxi­
mum size allowed is 32767 bytes. Use the fixed-length binary type BINARY for data in which all
entries are expected to be approximately equal in length. Because entries in BINARY columns
are zero-padded to the column length <length>, they might require more storage space than
entries in VARBINARY columns.

VARBINARY Binary data up to a length of <max-length> bytes. If <max-length> is omitted, the default is 1
byte. The maximum size allowed is (32K – 1) bytes. Use the variable-length binary type
VARBINARY for data that is expected to vary greatly in length.

UNIQUEIDENTIFIER The UNIQUEIDENTIFIER data type is used for storage of UUID (also known as GUID) values.

In this section:

Treatment of Trailing Zeros [page 125]


All BINARY columns are padded with zeros to the full width of the column. Trailing zeros are truncated
in all VARBINARY columns.

ASCII Data From a Flat File [page 126]


Any ASCII data loaded from a flat file into a binary type column (BINARY or VARBINARY) is stored as
nibbles.

SAP IQ SQL Reference


124 INTERNAL SQL Data Types
Storage Size [page 126]
The storage size of binary data differs based on data type.

String Operators [page 127]


The concatenation string operators || and + both support binary type data.

Restrictions on BINARY and VARBINARY Data [page 127]


Restrictions apply to columns containing BINARY and VARBINARY data.

Binary Data Compatibility [page 128]


The treatment of trailing zeros in binary data differs between SAP IQ, SAP SQL Anywhere, and SAP
Adaptive Server Enterprise.

UNIQUEIDENTIFIER [page 128]


The UNIQUEIDENTIFIER data type is used for storage of UUID (also known as GUID) values.

Binary Large Object Data [page 129]


As a separately licensed option, SAP IQ supports binary large object (BLOB) data with a length ranging
from zero (0) to 512 TB (terabytes) for a page size of 128 KB or 2 PB (petabytes) for a page size of 512
KB.

3.3.1.1 Treatment of Trailing Zeros

All BINARY columns are padded with zeros to the full width of the column. Trailing zeros are truncated in all
VARBINARY columns.

The following example creates a table with all four variations of BINARY and VARBINARY data types defined
with NULL and NOT NULL. The same data is inserted in all four columns and is padded or truncated according
to the data type of the column:

CREATE TABLE zeros (bnot BINARY(5) NOT NULL,


bnull BINARY(5) NULL,
vbnot VARBINARY(5) NOT NULL,
vbnull VARBINARY(5) NULL);
INSERT zeros VALUES (0x12345000, 0x12345000,
0x12345000, 0x12345000);
INSERT zeros VALUES (0x123, 0x123, 0x123, 0x123);
INSERT zeros VALUES (0x0, 0x0, 0x0, 0x0);
INSERT zeros VALUES ('002710000000ae1b',
'002710000000ae1b', '002710000000ae1b',
'002710000000ae1b');
SELECT * FROM zeros;

bnot bnull vbnot vbnull

0x1234500000 0x1234500000 0x12345000 0x12345000

0x0123000000 0x0123000000 0x0123 0x0123

0x0000000000 0x0000000000 0x00 0x00

0x3030323731 0x3030323731 0x3030323731 0x3030323731

Because each byte of storage holds 2 hexadecimal digits, SAP IQ expects binary entries to consist of the
characters "0x" followed by an even number of digits. When the "0x" is followed by an odd number of digits,
SAP IQ assumes that you omitted the leading 0 and adds it for you.

SAP IQ SQL Reference


SQL Data Types INTERNAL 125
Input values "0x00" and "0x0" are stored as "0x00" in variable-length binary columns (VARBINARY). In fixed-
length binary columns (BINARY), the value is padded with zeros to the full length of the field:

INSERT zeros VALUES (0x0, 0x0, 0x0, 0x0);


SELECT * FROM zeros

bnot bnull vbnot vbnull

0x0000000000 0x0000000000 0x00 0x00

If the input value does not include "0x", SAP IQ assumes that the value is an ASCII value and converts it. For
example:

CREATE TABLE sample (col_bin BINARY(8));


INSERT sample VALUES ('002710000000ae1b');SELECT * FROM sample;

col_bin

0x3030323731303030

 Note

In the above example, ensure you set the string_rtruncation option to "off".

When you select a BINARY value, specify the value with the padded zeros or use the CAST function, as shown in
these examples:

SELECT * FROM zeros WHERE bnot = 0x0123000000;

SELECT * FROM zeros WHERE bnot = CAST(0x0123 as binary(5));

3.3.1.2 ASCII Data From a Flat File

Any ASCII data loaded from a flat file into a binary type column (BINARY or VARBINARY) is stored as nibbles.

For example, if 0x1234 or 1234 is read from a flat file into a binary column, SAP IQ stores the value as
hexadecimal 1234. SAP IQ ignores the "0x" prefix. The data is rejected if the input data contains any characters
out of the range 0 – 9, a – f, and A – F.

3.3.1.3 Storage Size

The storage size of binary data differs based on data type.

Data Type Column Definition Input Data Storage

VARBINARY width of (32K – 1) bytes (32K – 1) bytes binary (32K – 1) bytes

SAP IQ SQL Reference


126 INTERNAL SQL Data Types
Data Type Column Definition Input Data Storage

VARBINARY width of (32K– 1) bytes (64K – 2) bytes ASCII (32K – 1) bytes

BINARY width of (32K – 1) bytes (32K – 1) bytes binary (32K – 1) bytes

BINARY width of (32K – 1) bytes (64K – 2) bytes ASCII (32K – 1) bytes

The exact form in which you enter a particular value depends on the platform you are using. Therefore,
calculations involving binary data might produce different results on different machines.

For platform-independent conversions between hexadecimal strings and integers, use the INTTOHEX and
HEXTOINT functions rather than the platform-specific CONVERT function.

Related Information

Data Type Conversion Functions [page 202]


Data Type Conversions [page 143]

3.3.1.4 String Operators

The concatenation string operators || and + both support binary type data.

Explicit conversion of binary operands to character data types is not necessary with the || operator. Explicit and
implicit data conversion produces different results, however.

3.3.1.5 Restrictions on BINARY and VARBINARY Data

Restrictions apply to columns containing BINARY and VARBINARY data.

● You cannot use the aggregate functions SUM, AVG, STDDEV, or VARIANCE with the binary data types. The
aggregate functions MIN, MAX, and COUNT do support the binary data types BINARY and VARBINARY.
● HNG, WD, DATE, TIME, and DTTM indexes do not support BINARY or VARBINARY data.
● Only the default index, CMP index, and TEXT index types are supported for BINARY and VARBINARY data
greater than 255 bytes in length.
● Bit operations are supported on BINARY and VARBINARY data that is 8 bytes or less in length.

SAP IQ SQL Reference


SQL Data Types INTERNAL 127
3.3.1.6 Binary Data Compatibility

The treatment of trailing zeros in binary data differs between SAP IQ, SAP SQL Anywhere, and SAP Adaptive
Server Enterprise.

Treatment of trailing zeroes:

Data Type SAP IQ SAP SQL Anywhere SAP ASE

BINARY NOT NULL Padded Not padded Padded

BINARY NULL Padded Not padded Not padded

VARBINARY NOT NULL Truncated, not padded Truncated, not padded Truncated, not padded

VARBINARY NULL Truncated, not padded Truncated, not padded Truncated, not padded

SAP ASE, SAP SQL Anywhere, and SAP IQ all support the STRING_RTRUNCATION database option, which
affects error message reporting when an INSERT or UPDATE string is truncated. For Transact-SQL compatible
string comparisons, set the STRING_RTRUNCATION option to the same value in both databases.

You can also set the STRING_RTRUNCATION option ON when loading data into a table, to alert you that the data
is too large to load into the field. The default value is ON.

Bit operations on binary type data are not supported by SAP ASE. SAP SQL Anywhere only supports bit
operations against the first four bytes of binary type data. SAP IQ supports bit operations against the first eight
bytes of binary type data.

3.3.1.7 UNIQUEIDENTIFIER

The UNIQUEIDENTIFIER data type is used for storage of UUID (also known as GUID) values.

The UNIQUEIDENTIFIER data type is often used for a primary key or other unique column to hold UUID
(Universally Unique Identifier) values that can be used to uniquely identify rows. The NEWID function generates
UUID values in such a way that a value produced on one computer does 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, the following statement updates the table mytab and sets the value of the column uid_col to a
unique identifier generated by the NEWID function, if the current value of the column is NULL:

UPDATE mytab
SET uid_col = NEWID()
WHERE uid_col IS NULL

If you execute the following statement, the unique identifier is returned as a BINARY(16):

SELECT NEWID()

For example, the value might be 0xd3749fe09cf446e399913bc6434f1f08. You can convert this string into a
readable format using the UUIDTOSTR() function.

UUID values are also referred to as GUIDs (Globally Unique Identifier).

SAP IQ SQL Reference


128 INTERNAL SQL Data Types
The STRTOUUID and UUIDTOSTR functions are used to convert values between UNIQUEIDENTIFIER and string
representations.

UNIQUEIDENTIFIER values are stored and returned as BINARY(16).

Because UNIQUEIDENTIFIER values are large, using UNSIGNED BIGINT or UNSIGNED INT identity columns
instead of UNIQUEIDENTIFIER is more efficient, if you do not need cross database unique identifiers.

In this section:

Standards and Compatibility for UNIQUEIDENTIFIER [page 129]


These standards and compatibilities apply to UNIQUEIDENTIFIER values.

3.3.1.7.1 Standards and Compatibility for


UNIQUEIDENTIFIER

These standards and compatibilities apply to UNIQUEIDENTIFIER values.

● SQL – Vendor extension to ISO/ANSI SQL grammar.


● Sybase – Supported by SAP SQL Anywhere. Not supported by SAP Adaptive Server Enterprise.

3.3.1.8 Binary Large Object Data

As a separately licensed option, SAP IQ supports binary large object (BLOB) data with a length ranging from
zero (0) to 512 TB (terabytes) for a page size of 128 KB or 2 PB (petabytes) for a page size of 512 KB.

The maximum length is equal to 4 GB multiplied by the database page size. See SAP IQ Administration:
Unstructured Data Analytics

3.4 Bit Data Type

Use the BIT data type for storing Boolean values.

Data Type Values Supported By

BIT 0 or 1 SAP SQL Anywhere and SAP Adaptive Server Enterprise

BIT stores only the values 0 or 1.

Inserting any nonzero value into a BIT column stores a 1 in the column. Inserting any zero value into a BIT
column stores a 0.

Only the default index type is supported for BIT data.

SAP IQ SQL Reference


SQL Data Types INTERNAL 129
3.5 Date and Time Data Types

Use date and time data types for storing dates and times.

 Syntax

DATE

DATETIME

SMALLDATETIME

TIME

TIMESTAMP

In this section:

Usage for Date and Time Data Types [page 130]


Familiarize yourself with these usage considerations before using date and time data types.

Related Information

TIMESTAMP Special Value [page 92]


CURRENT TIMESTAMP Special Value [page 87]
CURRENT TIME Special Value [page 86]
CURRENT DATE Special Value [page 85]
Retrieve Dates and Times [page 133]
BIGTIME and BIGDATETIME Support [page 161]

3.5.1 Usage for Date and Time Data Types

Familiarize yourself with these usage considerations before using date and time data types.

Date and Time Data


Type Description

DATE A calendar date, such as a year, month and day. The year can be from 0001 to 9999. The day
must be a nonzero value, so that the minimum date is 0001-01-01. A DATE value requires 4
bytes of storage.

SAP IQ SQL Reference


130 INTERNAL SQL Data Types
Date and Time Data
Type Description

DATETIME A domain, implemented as TIMESTAMP. DATETIME is provided primarily for compatibility


with SAP Adaptive Server Enterprise.

SMALLDATETIME A domain, implemented as TIMESTAMP. SMALLDATETIME is provided primarily for compati­


bility with SAP ASE.

TIME Time of day, containing hour, minute, second, and fraction of a second. The fraction is stored to
6 decimal places. A TIME value requires 8 bytes of storage. (ODBC standards restrict TIME
data type to an accuracy of seconds. For this reason, do not use TIME data types in WHERE
clause comparisons that rely on a higher accuracy than seconds.)

TIMESTAMP Point in time, containing year, month, day, hour, minute, second, and fraction of a second. The
fraction is stored to 6 decimal places. The day must be a nonzero value. A TIMESTAMP value
requires 8 bytes of storage.

The valid range of the TIMESTAMP data type is from 0001-01-01 00:00:00.000000 to 9999-12-31
23:59:59.999999. The display of TIMESTAMP data outside the range of 1600-02-28 23:59:59 to 7911-01-01
00:00:00 might be incomplete, but the complete datetime value is stored in the database; you can see the
complete value by first converting it to a character string. You can use the CAST() function to do this, as in the
following example, which first creates a table with DATETIME and TIMESTAMP columns, then inserts values
where the date is greater 7911-01-01:

create table mydates (id int, descript char(20),


datetime_null datetime, timestamp_null timestamp);

insert into mydates values (1, 'example', '7911-12-30


23:59:59','7911-12-30 06:03:44');
commit;

When you select without using CAST, hours and minutes are set to 00:00:

select * from mydates;

1, 'example', '7911-12-30 00:00:59.000', '7911-12-30 00:00:44.000'

When you select using cast, you see the complete timestamp:

select id, descript, cast(datetime_null as char(23)),


cast(timestamp_null as char(23)) from mydates;

1, 'example', '7911-12-30 23:59:59.0', '7911-12-30 06:03:44.0'

In this section:

Index Types Supported [page 132]


These index types are supported by date and time data.

Send Dates and Times [page 132]

SAP IQ SQL Reference


SQL Data Types INTERNAL 131
You send dates and times to the database in a number of ways.

Retrieve Dates and Times [page 133]


There are three ways in which you can retrieve dates and times from the database.

Compare Dates and Times [page 134]


To compare a date to a string as a string, use the DATEFORMAT function or CAST function to convert the
date to a string before comparing.

Unambiguous Dates and Times [page 134]


Using the unambiguous date format prevents misinterpretation of dates according to the user's
DATE_ORDER setting.

Related Information

Compatibility of String to Datetime Conversions [page 144]

3.5.1.1 Index Types Supported

These index types are supported by date and time data.

● All date and time data types support the CMP, HG, and HNG index types; the WD index type is not supported.
● DATE data supports the DATE index.
● TIME data supports the TIME index.
● DATETIME and TIMESTAMP data support the DTTM index.

3.5.1.2 Send Dates and Times

You send dates and times to the database in a number of ways.

● Using any interface, as a string


● Using ODBC, as a TIMESTAMP structure
● Using Embedded SQL, as a SQLDATETIME structure

When you send a time to the database as a string (for the TIME data type) or as part of a string (for TIMESTAMP
or DATE data types), hours, minutes, and seconds must be separated by colons in the format
<hh>:<mm>:<ss>:<sss>, but can appear anywhere in the string. As an option, a period can separate the
seconds from fractions of a second, as in <hh>:<mm>:<ss>.<sss>. The following are valid and unambiguous
strings for specifying times:

21:35 -- 24 hour clock if no am or pm specified


10:00pm -- pm specified, so interpreted as 12 hour clock
10:00 -- 10:00am in the absence of pm
10:23:32.234 -- seconds and fractions of a
second included

SAP IQ SQL Reference


132 INTERNAL SQL Data Types
When you send a date to the database as a string, conversion to a date is automatic. You can supply the string
in one of two ways:

● As a string of format <yyyy/mm/dd> or <yyyy-mm-dd>, which is interpreted unambiguously by the


database
● As a string interpreted according to the DATE_ORDER database option

Date format strings cannot contain any multibyte characters. Only single-byte characters are allowed in a
date/time/datetime format string, even when the collation order of the database is a multibyte collation order
like 932JPN.

3.5.1.3 Retrieve Dates and Times

There are three ways in which you can retrieve dates and times from the database.

● Using any interface, as a string


● Using ODBC, as a TIMESTAMP structure
● Using embedded SQL, as a SQLDATETIME structure

When a date or time is retrieved as a string, it is retrieved in the format specified by the database options
DATE_FORMAT, TIME_FORMAT, and TIMESTAMP_FORMAT.

The following operators are allowed on dates:

Operator Description

timestamp + integer Add the specified number of days to a date or timestamp.

timestamp - integer Subtract the specified number of days from a date or time­
stamp.

date - date Compute the number of days between two dates or time­
stamps.

date + time Create a timestamp combining the given date and time.

Related Information

TIMESTAMP Special Value [page 92]


CURRENT TIMESTAMP Special Value [page 87]
CURRENT TIME Special Value [page 86]
CURRENT DATE Special Value [page 85]
Date and Time Data Types [page 130]

SAP IQ SQL Reference


SQL Data Types INTERNAL 133
3.5.1.4 Compare Dates and Times

To compare a date to a string as a string, use the DATEFORMAT function or CAST function to convert the date to
a string before comparing.

DATEFORMAT(invoice_date,'yyyy/mm/dd') = '1992/05/23'

You can use any allowable date format for the DATEFORMAT string expression.

Date format strings must not contain any multibyte characters. Only single-byte characters are allowed in a
date/time/datetime format string, even when the collation order of the database is a multibyte collation order
like 932JPN.

If '<?>' represents a multibyte character, the following query fails:

SELECT DATEFORMAT ( StartDate, 'yy?') FROM Employees;

Instead, move the multibyte character outside of the date format string using the concatenation operator:

SELECT DATEFORMAT (StartDate, 'yy') + '?' FROM Employees;

3.5.1.5 Unambiguous Dates and Times

Using the unambiguous date format prevents misinterpretation of dates according to the user's DATE_ORDER
setting.

Dates in the format <yyyy>/<mm>/<dd> or <yyyy>-<mm>-<dd> are always recognized as dates regardless of
the DATE_ORDER setting. You can use other characters as separators; for example, a question mark, a space
character, or a comma. Use this format in any context where different users might be employing different
DATE_ORDER settings. For example, in stored procedures, use of the unambiguous date format prevents
misinterpretation of dates according to the user's DATE_ORDER setting.

A string of the form <hh>:<mm>:<ss>.<sss> is also interpreted unambiguously as a time.

For combinations of dates and times, any unambiguous date and any unambiguous time yield an unambiguous
date-time value. Also, the following form is an unambiguous date-time value:

YYYY-MM-DD HH.MM.SS.SSSSSS

You can use periods in the time only in combination with a date.

In other contexts, you can use a more flexible date format. SAP IQ can interpret a wide range of strings as
formats. The interpretation depends on the setting of the DATE_ORDER database option. The DATE_ORDER
database option can have the value 'MDY', 'YMD', or 'DMY'. For example, to set the DATE_ORDER option to
'DMY' enter:

SET OPTION DATE_ORDER = 'DMY' ;

The default DATE_ORDER setting is 'YMD'. The ODBC driver sets the DATE_ORDER option to 'YMD' whenever a
connection is made. Use the SET OPTION statement to change the value.

SAP IQ SQL Reference


134 INTERNAL SQL Data Types
The DATE_ORDER database option determines whether the string 10/11/12 is interpreted by the database as
Oct 11 1912, Nov 12 1910, or Nov 10 1912. The year, month, and day of a date string should be separated by
some character (for example "/", "-", or space) and appear in the order specified by the DATE_ORDER option.

You can supply the year as either two or four digits. The value of the NEAREST_CENTURY option [TSQL] affects
the interpretation of two-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. Thus, by default, 50 is interpreted as 1950, and 49 is
interpreted as 2049.

The month can be the name or number of the month. The hours and minutes are separated by a colon, but can
appear anywhere in the string.

Specify the year using the four-digit format.

With an appropriate setting of DATE_ORDER, the following strings are all valid dates:

99-05-23 21:35
99/5/23
1999/05/23
May 23 1999
23-May-1999
Tuesday May 23, 1999 10:00pm

If a string contains only a partial date specification, default values are used to fill out the date. The following
defaults are used:

● Year – 1900
● Month – no default
● Day – 1 (useful for month fields; for example, 'May 1999' is the date '1999-05-01 00:00')
● Hour, minute, second, fraction – 0

3.6 TABLE REF data type


The TABLE REF data type stores a reference to a base table, temporary table, or view. This data type is only for
use with connection-scope variables.

 Syntax

Declaring a variable of type TABLE REF

DECLARE <table-ref-variable> TABLE REF


[ { DEFAULT | = } TABLE REF ( [ <owner>.]<table-name> ) ]

Creating a variable of type TABLE REF

CREATE VARIABLE <table-ref-variable> TABLE REF


[ { DEFAULT | = } TABLE REF ( [ <owner>.]<table-name> ) ]

Setting a variable of type TABLE REF

SET <table-ref-variable> = TABLE REF ( <table-name> )

Referencing a variable of type TABLE REF in DML statements

TABLE REF ( <table-ref-variable> ) AS <correlation-name>

SAP IQ SQL Reference


SQL Data Types INTERNAL 135
Referencing a variable of type TABLE REF as a parameter in a function or procedure

TABLE REF ( <table-ref-variable> )

Parameters

table-ref-variable A valid identifier for the table reference variable.


table-name The name of a base table. Optionally, include the owner as part of the specification (for
example, GROUPO.Employees); this is recommended for base tables and views.

Remarks

Table reference variables (variables of type TABLE REF) allow procedures and functions to be defined even
though the names of the tables they operate on change or have not yet been defined.

When referencing a variable of TABLE REF type in a DML statement, you must specify a correlation name for
results.

When you specify a table reference variable in a statement, the table is looked up immediately before the
statement is executed.

Table reference variables can only accessed by their creator.

Creating a table reference variable does not create a dependence between the variable and the underlying
table, and DDL statements can still be performed on tables referenced by a table reference variable.

If a table is dropped, then any table reference variables that refer to it are invalidated; an attempt to use an
invalid table reference variable returns an error.

When executing a statement that acts on a table specified by using a table reference variable, you need the
appropriate privileges on the underlying table referenced by the variable.

Restrictions on the use of table reference variables:

● Table reference variables cannot be used in a SELECT or DML statement if the variable resolves to the
NULL value.
● Table reference variables cannot be used to specify tables in DDL statements.
● Table reference variables cannot be used as columns in base tables, temporary tables, or views.
● Table reference variables cannot be used in a top-level SELECT block or query expression that is returned
to a client.
● Table reference variables cannot be combined with other types of variables in built-in functions that require
a common super-type for the parameters.
● Table reference variables cannot be ordered or used as part of calculations or comparisons except for
equality and inequality.

The table reference variable functionality overlaps with indirect identifier functionality; both are ways of
indirectly referring to a table. However, a table reference is resolved at creation time and remains a valid
reference, whereas an indirect reference is resolved when the statement that references it is executed and
therefore may not be a valid reference.

SAP IQ SQL Reference


136 INTERNAL SQL Data Types
Additionally, a table reference can provide access to a table that is not accessible in the current context,
whereas an indirect identifier cannot. For example, suppose your procedure creates, and then refers to, a local
table that has the same name as a base table. Now let's say you need to refer to the base table from within the
procedure. An indirect identifier for the table would resolve to the local table, which is not what you want. To
precisely identify the base table instead, use a table reference variable. For example:

CREATE OR REPLACE PROCEDURE PROC1()


BEGIN
DECLARE LOCAL TEMPORARY TABLE myTab (x INTEGER, y INTEGER);
DECLARE tab_ref TABLE REF = TABLE REF (myTab);
INSERT INTO myTab VALUES (1,100), (2,200), (3,300);
SELECT * FROM PROC2( tab_ref );
END;
CREATE OR REPLACE PROCEDURE PROC2( IN @tab_ref TABLE REF )
RESULT (v1 LONG VARCHAR, v2 INTEGER)
BEGIN
DECLARE LOCAL TEMPORARY TABLE myTab ( pk INTEGER, val LONG VARCHAR );
INSERT INTO myTab VALUES( 1, 'apple'), (3, 'pear'), (10, 'banana');
SELECT val,T2.y FROM myTab T1 JOIN TABLE REF( @tab_ref ) AS T2 ON T2.x =
T1.pk;
END;
CALL PROC1;

Table 2: Result:

v1 v2

apple 100

pear 300

The myTab table in PROC2 shadows (hides) myTab that was created in PROC1, so the only table accessible by
using the name myTab in PROC2 would be the locally declared myTab. Using a table reference (TABLE
REF( @tab_ref )) more precisely identifies the object being joined to (in this example, the table created in
PROC1.

 Example

The following example declares a table reference variable, @ref, sets it to the GROUPO.Employees table
reference, and then queries the table using the table reference variable:

DECLARE @ref TABLE REF = TABLE REF ( GROUPO.Employees )


SELECT * FROM TABLE REF ( @ref ) AS T;

The following example creates a table reference variable called @tableDefinition and sets it to the
GROUPO.Employees table reference, and then selects from the table using the table reference variable:

CREATE VARIABLE @tableDefinition TABLE REF;


SET @tableDefinition = TABLE REF ( GROUPO.Employees );
SELECT * FROM TABLE REF ( @tableDefinition ) AS T;

The following code snippet declares a variable named @myTableRefVariable1 with the TABLE REF data type
and sets it to the GROUPO.Employees table reference:

DECLARE @myTableRefVariable1 TABLE REF;


SET @myTableRefVariable1 = TABLE REF ( GROUPO.Employees );

SAP IQ SQL Reference


SQL Data Types INTERNAL 137
The following example creates a TABLE REF variable, sets it to the GROUPO.Employees table, and then
queries the table reference variable for employees with birthdays in the month of February:

CREATE VARIABLE @myTableRefVariable2 TABLE REF;


SET @myTableRefVariable2 = TABLE REF ( GROUPO.Employees );
SELECT T.surname, T.givenname, T.birthdate FROM TABLE REF
( @myTableRefVariable2 ) AS T
WHERE MONTH( T.birthdate ) = 2;

Table 3: Results
surname givenname birthdate

Davidson Jo Ann 1957-02-17

Samuels Peter 1968-02-28

Barker Joseph 1969-02-14

Sterling Paul 1950-02-27

The following example shows a table reference variable (@myTableRefVariable3) being used in several
statements to update the GROUPO.Employees table. Notice that a correlation name (T, in this example) is
required when specifying a table using a table reference variable in a DML statement:

CREATE VARIABLE @myTableRefVariable3 TABLE REF;


SET @myTableRefVariable3 = TABLE REF ( GROUPO.Employees );
UPDATE TABLE REF ( @myTableRefVariable3 ) AS T SET T.GivenName =
REPLACE( GivenName, 'Fran', 'Francis' );
DELETE FROM TABLE REF ( @myTableRefVariable3 ) AS T WHERE Surname = 'Holmes';
SELECT * FROM TABLE REF ( @myTableRefVariable3 ) AS T;

The following example shows how you can use table reference variables in a procedure:

CREATE OR REPLACE PROCEDURE leapday_births( IN @tab TABLE REF )


RESULT ( Surname person_name_t, GivenName person_name_t, Birthdate TIMESTAMP)
BEGIN
SELECT Surname, GivenName, Birthdate FROM TABLE REF ( @tab ) AS T
WHERE MONTH( Birthdate ) = 02 AND DAY( Birthdate ) = 29;
END;
CREATE VARIABLE @myTableRefVariable4 TABLE REF;
SET @myTableRefVariable4 = TABLE REF ( GROUPO.Employees );
CALL leapday_births(@myTableRefVariable4);

3.7 Domains
Domains are aliases for built-in data types, including precision and scale values where applicable.

Domains, also called user-defined data types, allow columns throughout a database to be defined
automatically on the same data type, with the same NULL or NOT NULL condition. This encourages
consistency throughout the database. Domain names are case-insensitive. SAP IQ returns an error if you
attempt to create a domain with the same name as an existing domain except for case.

In this section:

Simple Domains [page 139]

SAP IQ SQL Reference


138 INTERNAL SQL Data Types
You create domains using the CREATE DOMAIN statement.

CREATE DOMAIN Statement [page 140]


Creates a user-defined data type in the database.

Domain Compatibility [page 142]


Domain compatibility differences exist between SAP IQ and SAP Adaptive Server Enterprise and SAP
SQL Anywhere.

3.7.1 Simple Domains

You create domains 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 )

Although you can use CREATE DATATYPE as an alternative to CREATE DOMAIN, you should use CREATE
DOMAIN instead, since its syntax uses the ISO/ANSI SQL standard.

Requires CREATE DATATYPE system privilege. 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, and unlike other
database objects, the owner name is never used to prefix the data type name.

The street_address data type may be used in exactly the same way as any other data type when defining
columns. For example, the following table with two columns has the second column as a street_address
column:

CREATE TABLE twocol (id INT,


street street_address)

Owners or DBAs can drop domains by issuing a COMMIT and then using the DROP DOMAIN statement:

DROP DOMAIN street_address

You can carry out this statement only if no tables in the database are using data type.

Constraints and Defaults with User-Defined Data Types

Many of the attributes associated with columns, such as allowing NULL values, having a DEFAULT value, and so
on, can be built into a user-defined data type. Any column that is defined on the data type automatically
inherits the NULL setting, CHECK condition, and DEFAULT values. This allows uniformity to be built into
columns with a similar meaning throughout a database.

For example, many primary key columns in the demo database are integer columns holding ID numbers. The
following statement creates a data type that may be useful for such columns:

CREATE DOMAIN id INT


NOT NULL
DEFAULT AUTOINCREMENT

SAP IQ SQL Reference


SQL Data Types INTERNAL 139
CHECK( @col > 0 )

Any column created using the data type id is not allowed to hold NULLs, defaults to an autoincremented value,
and must hold a positive number. Any identifier could be used instead of <col> in the <@col> variable.

The attributes of the data type can be overridden if needed by explicitly providing attributes for the column. A
column created on data type id with NULL values explicitly allowed does allow NULLs, regardless of the setting
in the id data type.

3.7.2 CREATE DOMAIN Statement

Creates a user-defined data type in the database.

 Syntax

CREATE { DOMAIN | DATATYPE } <domain-name> <data-type>


… [ NOT ] NULL ]
… [ DEFAULT <default-value> ]

<default-value> ::=
<special-value>
| <string>
| <global variable>
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function>( <constant-expression> )
| AUTOINCREMENT
| CURRENT DATABASE
| CURRENT REMOTE USER
| NULL
| TIMESTAMP
| LAST USER

<special-value> ::=
CURRENT
{ DATE
| TIME
| TIMESTAMP
| USER
| PUBLISHER }
| USER

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

SAP IQ SQL Reference


140 INTERNAL SQL Data Types
Parameters

(back to top)

data-type

Built-in data type, with precision and scale.

You can also specify a %TYPE or %ROWTYPE attribute to set the data type to the data type of a column or
row in a table or view. However, specifying a table reference variable for the %ROWTYPE (TABLE REF
(table-reference-variable) %ROWTYPE) is not allowed.

Remarks

(back to top)

User-defined data types are aliases for built-in data types, including precision and scale values, where
applicable. They improve convenience and encourage consistency in the database.

 Note

Use CREATE DOMAIN, rather than CREATE DATATYPE, as CREATE DOMAIN is the ANSI/ISO SQL3 term.

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 user-defined data type name must be unique, and all users can
access the data type without using the owner as prefix.

User-defined data types are objects within the database. Their names must conform to the rules for identifiers.
User-defined data type names are always case-insensitive, as are built-in data type names.

By default, user-defined data types allow NULLs unless the allow_nulls_by_default database option is set
to OFF. In this case, new user-defined data types by default do not allow NULLs. The nullability of a column
created on a user-defined data type depends on the setting of the definition of the user-defined data type, not
on the setting of the allow_nulls_by_default option when the column is referenced. Any explicit setting of
NULL or NOT NULL in the column definition overrides the user-defined data type setting.

The CREATE DOMAIN statement allows you to specify DEFAULT values on user-defined data types. The
DEFAULT value specification is inherited by any column defined on the data type. Any DEFAULT value explicitly
specified on the column overrides that specified for the data type.

The CREATE DOMAIN statement lets you incorporate a rule, called a CHECK condition, into the definition of a
user-defined data type.

SAP IQ enforces CHECK constraints for base, global temporary. local temporary tables, and user-defined data
types.

To drop the data type from the database, use the DROP statement. You must be either the owner of the data
type or have the CREATE DATATYPE or CREATE ANY OBJECT system privilege in order to drop a user-defined
data type.

SAP IQ SQL Reference


SQL Data Types INTERNAL 141
Privileges

(back to top)

Requires one of:

● CREATE DATATYPE system privilege


● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise. Transact-SQL provides similar
functionality using the sp_addtype system procedure and the CREATE DEFAULT and CREATE RULE
statements.

Examples

(back to top)

The following example creates a data type named address, which holds a 35-character string, and which may
be NULL:

CREATE DOMAIN address CHAR( 35 ) NULL

3.7.3 Domain Compatibility

Domain compatibility differences exist between SAP IQ and SAP Adaptive Server Enterprise and SAP SQL
Anywhere.

● Named constraints and defaults – in SAP IQ, user-defined data types are created with a base data type,
and optionally, a NULL or NOT NULL condition. Named constraints and named defaults are not supported.

SAP IQ SQL Reference


142 INTERNAL SQL Data Types
● Creating data types – in SAP IQ, you can use either the sp_addtype system procedure or the CREATE
DOMAIN statement to add a domain. In SAP ASE, you must use sp_addtype. The owner of the
sp_addtype and other stored procedures inherited from SAP SQL Anywhere is dbo. The creator for any
object created using SAP SQL Anywhere stored procedure is also dbo, and thus a user without the ALTER
DATATYPE or ALTER ANY OBJECT system privilege and DROP DATATYPE or DROP ANY OBJECT system
privileges may not alter or drop domains created using sp_addtype. You need these system privileges to
alter and drop domains owned by dbo.

3.8 Data Type Conversions

Type conversions happen automatically, or you can explicitly request them using the CAST or CONVERT
function.

If a string is used in a numeric expression or as an argument to a function expecting a numeric argument, the
string is converted to a number before use.

If a number is used in a string expression or as a string function argument, then the number is converted to a
string before use.

All date constants are specified as strings. The string is automatically converted to a date before use.

There are certain cases where the automatic data type conversions are not appropriate:

● '12/31/90' + 5 – tries to convert the string to a number


● 'a' > 0 – tries to convert 'a' to a number

You can use the CAST or CONVERT function to force type conversions.

You can also use the following functions to force type conversions:

● DATE( expression ) – converts the expression into a date, and removes any hours, minutes or seconds.
Conversion errors might be reported.
● DATETIME( expression ) – converts the expression into a timestamp. Conversion errors might be
reported.
● STRING( expression ) – similar to CAST(value AS CHAR), except that string(NULL) is the empty
string (''), whereas CAST(NULL AS CHAR) is the NULL value.

 Note

SAP IQ does not silently truncate the conversion result of NUMERIC and DATE data types to CHAR and
VARCHAR. A conversion error is generated when the following data types are converted to a string whose
length is less than the column width:

● TINYINT, SMALLINT, [UNSIGNED] { INT | INTEGER }, [ UNSIGNED ] BIGINT


● NUMERIC, DECIMAL
● FLOAT, DOUBLE, REAL
● DATE, DATETIME, SMALLDATETIME, TIME, TIMESTAMP

The CONVERSION_ERROR option controls SAP IQ behavior in cases of conversion error. If you set the
CONVERSION_ERROR option to:

SAP IQ SQL Reference


SQL Data Types INTERNAL 143
● OFF – SAP IQ inserts a NULL value when possible
● ON – SAP IQ rolls back the insert and logs a conversion error

Related Information

Data Type Conversion Functions [page 202]


Storage Size [page 126]

3.9 Compatibility of String to Datetime Conversions

There are some differences in behavior between SAP IQ and SAP Adaptive Server Enterprise when converting
strings to date and time data types.

If you convert a string containing only a time value (no date) to a date/time data type, SAP IQ and SAP ASE
both use a default date of January 1, 1900, while SAP SQL Anywhere uses the current date.

If the milliseconds portion of a time is less than three digits, SAP ASE interprets the value differently depending
on whether it was preceded by a period or a colon:

● If preceded by a colon – the value means thousandths of a second.


● If preceded by a period – 1 digit means tenths, 2 digits mean hundredths, and 3 digits mean thousandths.

SAP IQ and SAP SQL Anywhere interpret the value the same way, regardless of the separator.

● SAP ASE converts the values below as shown:

12:34:56.7 to 12:34:56.700
12.34.56.78 to 12:34:56.780
12:34:56.789 to 12:34:56.789
12:34:56:7 to 12:34:56.007
12.34.56:78 to 12:34:56.078
12:34:56:789 to 12:34:56.789

● SAP IQ converts the milliseconds value in the manner that SAP ASE does for values preceded by a period,
in both cases:

12:34:56.7 to 12:34:56.700
12.34.56.78 to 12:34:56.780
12:34:56.789 to 12:34:56.789
12:34:56:7 to 12:34:56.700
12.34.56:78 to 12:34:56.780
12:34:56:789 to 12:34:56.789

In this section:

Compatibility of Exported Dates [page 145]


For dates in the first 9 days of a month and hours less than 10, SAP Adaptive Server Enterprise
supports a blank for the first digit; SAP IQ supports a zero or a blank.

Conversion of BIT to BINARY Data Type [page 145]

SAP IQ SQL Reference


144 INTERNAL SQL Data Types
SAP IQ supports BIT to BINARYand BIT to VARBINARY implicit and explicit conversion and is
compatible with SAP Adaptive Server Enterprise support of these conversions.

Conversion Between BIT and CHAR/VARCHAR Data Types [page 147]


SAP IQ supports implicit conversion between BIT and CHAR, and BIT and VARCHAR data types for
comparison operators, arithmetic operations, and INSERT and UPDATE statements

Related Information

Usage for Date and Time Data Types [page 130]

3.9.1 Compatibility of Exported Dates

For dates in the first 9 days of a month and hours less than 10, SAP Adaptive Server Enterprise supports a
blank for the first digit; SAP IQ supports a zero or a blank.

For details on supported and unsupported SAP ASE data types, see SAP IQ Administration: Load Management.

3.9.2 Conversion of BIT to BINARY Data Type

SAP IQ supports BIT to BINARYand BIT to VARBINARY implicit and explicit conversion and is compatible with
SAP Adaptive Server Enterprise support of these conversions.

SAP IQ implicitly converts BIT to BINARY and BIT to VARBINARY data types for comparison operators,
arithmetic operations, and INSERT and UPDATE statements.

For BIT to BINARY conversion, bit value ‘b’ is copied to the first byte of the binary string and the rest of the
bytes are filled with zeros. For example, BIT value 1 is converted to BINARY(n) string 0x0100...00 having 2n
nibbles. BIT value 0 is converted to BINARY string 0x00...00.

For BIT to VARBINARY conversion, BIT value ‘b’ is copied to the first byte of the BINARY string and the
remaining bytes are not used; that is, only one byte is used. For example, BIT value 1 is converted to
VARBINARY(n) string 0x01 having 2 nibbles.

The result of both implicit and explicit conversions of BIT to BINARY and BIT to VARBINARY data types is the
same. The following table contains examples of BIT to BINARY and VARBINARY conversions.

Conversion of BIT Value ‘1’ to Result

BINARY(3) 0x010000

VARBINARY(3) 0x01

BINARY(8) 0x0100000000000000

SAP IQ SQL Reference


SQL Data Types INTERNAL 145
Conversion of BIT Value ‘1’ to Result

VARBINARY(8) 0x01

These examples illustrate both implicit and explicit conversion of BIT to BINARY and BIT to VARBINARY data
types.

Given the following tables and data:

CREATE TABLE tbin(c1 BINARY(9))


CREATE TABLE tvarbin(c2 VARBINARY(9))
CREATE TABLE tbar(c2 BIT)
INSERT tbar VALUES(1)
INSERT tbar VALUES(0)

Implicit conversion of BIT to BINARY:

INSERT tbin SELECT c2 FROM tbar


c1
---
0x010000000000000000 (18 nibbles)
0x000000000000000000 (18 nibbles)

Implicit conversion of BIT to VARBINARY:

INSERT tvarbin SELECT c2 FROM tbar


c2
---
0x01
0x00

Explicit conversion of BIT to BINARY:

INSERT tbin SELECT CONVERT (BINARY(9), c2) FROM tbar


c1
---
0x010000000000000000 (18 nibbles)
0x000000000000000000 (18 nibbles)

Explicit conversion of BIT to VARBINARY:

INSERT tvarbin SELECT CONVERT(VARBINARY(9), c2) FROM tbar


c2
---
0x01
0x00

SAP IQ SQL Reference


146 INTERNAL SQL Data Types
3.9.3 Conversion Between BIT and CHAR/VARCHAR Data
Types

SAP IQ supports implicit conversion between BIT and CHAR, and BIT and VARCHAR data types for comparison
operators, arithmetic operations, and INSERT and UPDATE statements

Using the following tables and data, these examples illustrate both implicit and explicit conversions between
BIT and CHAR, and BIT and VARCHAR data types:

CREATE TABLE tchar(c1 CHAR(9))


CREATE TABLE tvarchar(c2 VARCHAR(9))
CREATE TABLE tbar(c2 BIT)
CREATE TABLE tbit(c2 BIT)
INSERT tbar VALUES(1)
INSERT tbar VALUES(0)

● Implicit conversion of BIT to VARCHAR / VARCHAR to BIT and implicit conversion of BIT to VARCHAR:

INSERT tvarchar SELECT c2 FROM tbar


SELECT c2, char_length(c2) FROM tvarchar
c2,char_length(tvarchar.c2)
---------------------------
'1',1
'0',1

● Implicit conversion of VARCHAR to BIT:

INSERT tbit SELECT c2 FROM tvarchar


SELECT c2 FROM tbit
c2
--
0
1

● Explicit conversion of BIT to CHAR / CHAR to BIT and explicit conversion of BIT to CHAR:

INSERT tchar SELECT CONVERT (CHAR(9), c2) FROM tbar


SELECT c1, char_length(c1) FROM tchar
c1,char_length(tchar.c1)
------------------------
'1',9
'0',9

● Explicit conversion of CHAR to BIT:

INSERT tbit SELECT CONVERT (BIT, c1) FROM tchar


SELECT c2 FROM tbit
c2
--
0
1

● Explicit conversion of BIT to VARCHAR / VARCHAR to BIT and explicit conversion of BIT to VARCHAR:

INSERT tvarchar SELECT CONVERT(VARCHAR(9), c2)


FROM tbar
SELECT c2, char_length(c2) FROM tvarchar
c2,char_length(tvarchar.c2)
---------------------------
'1',1
'0',1

SAP IQ SQL Reference


SQL Data Types INTERNAL 147
● Explicit conversion of VARCHAR to BIT:

INSERT tbit SELECT CONVERT (BIT, c2) FROM tvarchar


SELECT c2 FROM tbit
c2
--
0
1

SAP IQ SQL Reference


148 INTERNAL SQL Data Types
4 Differences from Other SQL Dialects

SAP IQ conforms to the ANSI SQL89 standard, but has many additional features that are defined in the IBM
DB2 and SAA specifications, as well as in the ANSI SQL92 standard.

Certain SAP IQ features are not found in many other SQL implementations.

In this section:

Dates [page 150]


SAP IQ has date, time, and timestamp types that include year, month, day, hour, minutes, seconds, and
fraction of a second. For insertions or updates to date fields, or comparisons with date fields, a free-
format date is supported.

Integrity [page 150]


SAP IQ supports both entity and referential integrity.

Joins [page 151]


SAP IQ allows automatic joins between tables.

Updates [page 151]


SAP IQ allows more than one table to be referenced by UPDATE.

Altering Tables [page 151]


ALTER TABLE has been extended.

Subqueries Not Always Allowed [page 151]


Unlike SAP SQL Anywhere, SAP IQ does not allow subqueries to appear wherever expressions are
allowed.

Additional Functions [page 152]


SAP IQ supports several functions not in the ANSI SQL definition.

Cursors [page 152]


When using Embedded SQL, cursor positions can be moved arbitrarily on the FETCH statement.
Cursors can be moved forward or backward relative to the current position or a given number of
records from the beginning or end of the cursor.

SAP IQ SQL Reference


Differences from Other SQL Dialects INTERNAL 149
4.1 Dates

SAP IQ has date, time, and timestamp types that include year, month, day, hour, minutes, seconds, and fraction
of a second. For insertions or updates to date fields, or comparisons with date fields, a free-format date is
supported.

In addition, the following operations are allowed on dates:

Date Operation Description

date + integer Add the specified number of days to a date.

date - integer Subtract the specified number of days from a date.

date - date Compute the number of days between two dates.

date + time Make a timestamp out of a date and time.

Also, many functions are provided for manipulating dates and times.

4.2 Integrity

SAP IQ supports both entity and referential integrity.

This has been implemented via the following two extensions to the CREATE TABLE and ALTER TABLE
statements:

PRIMARY KEY ( <column-name>, ... )


[NOT NULL] FOREIGN KEY [<role-name>]
[(<column-name>, ...)]
REFERENCES <table-name> [(<column-name>, ...)]
[ CHECK ON COMMIT ]

The PRIMARY KEY clause declares the primary key for the relation. SAP IQ will then enforce the uniqueness of
the primary key, and ensure that no column in the primary key contains the NULL value.

The FOREIGN KEY clause defines a relationship between this table and another table. This relationship is
represented by a column (or columns) in this table, which must contain values in the primary key of another
table. The system then ensures referential integrity for these columns; whenever these columns are modified
or a row is inserted into this table, these columns are checked to ensure that either one or more is NULL or the
values match the corresponding columns for some row in the primary key of the other table.

SAP IQ SQL Reference


150 INTERNAL Differences from Other SQL Dialects
4.3 Joins

SAP IQ allows automatic joins between tables.

In addition to the NATURAL and OUTER join operators supported in other implementations, SAP IQ allows KEY
joins between tables based on foreign-key relationships. This reduces the complexity of the WHERE clause when
performing joins.

4.4 Updates

SAP IQ allows more than one table to be referenced by UPDATE.

Views defined on more than one table can also be updated. Many SQL implementations do not allow updates
on joined tables.

4.5 Altering Tables

ALTER TABLE has been extended.

In addition to changes for entity and referential integrity, the following types of alterations are allowed:

DELETE column
RENAME new-table-name
RENAME old-column TO new-column

 Tip

After you create a column, you cannot modify the column data type. To change a data type, drop the
column and re-create it with the correct data type.

4.6 Subqueries Not Always Allowed

Unlike SAP SQL Anywhere, SAP IQ does not allow subqueries to appear wherever expressions are allowed.

SAP IQ supports subqueries only as allowed in the SQL-1989 grammar, plus in the SELECT list of the top level
query block or in the SET clause of an UPDATE statement. SAP IQ does not support SAP SQL Anywhere
extensions.

Many SQL implementations allow subqueries only on the right side of a comparison operator. For example, the
following command is valid in SAP IQ, but is not valid in most other SQL implementations:

SELECT SurName,

SAP IQ SQL Reference


Differences from Other SQL Dialects INTERNAL 151
BirthDate,
( SELECT DepartmentName
FROM Departments
WHERE DepartmentID = Employees.EmployeeID
AND DepartmentID = 200 )
FROM Employees

4.7 Additional Functions

SAP IQ supports several functions not in the ANSI SQL definition.

Related Information

SQL Functions [page 193]

4.8 Cursors

When using Embedded SQL, cursor positions can be moved arbitrarily on the FETCH statement. Cursors can
be moved forward or backward relative to the current position or a given number of records from the beginning
or end of the cursor.

SAP IQ SQL Reference


152 INTERNAL Differences from Other SQL Dialects
5 Compatibility with Other SAP Database
Products

Use the topics in this section to simplify migration to SAP IQ from other SAP database products, and to serve
as a guide for creating SAP IQ applications that are compatible with SAP Adaptive Server Enterprise or SAP
SQL Anywhere.

Compatibility features are addressed in each new version of SAP IQ. This section compares SAP IQ with SAP
ASE, and SAP SQL Anywhere.

In this section:

About SAP SQL Anywhere [page 154]


SAP IQ is an extension of SAP SQL Anywhere.

An Overview of Transact-SQL Support [page 154]


SAP IQ, like SAP SQL Anywhere, supports a large subset of Transact-SQL, which is the dialect of SQL
supported by SAP Adaptive Server Enterprise.

SAP ASE, SAP SQL Anywhere, and SAP IQ Architectures [page 155]
SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ are complementary products, with
architectures designed to suit their distinct purposes.

Data Types [page 157]


SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ treat data types differently.

Data Definition Language [page 162]


Differences exist between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ in how you
create databases and database objects.

Data Manipulation Language [page 172]


Query requirements differ between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

Transact-SQL Procedure Language Overview [page 181]


The stored procedure language is the part of SQL used in stored procedures and batches.

Automatic Translation of Stored Procedures [page 184]


In addition to supporting Transact-SQL alternative syntax, SAP SQL Anywhere and SAP IQ provide aids
for translating statements between the Watcom-SQL and Transact-SQL dialects.

Result Sets from Transact-SQL Procedures [page 184]


SAP SQL Anywhere, SAP IQ procedures and Transact-SQL procedures return result sets differently.

Variables in Transact-SQL Procedures [page 185]


SAP SQL Anywhere and SAP IQ assign values to variables in procedures differently than Transact-SQL.

Error Handling in Transact-SQL Procedures [page 186]


Default procedure error handling is different in the Watcom-SQL and Transact-SQL dialects.

SAP SQL Anywhere and SAP IQ Differences and Shared Functionality [page 188]
SAP IQ and SAP SQL Anywhere have differences in starting and managing databases and servers,
database option support, DDL support, and DML support.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 153
Differences and Shared Functionality Between SAP ASE and SAP IQ [page 191]
SAP IQ and SAP Adaptive Server Enterprise have differences in stored procedure support and views
support.

5.1 About SAP SQL Anywhere

SAP IQ is an extension of SAP SQL Anywhere.

In most cases, SQL syntax, functions, options, utilities, procedures, and other features are common to both
products. There are, however, important differences. Do not assume that all features described in SAP SQL
Anywhere documentation are supported for SAP IQ. Use the SAP IQ documentation.

5.2 An Overview of Transact-SQL Support

SAP IQ, like SAP SQL Anywhere, supports a large subset of Transact-SQL, which is the dialect of SQL
supported by SAP Adaptive Server Enterprise.

The goal of Transact-SQL support in SAP IQ is to provide application portability. Many applications, stored
procedures, and batch files can be written for use with both SAP ASE and SAP IQ databases.

The aim is to write applications to work with both SAP ASE and SAP IQ. Existing SAP ASE applications
generally require some changes to run on SAP SQL Anywhere or SAP IQ databases.

Transact-SQL support in SAP IQ takes the following form:

● Most SQL statements are compatible between SAP IQ and SAP ASE.
● For some statements, particularly in the procedure language used in procedures and batches, a separate
Transact-SQL statement is supported along with the syntax supported in earlier versions of SAP IQ. For
these statements, SAP SQL Anywhere and SAP IQ support two dialects of SQL, which we refer to here as
Transact-SQL and Watcom-SQL.
● A procedure or batch is executed in either the Transact-SQL or Watcom-SQL dialect. Use only the control
statements from one dialect throughout the batch or procedure. For example, each dialect has different
flow control statements.

SAP IQ supports a high percentage of Transact-SQL language elements, functions, and statements for working
with existing data.

Further, SAP IQ supports a very high percentage of the Transact-SQL stored procedure language (CREATE
PROCEDURE syntax, control statements, and so on), and many — but not all — aspects of Transact-SQL data
definition language statements.

There are design differences in the architectural and configuration facilities supported by each product. Device
management, user management, and maintenance tasks such as backups tend to be system-specific. Even
here, however, SAP IQ provides Transact-SQL system tables as views, where the tables that are not meaningful
in SAP IQ have no rows. Also, SAP IQ provides a set of system procedures for some of the more common
administrative tasks.

SAP IQ SQL Reference


154 INTERNAL Compatibility with Other SAP Database Products
5.3 SAP ASE, SAP SQL Anywhere, and SAP IQ Architectures

SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ are complementary products, with
architectures designed to suit their distinct purposes.

SAP IQ is a high-performance, decision-support server designed specifically for data warehousing and analytic
processing. SAP SQL Anywhere works well as a workgroup or departmental server requiring little
administration, and as a personal database. SAP ASE works well as an enterprise-level server for large
databases, with a focus on transaction processing.

This section describes architectural differences among the three products. It also describes the SAP ASE-like
tools that SAP IQ and SAP SQL Anywhere include for compatible database management.

In this section:

Servers and Databases [page 155]


The relationship between servers and databases is different in SAP Adaptive Server Enterprise from
SAP IQ and SAP SQL Anywhere.

Space Allocation and Device Management [page 156]


SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ use different models for managing
devices and allocating disk space initially and later, reflecting the different uses for the products.

System Tables, Catalog Store, and IQ Main Store [page 156]


An SAP IQ database is a joint data store.

5.3.1 Servers and Databases

The relationship between servers and databases is different in SAP Adaptive Server Enterprise from SAP IQ
and SAP SQL Anywhere.

In SAP ASE, each database exists inside a server, and each server can contain several databases. Users can
have login rights to the server, and can connect to the server. They can then connect to any of the databases on
that server, provided that they have permissions. System-wide system tables, held in a master database,
contain information common to all databases on the server.

In SAP IQ, there is nothing equivalent to the SAP ASE master database. Instead, each database is an
independent entity, containing all of its system tables. Users can have connection rights to a database, rather
than to the server. When a user connects, he or she connects to an individual database. There is no system-
wide set of system tables maintained at a master database level. Each SAP IQ database server can dynamically
start and stop a database, to which users can maintain independent connections. SAP strongly recommends
that you run only one SAP IQ database per server.

SAP SQL Anywhere and SAP IQ provide tools in their Transact-SQL support and Open Server support to allow
some tasks to be carried out in a manner similar to SAP ASE. There are differences, however, in exactly how
these tools are implemented.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 155
5.3.2 Space Allocation and Device Management

SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ use different models for managing devices
and allocating disk space initially and later, reflecting the different uses for the products.

For example:

● In SAP ASE, you allocate space in database devices initially using DISK INIT and then create a database
on one or more database devices. You can add more space using ALTER DATABASE or automatically, using
thresholds.
● In SAP IQ, you initially allocate space by listing raw devices in the CREATE DATABASE statement. You can
add more space manually using CREATE DBSPACE. Although you cannot add space automatically, you can
create events to warn the DBA before space is actually needed. SAP IQ can also use file system space. SAP
IQ does not support Transact-SQL DISK statements, such as DISK INIT, DISK MIRROR, DISK REFIT,
DISK REINIT, DISK REMIRROR, and DISK UNMIRROR.
● SAP SQL Anywhere is similar to SAP IQ, except that the initial CREATE DATABASE statement takes a single
file system file instead of a list of raw devices. SAP SQL Anywhere lets you initialize its databases using a
command utility named dbinit. SAP IQ provides an expanded version of this utility called iqinit for
initializing SAP IQ databases.

5.3.3 System Tables, Catalog Store, and IQ Main Store

An SAP IQ database is a joint data store.

The joint store consists of:

● The catalog store includes system tables and stored procedures, and resides in a set of tables that are
compatible with SAP SQL Anywhere.
● The permanent IQ main store is the set of SAP IQ tables. Table data is stored in indexes.
● The temporary store consists of a set of temporary tables, which the database server uses for sorting and
other temporary processing.

Catalog distinctions and compatibility features include:

● SAP SQL Anywhere and SAP IQ use a different schema from SAP Adaptive Server Enterprise for the
catalog (tables, columns, and so on).
● SAP SQL Anywhere and SAP IQ provide compatibility views that mimic relevant parts of the SAP ASE
system tables, although there are performance implications when using them.
● In SAP ASE, the database owner (user ID dbo) owns the catalog objects.
● In SAP SQL Anywhere and SAP IQ, the system owner (user ID SYS) owns the catalog objects.

 Note

A dbo user ID owns the SAP ASE-compatible system views provided by SAP IQ.

SAP IQ SQL Reference


156 INTERNAL Compatibility with Other SAP Database Products
5.4 Data Types

SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ treat data types differently.

This section discusses compatibility information for data types.

 Note

Data types that are not included in this section are supported by all three products.

In this section:

Bit Data Type Compatibility [page 157]


SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ support the BIT data type, with
differences.

Character Data Type Compatibility [page 158]


SAP IQ, SAP SQL Anywhere and SAP Adaptive Server Enterprise permit CHAR and VARCHAR data, but
each product treats these types differently.

Binary Data Type Compatibility [page 159]


Binary data type support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP
IQ.

Date, Time, Datetime, and Timestamp Data Types [page 159]


Although SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ all support some form of
date and time data, there are some differences.

Numeric Data Types Compatibility [page 161]


SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ have different default precision and
scale.

Text Data Type Compatibility [page 161]


Support for TEXT data differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP
IQ.

Image Data Type Compatibility [page 161]


Support for IMAGE data differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP
IQ.

Java Data Type Compatibility [page 162]


SAP Adaptive Server Enterprise allows Java data types in the database. SAP SQL Anywhere and SAP IQ
do not.

5.4.1 Bit Data Type Compatibility

SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ support the BIT data type, with differences.

The differences are:

● SAP SQL Anywhere permits only 0 or 1.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 157
● SAP Adaptive Server Enterprise BIT data types only allow 0 or 1 values.
● SAP ASE and SAP IQ implicitly convert integral data types to BIT. Nonzero values are stored as 1 (TRUE).

5.4.2 Character Data Type Compatibility

SAP IQ, SAP SQL Anywhere and SAP Adaptive Server Enterprise permit CHAR and VARCHAR data, but each
product treats these types differently.

● SAP IQ treats all strings as VARCHAR, even in a blank-padded database.


● SAP ASE and SAP IQ differentiate between CHAR (fixed-length) and VARCHAR (variable-length) data.
SAP ASE trims trailing blank spaces from VARCHAR values. SAP IQ trims trailing blanks from VARCHAR
values depending on the form of the data and the operation.
● The CHARACTER (<n>) alternative for CHAR is not supported in SAP Adaptive Server Enterprise.
● SAP IQ does not support the NCHAR, NVARCHAR, UNICHAR, and UNIVARCHAR data types provided by SAP
Adaptive Server Enterprise. SAP IQ supports Unicode in the CHAR and VARCHAR data types.

When inserting into CHAR or VARCHAR:

● SAP SQL Anywhere permits inserting integral data types into CHAR or VARCHAR (implicit conversion).
● SAP ASE and SAP IQ require explicit conversion.

The maximum size of a column is determined as follows:

● SAP ASE CHAR and VARCHAR depend on the logical page size, which can be 2K, 4K, 8K, and 16K. For
example:
○ 2K page size allows a column as large as a single row, about 1962 bytes.
○ 4K page size allows a column as large as about 4010 bytes.
● Both SAP IQ and SAP SQL Anywhere supports up to 32K-1 with CHAR and VARCHAR. SAP SQL Anywhere
supports up to 2 GB with LONG VARCHAR.
● SAP SQL Anywhere supports the name LONG VARCHAR and its synonym TEXT, while SAP ASE supports
only the name TEXT, not the name LONG
● SAP IQ supports a longer LONG VARCHAR data type — to 512 TB (with an SAP IQ page size of 128 KB) and 2
PB (with an SAP IQ page size of 512 KB) — than SAP SQL Anywhere. See SAP IQ Administration:
Unstructured Data Analytics.
● VARCHAR.
● SAP ASE supports multibyte character set NCHAR and NVARCHAR data types, as well as single-byte
character set UNICHAR and UNIVARCHAR data types.
● SAP SQL Anywhere and SAP IQ support Unicode in the CHAR and VARCHAR data types, rather than as a
separate data type.
● For compatibility between SAP IQ and SAP ASE, always specify a length for character data types.

Related Information

Character Data Types [page 115]

SAP IQ SQL Reference


158 INTERNAL Compatibility with Other SAP Database Products
5.4.3 Binary Data Type Compatibility

Binary data type support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ.

Binary data type supported sizes:

Data Type SAP ASE SAP SQL Anywhere SAP IQ

BINARY < page size 32 KB - 1 255

VARBINARY < page size 32 KB - 1 32 KB - 1

LONG BINARY* Not supported 2 GB - 1 512 TB (IQ page size 128 KB) 2 PB (IQ page
size 512 KB)

IMAGE 2 GB 2 GB - 1 use LONG BINARY*

*For information on the LONG BINARY data type in SAP IQ, see Unstructured Data Analytics . This feature
requires a separate license.

SAP ASE and SAP SQL Anywhere display binary data differently when projected:

● SAP IQ supports both SAP ASE and SAP SQL Anywhere display formats.
● If '123' is entered in a BINARY field the SAP SQL Anywhere display format is by bytes, as '123'; the SAP ASE
display format is by nibbles, as '0x616263'.

Related Information

Binary Data Types [page 123]


NEWID Function [Miscellaneous] [page 432]
STRTOUUID Function [String] [page 533]
UUIDTOSTR Function [String] [page 553]
Character Data Types [page 115]

5.4.4 Date, Time, Datetime, and Timestamp Data Types

Although SAP Adaptive Server Enterprise, SAP SQL Anywhere and SAP IQ all support some form of date and
time data, there are some differences.

● SAP SQL Anywhere and SAP IQ support the 4-byte date and time data types.
● SAP ASE supports an 8-byte datetime type, and timestamp as a user-defined data type (domain)
implemented as binary (8).
● SAP SQL Anywhere and SAP IQ support an 8-byte timestamp type, and an 8-byte datetime domain
implemented as timestamp. The millisecond precision of the SAP SQL Anywhere/SAP IQ datetime data
type differs from that of SAP ASE.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 159
Display formats for dates have different defaults:

● SAP ASE defaults to displaying dates in the format "MMM-DD-YYYY" but can be changed by setting an
option.
● SAP SQL Anywhere and SAP IQ default to the ISO "YYYY-MM-DD" format but can be changed by setting an
option.

Time conversions are as follows:

● SAP ASE varies the way it converts time stored in a string to an internal time, depending on whether the
fraction part of the second was delimited by a colon or a period.
● SAP SQL Anywhere and SAP IQ convert times in the same way, regardless of the delimiter.

When you insert a time into a DATETIME column:

● SAP ASE and SAP IQ default to supplying 1st January 1900.


● SAP SQL Anywhere defaults to supplying the current date.

TIME and DATETIME values retrieved from an SAP ASE database change when inserted into an SAP IQ table
with a DATETIME column using INSERT…LOCATION. The INSERT…LOCATION statement uses Open Client,
which has a DATETIME precision of 1/300 of a second.

For example, assume that the following value is stored in a table column in an SAP ASE database:

2004-11-08 10:37:22.823

When you retrieve and store it in an SAP IQ table using INSERT...LOCATION, the value becomes:

2004-11-08 10:37:22.823333

In this section:

Compatibility of Datetime and Time Values from SAP ASE [page 160]
A DATETIME or TIME value retrieved from an SAP Adaptive Server Enterprise database using
INSERT...LOCATION can have a different value due to the datetime precision of Open Client.

BIGTIME and BIGDATETIME Support [page 161]


SAP IQ supports the SAP Adaptive Server Enterprise data types BIGTIME and BIGDATETIME for
Component Integration Services (CIS) and INSERT...LOCATION.

5.4.4.1 Compatibility of Datetime and Time Values from


SAP ASE

A DATETIME or TIME value retrieved from an SAP Adaptive Server Enterprise database using
INSERT...LOCATION can have a different value due to the datetime precision of Open Client.

For example, the DATETIME value in the – database is ‘2012-11-08 10:37:22.823’. When you retrieve it and store
it in SAP IQ using INSERT...LOCATION, the value becomes ‘2012-11-08 10:37:22.823333’.

SAP IQ SQL Reference


160 INTERNAL Compatibility with Other SAP Database Products
5.4.4.2 BIGTIME and BIGDATETIME Support

SAP IQ supports the SAP Adaptive Server Enterprise data types BIGTIME and BIGDATETIME for Component
Integration Services (CIS) and INSERT...LOCATION.

● Component Integration Services with SAP ASE – aseodbc server class proxy tables mapped to SAP ASE
tables that contain columns of data type BIGTIME and BIGDATETIME.
When you create a proxy table mapped to an SAP ASE table, a BIGDATETIME column is mapped to a
TIMESTAMP column by default, if no mapping is specified. A BIGTIME column is mapped to a TIME column
by default.
● INSERT...LOCATION – the INSERT...LOCATION command to load data into SAP IQ tables from SAP ASE
tables that contain columns of data type BIGTIME and BIGDATETIME.
SAP IQ inserts the SAP ASE data type BIGTIME into the SAP IQ data type TIME.
SAP IQ inserts the SAP ASE data type BIGDATETIME into the SAP IQ data types DATETIME, DATE, TIME,
and TIMESTAMP.

5.4.5 Numeric Data Types Compatibility

SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ have different default precision and scale.

● In SAP ASE – the default is precision 18 scale 0.


● In SAP SQL Anywhere – the default is precision 30 scale 6.
● In SAP IQ – the default is precision 126 scale 38. Because these defaults are too large for TDS and for some
client tools, always specify a precision and scale for SAP IQ exact numeric types.

5.4.6 Text Data Type Compatibility

Support for TEXT data differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP ASE supports up to 2 GB with LONG VARBINARY (LONG BINARY in SAP SQL Anywhere) and TEXT.
SAP SQL Anywhere does not support LONG VARBINARY as a column type, but uses LONG BINARY for the
same purpose. SAP SQL Anywhere supports up to 2 GB with LONG BINARY and TEXT.
● SAP IQ supports up to 32 KB - 1 with VARCHAR. SAP IQ also supports up to 512 TB (with an IQ page size of
128 KB) and 2 PB (with an IQ page size of 512 KB) with LONG VARCHAR. For information on the LONG
VARCHAR data type in SAP IQ, see SAP IQ Administration: Unstructured Data Analytics.

5.4.7 Image Data Type Compatibility

Support for IMAGE data differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP ASE and SAP SQL Anywhere support up to 2 GB with IMAGE.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 161
● SAP IQ supports up to 512 TB (with an IQ page size of 128 KB) and 2 PB (with an IQ page size of 512 KB)
with LONG BINARY. For information on the LONG BINARY data type in SAP IQ, see SAP IQ Administration:
Unstructured Data Analytics.

5.4.8 Java Data Type Compatibility

SAP Adaptive Server Enterprise allows Java data types in the database. SAP SQL Anywhere and SAP IQ do not.

5.5 Data Definition Language

Differences exist between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ in how you create
databases and database objects.

In this section:

Creating a Transact-SQL Compatible Database Using the CREATE DATABASE statement [page 163]
Use Interactive SQL to create a Transact-SQL compatible database.

Case-Sensitivity [page 163]


Case-sensitivity in databases refers to the case-sensitivity of data, identifiers, and passwords.

Ensuring Compatible Object Names [page 164]


Each database object must have a unique name within a certain name space.

CREATE TABLE Statement Usage Considerations [page 165]


When creating tables for compatibility, be aware of the following compatibility considerations for NULL
treatment, check constraints, referential integrity, default values, identify columns, computed columns,
temporary tables, and table location.

CREATE DEFAULT, CREATE RULE, and CREATE DOMAIN Statements Usage Considerations [page 168]
SAP IQ provides an alternative means of incorporating rules.

CREATE TRIGGER Statement Usage Considerations [page 168]


Support for triggers differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

CREATE INDEX Statement Usage Considerations [page 169]


CREATE INDEX syntax differs slightly between SAP Adaptive Server Enterprise, SAP SQL Anywhere,
and SAP IQ.

Users, Groups/Roles, and Permissions [page 169]


There are some differences between the SAP Adaptive Server Enterprise and SAP SQL Anywhere and
SAP IQ models of users and roles/groups.

Load Formats [page 171]


Load format support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

Options for Transact-SQL Compatibility [page 171]


Set SAP IQ database options using the SET OPTION statement.

SAP IQ SQL Reference


162 INTERNAL Compatibility with Other SAP Database Products
5.5.1 Creating a Transact-SQL Compatible Database Using
the CREATE DATABASE statement

Use Interactive SQL to create a Transact-SQL compatible database.

Procedure

Type the following statement, for example, in Interactive SQL:

CREATE DATABASE 'db-name.db' CASE RESPECT BLANK PADDING ON

5.5.2 Case-Sensitivity

Case-sensitivity in databases refers to the case-sensitivity of data, identifiers, and passwords.

In this section:

Case-Sensitivity of Data [page 163]


The case-sensitivity of the data is reflected in indexes, in the results of queries, and so on.

Case-Sensitivity of Identifiers [page 163]


Identifiers include table names, column names, user IDs, and so on.

Case-Sensitivity of User IDs and Passwords [page 164]


Case-sensitivity of passwords is treated differently from other identifiers.

5.5.2.1 Case-Sensitivity of Data

The case-sensitivity of the data is reflected in indexes, in the results of queries, and so on.

You decide the case-sensitivity of SAP IQ data in comparisons when you create the database. By default, SAP
IQ databases are case-sensitive in comparisons, although data is always held in the case in which you enter it.

SAP Adaptive Server Enterprise sensitivity to case depends on the sort order installed on the SAP ASE system.
You can change case-sensitivity for single-byte character sets by reconfiguring the SAP ASE sort order.

5.5.2.2 Case-Sensitivity of Identifiers

Identifiers include table names, column names, user IDs, and so on.

SAP IQ does not support case-sensitive identifiers. In SAP Adaptive Server Enterprise, the case-sensitivity of
identifiers follows the case-sensitivity of the data.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 163
In SAP ASE, user-defined data type names are case-sensitive. In SAP IQ, they are case-insensitive.

5.5.2.3 Case-Sensitivity of User IDs and Passwords

Case-sensitivity of passwords is treated differently from other identifiers.

All passwords in newly created databases are case-sensitive, regardless of the case-sensitivity of the database.

When you rebuild an existing database, SAP IQ determines the case-sensitivity of the password as follows:

● If the database was originally entered in a case-insensitive database, the password remains case-
insensitive.
● If the password was originally entered in a case-sensitive database, uppercase and mixed-case passwords
remain case-sensitive. If the password was entered in all lowercase, then the password becomes case-
insensitive.
● Changes to both existing passwords and new passwords are case-sensitive.

5.5.3 Ensuring Compatible Object Names

Each database object must have a unique name within a certain name space.

Outside this name space, duplicate names are allowed. Some database objects occupy different name spaces
in SAP Adaptive Server Enterprise as compared to SAP SQL Anywhere and SAP IQ.

Table Name Uniqueness

Table name uniqueness requirements apply within a database:

● For SAP IQ and SAP SQL Anywhere, table names must be unique within a database for a given owner. For
example, both user1 and user2 can create a table called employee; uniqueness is provided by the fully
qualified names, user1.employee and user2.employee.
● For SAP ASE, table names must be unique within the database and to the owner.

Index Name Uniqueness

Index name uniqueness requirements apply within a table. In all three products, indexes are owned by the
owner of the table on which they are created. Index names must be unique on a given table, but any two tables
can have an index of the same name, even for the same owner. For example, in all three products, tables t1 and
t2 can have indexes of the same name, whether they are owned by the same or different users.

SAP IQ SQL Reference


164 INTERNAL Compatibility with Other SAP Database Products
Renaming Indexes and Foreign Keys

SAP IQ allows you to rename explicitly created indexes, foreign key role names of indexes, and foreign keys,
using the ALTER INDEX statement. SAP SQL Anywhere allows you to rename indexes, foreign key role names,
and foreign keys, using the ALTER INDEX statement. SAP ASE does not allow you to rename these objects.

5.5.4 CREATE TABLE Statement Usage Considerations

When creating tables for compatibility, be aware of the following compatibility considerations for NULL
treatment, check constraints, referential integrity, default values, identify columns, computed columns,
temporary tables, and table location.

NULL in Columns

For compatible treatment of NULL:

● SAP SQL Anywhere and SAP IQ assume that columns can be null unless NOT NULL is stated in the column
definition. You can change this behavior by setting the database option ALLOW_NULLS_BY_DEFAULT to the
Transact-SQL compatible setting of OFF.
● SAP SQL Anywhere and SAP IQ assume that BIT columns cannot be NULL.
● SAP Adaptive Server Enterprise assumes that columns cannot be null unless NULL is stated.

Check Constraints

SAP IQ enforces check constraints on base, global temporary, and local temporary tables, and on user-defined
data types. Users can log check integrity constraint violations and specify the number of violations that can
occur before a LOAD statement rolls back.

SAP IQ does not allow the creation of a check constraint that it cannot evaluate, such as those composed of
user-defined functions, proxy tables, or non-SAP IQ tables. Constraints that cannot be evaluated are detected
the first time the table on which the check constraint is defined is used in a LOAD, INSERT, or UPDATE
statement. SAP IQ does not allow check constraints containing the following:

● Subqueries
● Expressions specifying a host language parameter, a SQL parameter, or a column as the target for a data
value
● Set functions
● Invocations of nondeterministic functions or functions that modify data

SAP ASE and SAP SQL Anywhere enforce CHECK constraints. SAP SQL Anywhere allows subqueries in check
constraints.

SAP IQ supports user-defined data types that allow constraints to be encapsulated in the data type definition.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 165
Referential Integrity Constraints

Actions for enforcing integrity are supported as follows:

● SAP SQL Anywhere supports all ANSI actions: SET NULL, CASCADE, DEFAULT, RESTRICT.
● SAP ASE supports two of these actions: SET NULL, DEFAULT.

 Note

You can achieve CASCADE in SAP ASE by using triggers instead of referential integrity.

● SAP IQ supports the RESTRICT action only.


● SAP IQ does not support NOT NULL FOREIGN KEY.
● SAP IQ has the restriction that a column cannot be both a candidate key and a foreign key at the same
time.

Default Values in a Column

Default value support differs as follows:

● SAP ASE and SAP SQL Anywhere support specifying a default value for a column.
● Only SAP SQL Anywhere supports DEFAULT UTC TIMESTAMP.
● SAP IQ supports specifying a default value for a column, except for the special values DEFAULT UTC
TIMESTAMP and DEFAULT CURRENT UTC TIMESTAMP. SAP IQ also ignores settings for the
DEFAULT_TIMESTAMP_INCREMENT database option.

Identity Columns

Identity column support differs as follows:

● SAP SQL Anywhere supports the AUTOINCREMENT default value. SAP SQL Anywhere supports identity
columns of any numeric type with any allowable scale and precision. The identity column value can be
positive, negative, or zero, limited by the range of the data type. SAP SQL Anywhere supports any number
of identity columns per table, and does not require identity_insert for explicit inserts, drops, and updates.
The table must be empty when adding identity columns. SAP SQL Anywhere identity columns can be
altered to be nonidentity columns, and vice versa. You can add or drop AUTOINCREMENT columns from SAP
SQL Anywhere views.
● SAP ASE supports a single identity column per table. SAP ASE identity columns are restricted to only
numeric data type scale 0, maximum precision 38. They must be positive, are limited by the range of the
data type, and cannot be null. SAP ASE requires identity_insert for explicit inserts and drops, but not for
updates to the identity column. The table can contain data when you add an identity column. SAP ASE
users cannot explicitly set the next value chosen for an identity column. SAP ASE views cannot contain
IDENTITY/AUTOINCREMENT columns. When using SELECT INTO under certain conditions, SAP ASE
allows Identity/Autoincrement columns in the result table if they were in the table being selected from.

SAP IQ SQL Reference


166 INTERNAL Compatibility with Other SAP Database Products
Computed Columns

Computed column support differs as follows:

● SAP SQL Anywhere supports computed columns that can be indexed.


● SAP ASE and SAP IQ do not.

Temporary Tables

You can create a temporary table by placing a pound sign (#) without an owner specification in front of the
table name in a CREATE TABLE statement. These temporary tables are SAP IQ-declared temporary tables and
are available only in the current connection.

Locating Tables

Physical placement of a table is carried out differently in SAP ASE and SAP IQ. SAP IQ supports the ON
<segment-name> clause, but <segment-name> refers to an SAP IQ dbspace.

Output for sp_iqstatus procedure

Sybase IQ (TM) Copyright (c) 1992-2014 by SAP AG or an SAP affiliate company.


All rights reserved.
Version: 16.0.0.735/140225/P/Mainline/Sun_x64/OS 5.10/64bit/2013-08-21 06:15:41
Time Now: 2013-08-21 06:27:14.150
Build Time: 2013-08-21 06:15:41
File Format: 23 on 03/18/1999
Server mode: IQ Server
Catalog Format: 2
Stored Procedure Revision: 1
Page Size: 65536/4096blksz/16bpp
Number of Main DB Files: 2
Main Store Out Of Space: N
Number of Cache Dbspace Files: 5
Number of Shared Temp DB Files: 0
Shared Temp Store Out Of Space: N
Number of Local Temp DB Files: 1
Local Temp Store Out Of Space: N
DB Blocks: 1-25600 IQ_SYSTEM_MAIN
DB Blocks: 522208-547807 MainUser
Cache Dbspace Blocks: 1-5120 ssd_dev_1
Cache Dbspace Blocks: 522208-527327 ssd_dev_2
Cache Dbspace Blocks: 1044416-1049535 ssd_dev_3
Cache Dbspace Blocks: 1566624-1571743 ssd_dev_4
Cache Dbspace Blocks: 2088832-2093951 ssd_dev_5
Local Temp Blocks: 1-25600 IQ_SYSTEM_TEMP
Create Time: 2013-08-21 06:27:05.444
Update Time: 2013-08-21 06:27:14.035
Main IQ Buffers: 1588, 100Mb
Temporary IQ Buffers: 1588, 100Mb
Main IQ Blocks Used: 5250 of 38400, 13%=20Mb, Max Block#: 5313

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 167
Cache Dbspace IQ Blocks Used: 197 of 25600, 0%=0Mb, Max Block#: 0
Shared Temporary IQ Blocks Used: 0 of 0, 0%=0Mb, Max Block#: 0
Local Temporary IQ Blocks Used: 65 of 12800, 0%=0Mb, Max Block#: 0
Main Reserved Blocks Available: 12800 of 12800, 100%=50Mb
Shared Temporary Reserved Blocks Available: 0 of 0, 0%=0Mb
Local Temporary Reserved Blocks Available: 12800 of 12800, 100%=50Mb
IQ Dynamic Memory: Current: 292mb, Max: 308mb
Main IQ Buffers: Used: 18, Locked: 0
Temporary IQ Buffers: Used: 4, Locked: 0
Main IQ I/O: I: L459/P9 O: C21/D33/P22 D:1 C:100.0
Temporary IQ I/O: I: L320/P0 O: C54/D59/P8 D:50 C:100.0
Other Versions: 0 = 0Mb
Active Txn Versions: 0 = C:0Mb/D:0Mb
Last Full Backup ID: 0
Last Full Backup Time:
Last Backup ID: 0
Last Backup Type: None
Last Backup Time:
DB Updated: 0
Blocks in next ISF Backup: 0 Blocks: =0Mb
Blocks in next ISI Backup: 0 Blocks: =0Mb
IQ large memory space: 2048Mb
IQ large memory flexible percentage: 50
IQ large memory flexible used: 0Mb
IQ large memory inflexible percentage: 90
IQ large memory inflexible used: 0Mb
IQ large memory anti-starvation percentage: 50
DB File Encryption Status: OFF
RLV Status: RW
RLV memory limit: 2048Mb
RLV memory used: 0Mb

5.5.5 CREATE DEFAULT, CREATE RULE, and CREATE DOMAIN


Statements Usage Considerations

SAP IQ provides an alternative means of incorporating rules.

● SAP Adaptive Server Enterprise supports the Create Default and Create Rule statements to create
named defaults.
● SAP SQL Anywhere and SAP IQ support the CREATE DOMAIN statement to achieve the same objective.

5.5.6 CREATE TRIGGER Statement Usage Considerations

Support for triggers differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP SQL Anywhere supports both row-level and statement-level triggers.


● SAP ASE supports only statement-level triggers.
● SAP IQ supports triggers only on catalog store tables.

 Note

A trigger is effectively a stored procedure that is run automatically either immediately before or
immediately after an INSERT, UPDATE, or DELETE as part of the same transaction that can be used to
cause a dependent change (for example, to automatically update the name of an employee’s manager

SAP IQ SQL Reference


168 INTERNAL Compatibility with Other SAP Database Products
when the employee is moved to a different department). It can also be used to write an audit trail to identify
which modifications made which changes to the database, and at what time.

5.5.7 CREATE INDEX Statement Usage Considerations

CREATE INDEX syntax differs slightly between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP
IQ.

● SAP ASE and SAP SQL Anywhere support clustered or nonclustered indexes, using the following syntax:

CREATE [UNIQUE] [CLUSTERED] INDEX <name>


ON <table> (<column>,...)
ON <dbspace>

SAP ASE also allows the NONCLUSTERED keyword, but the default is NONCLUSTERED for both products.
● SAP ASE CREATE INDEX statements work in SAP SQL Anywhere because SAP SQL Anywhere allows, but
ignores, the keywords FILLFACTOR, IGNORE_DUP_KEY, SORTED_DATA, IGNORE_DUP_ROW, and
ALLOW_DUP_ROW.
● SAP SQL Anywhere CREATE INDEX syntax supports the VIRTUAL keyword for use by its Index Consultant,
but not for actual query executions.
● SAP IQ supports seven specialized index types: HG, HNG, DATE, TIME, DTTM, and WD. SAP IQ also supports a
CMP index on the relationship between two columns of identical data type, precision, and scale. SAP IQ
defaults to creating an HG index unless the index type is specified in the CREATE INDEX statement:

CREATE [UNIQUE] [<type>] INDEX <name>


ON <table> (<column>,...)

5.5.8 Users, Groups/Roles, and Permissions

There are some differences between the SAP Adaptive Server Enterprise and SAP SQL Anywhere and SAP IQ
models of users and roles/groups.

In SAP ASE, users connect to a server, and each user requires a login ID and password to the server as well as a
user ID for each database they want to access on that server.

SAP SQL Anywhere and SAP IQ users do not require a server login ID. All SAP SQL Anywhere and SAP IQ users
receive a user ID and password for a database.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 169
User Roles/Groups

To allow you to grant permissions to many users at one time, SAP SQL Anywhere and SAP IQ support user
roles while SAP ASE supports user groups. Though basically roles are groups are equivalent, there are some
behavioral differences:

● SAP ASE allows each user to be a member of only one group.


● SAP SQL Anywhere and SAP IQ allow users to be members of multiple roles , and role hierarchies are
allowed.

All three products have a public role or group, for defining default permissions. Every user automatically
becomes a member of the public role or group.

Database Object Permissions

GRANT and REVOKE statements for granting permissions on individual database objects are very similar in all
three products.

● All three products allow SELECT, INSERT, DELETE, UPDATE, and REFERENCES permissions on database
tables and views, and UPDATE permissions on selected columns of database tables. SAP SQL Anywhere
and SAP IQ also allow LOAD and TRUNCATE permissions on database tables and views.
For example, the following statement is valid in all three products:

GRANT INSERT, DELETE


ON TITLES
TO MARY, SALES

This statement grants permission to use the INSERT and DELETE statements on the TITLES table to user
MARY and to the SALES role or group.
● All three products allow EXECUTE permissions to be granted on stored procedures.
● SAP ASE also supports GRANT and REVOKE on additional items:
○ Objects: columns within tables, columns within views, and stored procedures
○ User abilities: CREATE DATABASE, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE
TABLE, CREATE VIEW
● SAP SQL Anywhere and SAP IQ require a user to have the MANAGE ANY OBJECT PRIVILEGE system
privilege to grant database objects permissions. (A closely corresponding SAP ASE permission is GRANT
ALL, used by a Database Owner.)
● All three products support the WITH GRANT OPTION clause, allowing the recipient of permissions to grant
them in turn, although SAP IQ and SAP SQL Anywhere do not permit WITH GRANT OPTION to be used on
a GRANT EXECUTE statement.

Database-wide Permissions

SAP ASE uses a different model for database-wide user permissions.

SAP IQ SQL Reference


170 INTERNAL Compatibility with Other SAP Database Products
● SAP SQL Anywhere and SAP IQ use the SYS_AUTH_DBA_ROLE compatibility role to allow a user full
permissions within a database, assuming that the SYS_AUTH_DBA_ROLE compatibility role has not been
migrated to a hierarchy of roles to meet customer security requirements..
● The System Administrator in SAP ASE enjoys this permission for all databases on a server.
● The database owner must use the SAP ASE SETUSER statement to gain permissions on objects owned by
other users.

Adding Users

SAP ASE requires a two-step process to add a user: sp_addlogin followed by sp_adduser.

SAP SQL Anywhere and SAP IQ add users in a single step.

SAP IQ Login Management stored procedures, although not required to add or drop users, allow users with
applicable system privileges to add or drop SAP IQ user accounts. When SAP IQ User Administration is
enabled, these SAP IQ user accounts allow control user connections and password expirations.

Although SAP SQL Anywhere and SAP IQ allow SAP ASE system procedures for managing users and groups,
the exact syntax and function of these procedures differs in some cases.

Related Information

SAP ASE System Procedures [page 978]

5.5.9 Load Formats

Load format support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP IQ handles ASCII, BINARY, and BCP load formats.


● SAP SQL Anywhere, in addition to ASCII and BINARY, also lets you import dBase, Excel, FoxPro, and Lotus
file formats.
● SAP ASE handles ASCII and BINARY load formats through BCP.

 Note

The syntax of the SAP IQ and SAP SQL Anywhere LOAD statement is based on BCP and designed to offer
exactly the same functionality.

5.5.10 Options for Transact-SQL Compatibility

Set SAP IQ database options using the SET OPTION statement.

See the Transact-SQL compatibility options.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 171
Related Information

Transact-SQL Compatibility Options [page 1733]

5.6 Data Manipulation Language

Query requirements differ between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

In this section:

General Guidelines for Writing Portable SQL [page 173]


Even if more than one server supports a given SQL statement, it might be a mistake to assume that
default behavior is the same on each system.

Criteria for Writing Compatible Queries [page 174]


There are two criteria for writing a query that runs on both SAP IQ and SAP Adaptive Server Enterprise
databases.

Subquery Support [page 175]


SAP IQ currently provides support for subqueries that is somewhat different from that provided by SAP
Adaptive Server Enterprise and SAP SQL Anywhere.

GROUP BY Clause Support [page 175]


GROUP BY ALL support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP
IQ.

COMPUTE Clause Support [page 175]


COMPUTE support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

WHERE Clause Support [page 176]


The WHERE clause differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ in
support for the Contains() predicate, and treatment of trailing white space in the Like() predicate.

Transact-SQL Outer Joins Support [page 176]


Supported syntax for outer joins differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere,
and SAP IQ.

ANSI Joins Support [page 176]


Support for ANSI join syntax differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and
SAP IQ.

Null Comparisons Support [page 177]


SAP Adaptive Server Enterprise has Transact-SQL extensions that permit predicates to compare the
null value.

Zero-Length Strings Support [page 177]


Zero-length strings are treated differently in SAP Adaptive Server Enterprise, SAP SQL Anywhere, and
SAP IQ.

HOLDLOCK, SHARED, and FOR BROWSE Support [page 177]


HOLDLOCK, SHARED, and FOR BROWSE syntax differs between SAP Adaptive Server Enterprise, SAP
SQL Anywhere, and SAP IQ.

SAP IQ SQL Reference


172 INTERNAL Compatibility with Other SAP Database Products
SQL Function Support [page 177]
SAP IQ supports most of the same functions as SAP SQL Anywhere and SAP Adaptive Server
Enterprise, with some differences.

OLAP Function Support [page 178]


Currently, SAP Adaptive Server Enterprise does not support OLAP functions. SAP IQ and SAP SQL
Anywhere do.

System Function Support [page 179]


SAP IQ and SAP SQL Anywhere do not support certain SAP Adaptive Server Enterprise system
functions.

User-Defined Function Support [page 180]


User-defined function (UDF) support differs between SAP Adaptive Server Enterprise, SAP SQL
Anywhere, and SAP IQ.

Differences Interpreting Arithmetic Expressions on Dates [page 180]


SAP SQL Anywhere and SAP IQ interpret arithmetic expressions on dates as shorthand notation for
various date functions. SAP Adaptive Server Enterprise does not.

SELECT INTO Statement Support [page 180]


There are differences in the types of tables permitted in SELECT INTO statements in SAP Adaptive
Server Enterprise, SAP SQL Anywhere, and SAP IQ.

Updatable Views Support [page 181]


SAP Adaptive Server Enterprise and SAP SQL Anywhere are more liberal than ANSI permits on the view
definitions that are updatable when the WITH CHECK option is not requested.

Support for FROM Clause in UPDATE and DELETE [page 181]


SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ all support the FROM clause with
multiple tables in UPDATE and DELETE.

5.6.1 General Guidelines for Writing Portable SQL

Even if more than one server supports a given SQL statement, it might be a mistake to assume that default
behavior is the same on each system.

General guidelines applicable to writing compatible SQL include:

● When writing SQL for use on more than one database management system, make your SQL statements as
explicit as possible.
● Spell out all of the available options, rather than using default behavior.
● Use parentheses to make the order of execution within statements explicit, rather than assuming identical
default order of precedence for operators.
● Use the Transact-SQL convention of an @ sign preceding variable names for SAP Adaptive Server
Enterprise portability.
● Declare variables and cursors in procedures and batches immediately following a BEGIN statement. SAP IQ
requires this, although SAP ASE allows declarations to be made anywhere in a procedure or batch.
● Do not use reserved words from either SAP ASE or SAP IQ as identifiers in your databases.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 173
5.6.2 Criteria for Writing Compatible Queries

There are two criteria for writing a query that runs on both SAP IQ and SAP Adaptive Server Enterprise
databases.

● The data types, expressions, and search conditions in the query must be compatible.
● The syntax of the SELECT statement itself must be compatible.

SAP IQ supports the following subset of the Transact-SQL SELECT statement.

Syntax

SELECT [ ALL | DISTINCT ] <select-list>


…[ INTO <#temporary-table-name> ]
…[ FROM <table-spec>,
… <table-spec>, … ]
…[ WHERE <search-condition> ]
…[ GROUP BY <column-name>, … ]
…[ HAVING <search-condition> ]
…| [ ORDER BY <expression> [ ASC | DESC ], … ] |
| [ ORDER BY <integer> [ ASC | DESC ], … ] |

Parameters

select-list:

{ <table-name.* >}…
{ <*> }…
{ <expression> }…
{ <alias-name> = <expression> }…
{ <expression as identifier> }…
{ <expression as T_string> }…

table-spec:

[ <owner>. ]<table-name>
… [ [ AS ] <correlation-name> ]

alias-name:

<identifier> | '<string>' | "<string>"

The sections that follow provide details on several items to be aware of when writing compatible queries.

Related Information

Variables in Transact-SQL Procedures [page 185]

SAP IQ SQL Reference


174 INTERNAL Compatibility with Other SAP Database Products
5.6.3 Subquery Support

SAP IQ currently provides support for subqueries that is somewhat different from that provided by SAP
Adaptive Server Enterprise and SAP SQL Anywhere.

SAP ASE and SAP SQL Anywhere support subqueries in the ON clause; SAP IQ does not currently support this.

UNION in subqueries is supported as follows:

● SAP SQL Anywhere supports UNION in both correlated and uncorrelated subqueries.
● SAP IQ supports UNION only in uncorrelated subqueries.
● SAP ASE does not support UNION in any subqueries.

SAP SQL Anywhere supports subqueries in many additional places that a scalar value might appear in the
grammar. SAP ASE and SAP IQ follow the ANSI standard as to where subqueries can be specified.

5.6.4 GROUP BY Clause Support

GROUP BY ALL support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP ASE supports GROUP BY ALL, which returns all possible groups including those eliminated by the
WHERE clause and HAVING clause. These have the NULL value for all aggregates.
● SAP SQL Anywhere does not support the GROUP BY ALL Transact-SQL extension.

ROLLUP and CUBE in the GROUP BY clause are supported as follows:

● SAP IQ and SAP SQL Anywhere support ROLLUP and CUBE in the GROUP BY clause.
● SAP ASE does not currently support ROLLUP and CUBE.

SAP ASE supports projecting non-grouped columns in the SELECT clause. This is known as extended group by
semantics and returns a set of values. SAP IQ supports and SAP SQL Anywhere do not support extended group
by semantics. Only SAP SQL Anywhere supports the List() aggregate to return a list of values.

5.6.5 COMPUTE Clause Support

COMPUTE support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP ASE supports the Transact-SQL COMPUTE clause.


● SAP SQL Anywhere and SAP IQ do not support the Transact-SQL COMPUTE clause since it is not in the
ANSI standard and this functionality is provided by most third-party front-end tools.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 175
5.6.6 WHERE Clause Support

The WHERE clause differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ in
support for the Contains() predicate, and treatment of trailing white space in the Like() predicate.

● SAP IQ supports the Contains() predicate for word searches in character data (similar to Contains in MS
SQL Server and Verity). SAP IQ uses WORD indexes and TEXT indexes to optimize these, if possible.
● SAP ASE does not support Contains().

5.6.7 Transact-SQL Outer Joins Support

Supported syntax for outer joins differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP
IQ.

● SAP ASE fully supports *= and =* Transact-SQL syntax for outer joins.
● SAP SQL Anywhere and SAP IQ support Transact-SQL outer joins, but reject some complex Transact-SQL
outer joins that are potentially ambiguous.
● SAP IQ does not support chained (nested) Transact-SQL outer joins. Use ANSI syntax for this type of
multiple outer join.

 Note

Transact-SQL outer join syntax is deprecated in SAP SQL Anywhere and SAP IQ.

For detailed information on Transact-SQL outer joins, including ANSI syntax alternatives, see the white paper
Semantics and Compatibility of Transact-SQL Outer Joins, on the SAP Community Network . Although
written for SAP SQL Anywhere, the information in the document also applies to SAP IQ.

5.6.8 ANSI Joins Support

Support for ANSI join syntax differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

● SAP IQ does not support subqueries in the ON clause.


● SAP ASE and SAP SQL Anywhere support subqueries in the ON clause.
● A CONTAINS condition in the FROM clause in queries using ANSI join syntax is supported but may have
suboptimal performance. Using Outer Joins for CONTAINS in the FROM clause should only be used if the
“score” column from each of the CONTAINS clauses is required. Otherwise CONTAINS should be moved to
an ON condition or WHERE clause.

Full outer join support is as follows:

● SAP SQL Anywhere and SAP IQ support FULL OUTER JOIN.


● SAP ASE does not support FULL OUTER JOIN.

SAP IQ SQL Reference


176 INTERNAL Compatibility with Other SAP Database Products
5.6.9 Null Comparisons Support

SAP Adaptive Server Enterprise has Transact-SQL extensions that permit predicates to compare the null value.

For example, {col} = Null means {col} Is Null.

SAP SQL Anywhere and SAP IQ use ANSI semantics for null comparisons unless the ANSINULL option is set to
OFF, in which case such comparisons are SAP ASE-compatible.

 Note

SAP SQL Anywhere 8.0 and later adds support for the TDS_EMPTY_STRING_AS_NULL to offer SAP ASE
compatibility in mapping empty strings to the null value.

5.6.10 Zero-Length Strings Support

Zero-length strings are treated differently in SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

The differences are as follows:

● SAP ASE treats zero-length strings as the null value.SAP ASE users store a single space for blank strings.
● SAP SQL Anywhere and SAP IQ follow ANSI semantics for zero-length strings, that is, a zero-length string
is a real value; it is not null.

5.6.11 HOLDLOCK, SHARED, and FOR BROWSE Support

HOLDLOCK, SHARED, and FOR BROWSE syntax differs between SAP Adaptive Server Enterprise, SAP SQL
Anywhere, and SAP IQ.

The differences are as follows:

● SAP ASE supports HOLDLOCK, SHARED, and FOR BROWSE syntax.


● SAP SQL Anywhere supports HOLDLOCK but does not support SHARED or FOR BROWSE.
● SAP IQ does not support these keywords.

5.6.12 SQL Function Support

SAP IQ supports most of the same functions as SAP SQL Anywhere and SAP Adaptive Server Enterprise, with
some differences.

● SAP ASE supports the USING CHARACTERS | USING BYTES syntax in PatIndex(); SAP SQL
Anywhere and SAP IQ do not.
● SAP ASE supports the Reverse() function; SAP SQL Anywhere and SAP IQ do not.
● SAP ASE supports Len() as alternative syntax for Length(); SAP SQL Anywhere does not support this
alternative.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 177
● SAP ASE supports the Square() and Str_Replace() Microsoft compatibility functions; SAP SQL
Anywhere does not.
● SAP IQ supports Str_Replace().
● SAP ASE and SAP SQL Anywhere support TSEQUAL() to compare two timestamps for modification time;
SAP IQ does not support TSEQUAL(). (TSEQUAL is not relevant in the SAP IQ table-level versioning model.)
● SAP IQ supports ROWID(); SAP ASE and SAP SQL Anywhere do not.
● SAP SQL Anywhere and SAP IQ support Cast() in addition to SAP ASE’s Convert() for data type
conversions.

 Note

Cast() is the ANSI-compliant name.

● SAP SQL Anywhere and SAP IQ support Lcase() and Ucase() as synonyms of Lower() and Upper();
SAP ASE does not.
● SAP SQL Anywhere and SAP IQ support the Locate() string function; SAP ASE does not.
● SAP SQL Anywhere supports the IsDate() and IsNumeric() function to test the ability to convert a
string to the respective data type; SAP ASE does not. SAP IQ supports IsDate(). You can use IsNumeric
in SAP IQ, but CIS functional compensation performance considerations apply.
● SAP SQL Anywhere supports the NEWID, STRTOUID, and UUIDTOSTR functions; SAP ASE does not. These
are native functions in SAP IQ, so CIS functional compensation performance considerations do not apply.

 Note

Some SQL functions, including SOUNDEX and DIFFERENCE string functions, and some date functions
operate differently in SAP IQ and SAP SQL Anywhere. The SAP IQ database option
ASE_FUNCTION_BEHAVIOR specifies that output of some of the SAP IQ data type conversion functions,
including HEXTOINT and INTTOHEX, is consistent with the output of SAP ASE functions.

5.6.13 OLAP Function Support

Currently, SAP Adaptive Server Enterprise does not support OLAP functions. SAP IQ and SAP SQL Anywhere
do.

SAP IQ currently supports these OLAP functions:

● Corr()
● Covar_Pop()
● Covar_Samp()
● Cume_Dist
● Dense_Rank()
● Exp_Weighted_Avg
● First_Value
● Last_Value
● Median
● Ntile()

SAP IQ SQL Reference


178 INTERNAL Compatibility with Other SAP Database Products
● Percent_Rank()
● Percentile_Cont()
● Percentile_Disc()
● Rank()
● Regr_Avgx()
● Regr_Avgy()
● Regr_Intercept()
● Regr_R2
● Regr_Slope()
● Regr_Sxx()
● Regr_Sxy()
● Regr_Syy()
● StdDev()
● Stddev_Pop
● Stddev_Samp
● Var_Pop
● Var_Samp
● Variance()
● Weighted_Avg

SAP SQL Anywhere supports all of the SAP IQ OLAP functions.

Currently, SAP ASE does not support OLAP functions.

CIS functional compensation does not support OLAP functions.

 Note

Support for OLAP functions is a rapidly evolving area of SAP product development.

5.6.14 System Function Support

SAP IQ and SAP SQL Anywhere do not support certain SAP Adaptive Server Enterprise system functions.

These SAP ASE system functions are not supported by SAP SQL Anywhere and SAP IQ:

● curunreservedpgs() – number of pages free on a dbspace.


● data_pgs() – number of pages used by a table or index.
● host_id() – UNIX PID (processor ID) of the server process.
● hos_name() – name of the machine on which the server is running.
● lct_admin() – manages the "last chance threshold" for the Transaction manager.
● reserved_pgs() – number of pages allocated to a table or index.
● rowcnt() – number of rows in the specified table.
● valid_name() – whether a name would be a valid name if used, for example, for a table.
● valid_user() – returns TRUE if that user has connect permissions.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 179
● ptn_data_pgs() – number of data pages in a partition.
● index_colorder() – returns the column order in an index.

5.6.15 User-Defined Function Support

User-defined function (UDF) support differs between SAP Adaptive Server Enterprise, SAP SQL Anywhere, and
SAP IQ.

Differences are as follows:

● SAP SQL Anywhere supports UDFs in SQL, Java, and C.


● SAP ASE supports UDFs written only in Java.
● SAP IQ offers support for external C/C++ and Java UDFs as a licensed option. SAP IQ offers support for
Interactive SQL UDFs via CIS query decomposition, but there are performance implications.

5.6.16 Differences Interpreting Arithmetic Expressions on


Dates

SAP SQL Anywhere and SAP IQ interpret arithmetic expressions on dates as shorthand notation for various
date functions. SAP Adaptive Server Enterprise does not.

● Date +/- integer is equivalent to Dateadd().


● Date – date is equivalent to Datediff().
● Date + time creates a timestamp from the two.

5.6.17 SELECT INTO Statement Support

There are differences in the types of tables permitted in SELECT INTO statements in SAP Adaptive Server
Enterprise, SAP SQL Anywhere, and SAP IQ.

Consider this example statement:

select into <table1> from <table2>

● SAP ASE permits <table1> to be permanent, temporary, or a proxy table. SAP ASE also supports SELECT
INTO EXISTING TABLE.
● SAP SQL Anywhere and SAP IQ permit <table1> to be a permanent or a temporary table. A permanent
table is created only when you select into <table> and specify more than one column. SELECT INTO
<#table>, without an owner specification, always creates a temporary table, regardless of the number of
columns specified. SELECT INTO table with just one column selects into a host variable.

SAP IQ SQL Reference


180 INTERNAL Compatibility with Other SAP Database Products
5.6.18 Updatable Views Support

SAP Adaptive Server Enterprise and SAP SQL Anywhere are more liberal than ANSI permits on the view
definitions that are updatable when the WITH CHECK option is not requested.

SAP SQL Anywhere offers the ANSI_UPDATE_CONSTRAINTS option to control whether updates are restricted
to those supported by SQL92, or a more liberal set of rules.

SAP IQ permits UPDATE only on single-table views that can be flattened. SAP IQ does not support WITH
CHECK.

5.6.19 Support for FROM Clause in UPDATE and DELETE

SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ all support the FROM clause with multiple
tables in UPDATE and DELETE.

5.7 Transact-SQL Procedure Language Overview

The stored procedure language is the part of SQL used in stored procedures and batches.

SAP SQL Anywhere and SAP IQ support a large part of the Transact-SQL stored procedure language in addition
to the Watcom-SQL dialect based on SQL92.

In this section:

Transact-SQL Stored Procedure Overview [page 181]


Because it is based on the ISO/ANSI draft standard, the SAP SQL Anywhere and SAP IQ stored
procedure language differs from the Transact-SQL dialect in many ways.

Transact-SQL Batch Overview [page 182]


In Transact-SQL, a batch is a set of SQL statements submitted together and executed as a group, one
after the other.

SQL Statements in Procedures and Batches [page 182]


Some SQL statements supported by SAP IQ are part of one dialect, but not the other.

5.7.1 Transact-SQL Stored Procedure Overview

Because it is based on the ISO/ANSI draft standard, the SAP SQL Anywhere and SAP IQ stored procedure
language differs from the Transact-SQL dialect in many ways.

Many of the concepts and features are similar, but the syntax is different. SAP SQL Anywhere and SAP IQ
support for Transact-SQL takes advantage of the similar concepts by providing automatic translation between
dialects. However, you must write a procedure exclusively in one of the two dialects, not in a mixture of the two.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 181
There are a variety of aspects to SAP SQL Anywhere and SAP IQ support for Transact-SQL stored procedures,
including:

● Passing parameters
● Returning result sets
● Returning status information
● Providing default values for parameters
● Control statements
● Error handling

5.7.2 Transact-SQL Batch Overview


In Transact-SQL, a batch is a set of SQL statements submitted together and executed as a group, one after the
other.

Batches can be stored in command files. The ISQL utility in SAP SQL Anywhere and SAP IQ and the isql utility
in SAP Adaptive Server Enterprise provide similar capabilities for executing batches interactively.

The control statements used in procedures can also be used in batches. SAP SQL Anywhere and SAP IQ
support the use of control statements in batches and the Transact-SQL-like use of nondelimited groups of
statements terminated with a GO statement to signify the end of a batch.

For batches stored in command files, SAP SQL Anywhere and SAP IQ support the use of parameters in
command files. SAP ASE does not support parameters.

5.7.3 SQL Statements in Procedures and Batches


Some SQL statements supported by SAP IQ are part of one dialect, but not the other.

You cannot mix the two dialects within a procedure or batch. This means that:

● You can include Transact-SQL-only statements with statements that are part of both dialects in a batch or
procedure.
● You can include statements not supported by SAP Adaptive Server Enterprise with statements that are
supported by both servers in a batch or procedure.
● You cannot include Transact-SQL–only statements with SAP IQ—only statements in a batch or procedure.

SQL statements not separated by semicolons are part of a Transact-SQL procedure or batch. See SAP IQ SQL
Reference for details of individual statements.

Transact-SQL compatibility has improved; incorrect SQL syntax that was previously accepted now fails with an
error.

In this section:

Expression Subqueries in IF Statements [page 183]


SAP Adaptive Server Enterprise and SAP SQL Anywhere support comparisons between a variable and
a scalar value returned by an expression subquery.

CASE Statement Support [page 183]

SAP IQ SQL Reference


182 INTERNAL Compatibility with Other SAP Database Products
Permitted usage of the CASE statement differs in SAP IQ and SAP SQL Anywhere.

Row-level Cursor Operations Support [page 183]


SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ support the use of cursors with
UPDATE and DELETE.

PRINT Command Support [page 184]


Support for PRINT differs in SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

5.7.3.1 Expression Subqueries in IF Statements

SAP Adaptive Server Enterprise and SAP SQL Anywhere support comparisons between a variable and a scalar
value returned by an expression subquery.

For example:

create procedure testIf ()


begin
declare var4 int;
set var4 = 10;
if var4 = (select MIN (a_i1) from a) then set
var4 = 100;
end if;
end;

5.7.3.2 CASE Statement Support

Permitted usage of the CASE statement differs in SAP IQ and SAP SQL Anywhere.

The CASE statement is not supported in SAP Adaptive Server Enterprise, which supports case expressions
only.

Related Information

Expressions [page 40]

5.7.3.3 Row-level Cursor Operations Support

SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ support the use of cursors with UPDATE and
DELETE.

Consider this example:

UPDATE WHERE CURRENT OF {cursor}

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 183
DELETE WHERE CURRENT OF {cursor}

In SAP IQ, updatable cursors are asensitive only, for one table only, and chained only. Updatable hold cursors
are not permitted. Updatable cursors in SAP IQ get a table lock.

5.7.3.4 PRINT Command Support

Support for PRINT differs in SAP Adaptive Server Enterprise, SAP SQL Anywhere, and SAP IQ.

The effect of PRINT depends on the client:

● SAP ASE PRINT always sends a message to the client.


● In SAP SQL Anywhere and SAP IQ, PRINT sends a message to the client for Open Client and JDBC
connections.
● SAP ASE stored procedures that rely on PRINT work in SAP IQ using Interactive SQL.

 Note

Interactive SQL uses the deprecated iAnywhere JDBC driver.

5.8 Automatic Translation of Stored Procedures

In addition to supporting Transact-SQL alternative syntax, SAP SQL Anywhere and SAP IQ provide aids for
translating statements between the Watcom-SQL and Transact-SQL dialects.

Functions returning information about SQL statements and enabling automatic translation of SQL statements
include:

● SQLDialect(statement) – returns Watcom-SQL or Transact-SQL.


● WatcomSQL(statement) – returns the Watcom-SQL syntax for the statement.
● TransactSQL(statement) – returns the Transact-SQL syntax for the statement.

These are functions and thus can be accessed using a SELECT statement from ISQL. For example, the following
statement returns the value Watcom-SQL:

SELECT SqlDialect('select * from Employees')

5.9 Result Sets from Transact-SQL Procedures

SAP SQL Anywhere, SAP IQ procedures and Transact-SQL procedures return result sets differently.

SAP SQL Anywhere and SAP IQ use a RESULT clause to specify returned result sets.

SAP IQ SQL Reference


184 INTERNAL Compatibility with Other SAP Database Products
In Transact-SQL procedures, column names or alias names of the first query are returned to the calling
environment.

The following Transact-SQL procedure illustrates how Transact-SQL stored procedures return result sets:

CREATE PROCEDURE showdept (@deptname varchar(30))


AS
SELECT Employees.Surname, Employees.GivenName
FROM Departments, Employees
WHERE Departments.DepartmentName = @deptname
AND Departments.DepartmentID = Employees.DepartmentID

The following is the corresponding SAP SQL Anywhere or SAP IQ procedure:

CREATE PROCEDURE showdept(in deptname varchar(30))


RESULT ( lastname char(20), firstname char(20))
BEGIN
SELECT Employees.Surname, Employees.GivenName
FROM Departments, Employees
WHERE Departments.DepartmentName = deptname
AND Departments.DepartmentID = Employee.DepartmentID
END

There are minor differences in the way the client tools present multiple results to the client:

● isql displays all results in a single stream.


● Interactive SQL presents each result set on a separate tab. You must enable this functionality in the Option
menu. Make it a permanent change, then restart or reconnect to Interactive SQL.

5.10 Variables in Transact-SQL Procedures

SAP SQL Anywhere and SAP IQ assign values to variables in procedures differently than Transact-SQL.

SAP SQL Anywhere and SAP IQ use the SET statement to assign values to variables in a procedure.

In Transact-SQL, values are assigned using the SELECT statement with an empty table list. The following
simple procedure illustrates how the Transact-SQL syntax works:

CREATE PROCEDURE multiply


@mult1 int,
@mult2 int,
@result int output
AS
SELECT @result = @mult1 * @mult2

This procedure can be called as follows:

CREATE VARIABLE @product int


go
EXECUTE multiply 5, 6, @product OUTPUT
go

The variable <@product> has a value of 30 after the procedure executes.

There are some differences in order and persistence of variable declarations:

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 185
● In SAP Adaptive Server Enterprise, you can declare variables anywhere in the body of a stored procedure.
Variables persist for the duration of the procedure.
● In SAP SQL Anywhere and SAP IQ, you must declare variables at the beginning of a compound statement
(that is, immediately after BEGIN in a BEGIN...END pair). Variables persist only for the duration of the
compound statement.

Related Information

Criteria for Writing Compatible Queries [page 174]

5.11 Error Handling in Transact-SQL Procedures

Default procedure error handling is different in the Watcom-SQL and Transact-SQL dialects.

By default, Watcom-SQL dialect procedures exit when they encounter an error, returning SQLSTATE and
SQLCODE values to the calling environment.

You can build explicit error handling into Watcom-SQL stored procedures using the EXCEPTION statement, or
you can instruct the procedure to continue execution at the next statement when it encounters an error, using
the ON EXCEPTION RESUME statement.

When a Transact-SQL dialect procedure encounters an error, execution continues at the following statement.
The global variable @@error holds the error status of the most recently executed statement. You can check
this variable following a statement to force return from a procedure. For example, the following statement
causes an exit if an error occurs:

IF @@error != 0 RETURN

When the procedure completes execution, a return value indicates the success or failure of the procedure. This
return status is an integer, and can be accessed as follows:

DECLARE @status INT


EXECUTE @status = proc_sample
IF @status = 0
PRINT 'procedure succeeded'
ELSE
PRINT 'procedure failed'

This table describes the built-in procedure return values and their meanings:

Value Meaning

0 Procedure executed without error

-1 Missing object

-2 Data type error

SAP IQ SQL Reference


186 INTERNAL Compatibility with Other SAP Database Products
Value Meaning

-3 Process was chosen as deadlock victim

-4 Permission error

-5 Syntax error

-6 Miscellaneous user error

-7 Resource error, such as out of space

-8 Nonfatal internal problem

-9 System limit was reached

-10 Fatal internal inconsistency

-11 Fatal internal inconsistency

-12 Table or index is corrupt

-13 Database is corrupt

-14 Hardware error

The RETURN statement can be used to return other integers, with their own user-defined meanings.

In this section:

Using the RAISERROR Statement in Procedures [page 187]


The RAISERROR statement is a Transact-SQL statement for generating user-defined errors. It has a
similar function to the SIGNAL statement.

Transact-SQL-Like Error Handling in the Watcom-SQL Dialect [page 188]


You can make a Watcom-SQL dialect procedure handle errors in a Transact-SQL-like manner.

5.11.1 Using the RAISERROR Statement in Procedures


The RAISERROR statement is a Transact-SQL statement for generating user-defined errors. It has a similar
function to the SIGNAL statement.

By itself, RAISERROR does not cause an exit from the procedure, but it can be combined with a RETURN
statement or a test of the @@error global variable to control execution following a user-defined error.

If you set the ON_TSQL_ERROR database option to CONTINUE, RAISERROR no longer signals an execution-
ending error. Instead, the procedure completes and stores the RAISERROR status code and message, and
returns the most recent RAISERROR. If the procedure causing the RAISERROR was called from another
procedure, RAISERROR returns after the outermost calling procedure terminates.

You lose intermediate RAISERROR statuses and codes when the procedure terminates. If, at return time, an
error occurs along with RAISERROR, the error information is returned and you lose the RAISERROR

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 187
information. The application can query intermediate RAISERROR statuses by examining @@error global
variable at different execution points.

5.11.2 Transact-SQL-Like Error Handling in the Watcom-SQL


Dialect

You can make a Watcom-SQL dialect procedure handle errors in a Transact-SQL-like manner.

Supply the ON EXCEPTION RESUME clause to the CREATE PROCEDURE statement:

CREATE PROCEDURE sample_proc()


ON EXCEPTION RESUME
BEGIN
...
END

The presence of an ON EXCEPTION RESUME clause prevents explicit exception handling code from being
executed, so avoid using these two clauses together.

5.12 SAP SQL Anywhere and SAP IQ Differences and Shared


Functionality

SAP IQ and SAP SQL Anywhere have differences in starting and managing databases and servers, database
option support, DDL support, and DML support.

For additional information, always refer to the SAP IQ documentation set when using the product. Refer to the
SAP SQL Anywhere documentation set when using SAP SQL Anywhere, or when the SAP IQ documentation
refers to SAP SQL Anywhere documentation for specific functionality only.

In this section:

SAP SQL Anywhere Server and Database Startup and Administration [page 189]
Starting and managing databases and servers differs between SAP IQ and SAP SQL Anywhere.

SAP SQL Anywhere Data Definition Language (DDL) Differences [page 189]
SAP SQL Anywhere and SAP IQ have differences in DDL behavior.

SAP SQL Anywhere Data Manipulation Language (DML) Differences [page 190]
Not all SAP SQL Anywhere DML objects and syntax are supported by SAP IQ.

SAP IQ SQL Reference


188 INTERNAL Compatibility with Other SAP Database Products
5.12.1 SAP SQL Anywhere Server and Database Startup and
Administration

Starting and managing databases and servers differs between SAP IQ and SAP SQL Anywhere.

● SAP IQ uses the server startup command start_iq, instead of the SAP SQL Anywhere network server
startup command.
● SAP IQ does not support personal servers.
● SAP IQ supports many SAP SQL Anywhere server command line options, but not all. Other server options
are supported for SAP IQ but not for SAP SQL Anywhere.
● SAP IQ provides the stop_iq utility (UNIX) to shut down servers.
● Clauses permitted in the BACKUP DATABASE and RESTORE DATABASE statements differ in SAP IQ and
SAP SQL Anywhere.
● SQL Remote is supported in SAP IQ only for multiplex operations.

SAP IQ supports many SAP SQL Anywhere database administration utilities, but not all:

● The following SAP SQL Anywhere utilities are not supported by SAP IQ:
○ backup
○ compression
○ console
○ initialization
○ license
○ log transfer
○ log translation
○ rebuild
○ spawn
○ some transaction log options (-g, -il, -ir, -n, -x, -z)
○ uncompression
○ unload
○ upgrade
○ write file
● SAP IQ supports the SAP SQL Anywhere validation utility only on the catalog store. To validate the IQ
main store, use sp_iqcheckdb.

5.12.2 SAP SQL Anywhere Data Definition Language (DDL)


Differences

SAP SQL Anywhere and SAP IQ have differences in DDL behavior.

● In a DELETE/DROP or PRIMARY KEY clause of an ALTER TABLE statement, SAP IQ takes the RESTRICT
action (reports an error if there are associated foreign keys). SAP SQL Anywhere always takes the
CASCADE action.
● Similarly, DROP TABLE statement reports an error in SAP IQ if there are associated foreign-key constraints.

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 189
● SAP IQ does not support these DDL statements: CREATE COMPRESSED DATABASE, CREATE TRIGGER,
SETUSER.
● SAP IQ supports referential integrity at the statement level, rather than the transaction-level integrity that
SAP SQL Anywhere supports with the CHECK ON COMMIT clause of the CREATE TABLE statement.
● An SAP IQ table cannot have a foreign key that references an SAP SQL Anywhere (or catalog) table, and an
SAP SQL Anywhere table cannot have a foreign key that references an SAP IQ table.
● In an SAP IQ database, publications can only be created on SAP SQL Anywhere tables.
● In CREATE DATABASE, the defaults for case-sensitivity and collation differ. The defaults for SAP IQ are
CASE RESPECT and the ISO_BINENG collation; for SAP SQL Anywhere, the defaults are CASE IGNORE,
and collation inferred from the language and character set of the operating system.
● SAP IQ does not support the CREATE ENCRYPTED DATABASE and CREATE DECRYPTED DATABASE
commands supported by SAP SQL Anywhere. See SAP IQ Administration: User Management and Security.

5.12.3 SAP SQL Anywhere Data Manipulation Language


(DML) Differences

Not all SAP SQL Anywhere DML objects and syntax are supported by SAP IQ.

● SAP IQ does not support these DML and procedural statements:


○ EXPLAIN
○ GET DATA
○ INPUT
○ PREPARE TO COMMIT
○ PUT
○ READTEXT
○ ROLLBACK TRIGGER
○ SYSTEM
○ UNLOAD TABLE
○ VALIDATE TABLE

 Note

A set of extraction options performs a role similar to UNLOAD TABLE.

● SAP IQ supports the INSERT...LOCATION syntax; SAP SQL Anywhere does not.
● LOAD TABLE options differ in SAP IQ and SAP SQL Anywhere.
● OPEN statement in SAP IQ does not support BLOCK and ISOLATION LEVEL clauses.
● SAP IQ does not support triggers.
● Use of transactions, isolation levels, checkpoints, and automatically generated COMMITs, as well as cursor
support, is different in SAP IQ and SAP SQL Anywhere.
● When you SELECT from a stored procedure in SAP IQ, CIS functional compensation performance
considerations apply.
● SAP IQ ignores the database name qualifier in fully qualified names in SAP Adaptive Server Enterprise
SELECT statements, such as a FROM clause with <database name>.<owner>.<table name>. For
example, SAP IQ interprets the query SELECT * FROM XXX..TEST as SELECT * FROM TEST.

SAP IQ SQL Reference


190 INTERNAL Compatibility with Other SAP Database Products
5.13 Differences and Shared Functionality Between SAP ASE
and SAP IQ

SAP IQ and SAP Adaptive Server Enterprise have differences in stored procedure support and views support.

For additional information, always refer to the SAP IQ documentation set when using the product. Refer to the
SAP ASE documentation set when using SAP ASE, or when the SAP IQ documentation refers to SAP ASE
documentation for specific functionality only.

In this section:

SAP ASE Stored Procedures [page 191]


Certain stored procedures are not supported by SAP IQ.

SAP ASE System Views [page 191]


Certain views are not supported by SAP IQ.

5.13.1 SAP ASE Stored Procedures

Certain stored procedures are not supported by SAP IQ.

SAP IQ does not support these SAP Adaptive Server Enterprise stored procedures:

● sp_addserver
● sp_configure
● sp_estspace
● sp_help
● sp_helpuser
● sp_who

SAP IQ does not support the following catalog procedures:

● sp_column_privileges
● sp_databases
● sp_datatype_info
● sp_server_info

5.13.2 SAP ASE System Views

Certain views are not supported by SAP IQ.

SAP IQ does not support these SAP Adaptive Server Enterprise views:

● sysalternates
● sysaudits

SAP IQ SQL Reference


Compatibility with Other SAP Database Products INTERNAL 191
● sysauditoptions
● sysconstraints
● syscharsets
● sysconfigures
● syscurconfigs
● sysdatabases
● sysdepends
● sysdevices
● sysengines
● syskeys
● syslanguages
● syslocks
● syslogs
● sysloginroles
● sysmessages
● sysprocedures
● sysprocesses
● sysprotects
● sysreferences
● sysremotelogins
● sysroles
● syssegments
● sysservers
● syssrvroles
● systhresholds
● sysusages

Column Name Differences

The column name used in the SAP ASE view SYSTYPES is “allownulls”. The column name used in the SAP IQ
view SYSTYPES is “allowsnulls”.

SAP IQ SQL Reference


192 INTERNAL Compatibility with Other SAP Database Products
6 SQL Functions

Functions return information from the database and are allowed anywhere an expression is allowed.

When using functions with SAP IQ, unless otherwise stated, any function that receives the NULL value as a
parameter returns a NULL value.

If you omit the FROM clause, or if all tables in the query are in the SYSTEM dbspace, SAP SQL Anywhere
processes the query, instead of SAP IQ, and might behave differently, especially with regard to syntactic and
semantic restrictions and the effects of option settings.

If you have a query that does not require a FROM clause, you can force SAP IQ to process the query by adding
the clause “FROM iq_dummy,” where iq_dummy is a one-row, one-column table that you create in your
database.

In this section:

Aggregate Functions [page 194]


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.

Analytical Functions [page 196]


Analytical functions include simple aggregates, window functions, and numeric functions.

Data Type Conversion Functions [page 202]


Data type conversion functions convert arguments from one data type to another.

Date and Time Functions [page 203]


Date and time functions perform conversion, extraction, or manipulation operations on date and time
data types and can return date and time information.

HTTP Functions [page 206]


HTTP functions facilitate the handling of HTTP requests within Web services.

Numeric Functions [page 207]


Numeric functions perform mathematical operations on numerical data types or return numeric
information.

String Functions [page 208]


String functions perform conversion, extraction, or manipulation operations on strings, or return
information about strings.

System Functions [page 210]


System functions return system information.

SQL and External Environment User-Defined Functions [page 253]


There are two mechanisms for creating user-defined functions in SAP IQ. You can use the SQL
language to write the function, or you can use the ESQL, ODBC, Java, Perl, or PHP external
environments.

Miscellaneous Functions [page 254]


Miscellaneous functions perform operations on arithmetic, string, or date/time expressions, including
the return values of other functions.

SAP IQ SQL Reference


SQL Functions INTERNAL 193
Alphabetical List of Functions [page 255]
This section describes each SQL function individually.

Related Information

Additional Functions [page 152]

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

Simple aggregate functions, such as SUM(), MIN(), MAX(), AVG() and COUNT() are allowed only in the select
list and in the HAVING and ORDER BY clauses of a SELECT statement. These functions summarize data over a
group of rows from the database. Groups are formed using the GROUP BY clause of the SELECT statement.

A class of aggregate functions, called window functions, provides moving averages and cumulative measures
that compute answers to queries such as, “What is the quarterly moving average of the Dow Jones Industrial
average?” or “List all employees and their cumulative salaries for each department.”

● Simple aggregate functions, such as AVG(), COUNT(), MAX(), MIN(), and SUM() summarize data over a
group of rows from the database. The groups are formed using the GROUP BY clause of the SELECT
statement.
● Newer statistical aggregate functions that take one argument include STDDEV(), STDDEV_SAMP(),
STDDEV_POP(), VARIANCE(), VAR_SAMP(), and VAR_POP().

Both the simple and newer categories of aggregates can be used as a windowing function that incorporates a
window clause in a SQL query specification (a window) that conceptually creates a moving window over a
result set as it is processed.

Another class of window aggregate functions supports analysis of time series data. Like the simple aggregate
and statistical aggregate functions, you can use these window aggregates with a SQL query specification (or
<window-spec>). The time series window aggregate functions calculate correlation, linear regression,
ranking, and weighted average results:

● ISO/ANSI SQL:2008 OLAP functions for time series analysis include: CORR(), COVAR_POP(),
COVAR_SAMP(), CUME_DIST(), FIRST_VALUE(), LAST_VALUE(), REGR_AVGX(), REGR_AVGY(),
REGR_COUNT(), REGR_INTERCEPT(), REGR_R2(), REGR_SLOPE(), REGR_SXX(), REGR_SXY(), and
REGR_SYY().
● Non-ISO/ANSI SQL:2008 OLAP aggregate function extensions used in the database industry include
FIRST_VALUE(), MEDIAN(), and LAST_VALUE().
● Weighted OLAP aggregate functions that calculate weighted moving averages include
EXP_WEIGHTED_AVG() and WEIGHTED_AVG().

Time series functions designed exclusively for financial time series forecasting and analysis have names
beginning with “TS_”.

SAP IQ SQL Reference


194 INTERNAL SQL Functions
For more information about OLAP, see OLAP in SAP IQ Administration: Database.

For information on aggregate function support of the LONG BINARY and LONG VARCHAR data types, see SAP
IQ Administration: Unstructured Data Analytics.

The aggregate functions AVG, SUM, STDDEV, and VARIANCE do not support the binary data types (BINARY and
VARBINARY).

Related Information

Analytical Functions [page 196]


Aggregate Functions [page 194]
AVG Function [Aggregate] [page 277]
CORR Function [Aggregate] [page 307]
COVAR_POP Function [Aggregate] [page 311]
COVAR_SAMP Function [Aggregate] [page 312]
COUNT Function [Aggregate] [page 314]
CUME_DIST Function [Analytical] [page 315]
EXP_WEIGHTED_AVG Function [Aggregate] [page 359]
FIRST_VALUE Function [Aggregate] [page 361]
LAST_VALUE Function [Aggregate] [page 399]
LIST Function [Aggregate] [page 413]
MAX Function [Aggregate] [page 420]
MEDIAN Function [Aggregate] [page 422]
MIN Function [Aggregate] [page 423]
REGR_AVGX Function [Aggregate] [page 472]
REGR_AVGY Function [Aggregate] [page 474]
REGR_COUNT Function [Aggregate] [page 476]
REGR_INTERCEPT Function [Aggregate] [page 477]
REGR_R2 Function [Aggregate] [page 479]
REGR_SLOPE Function [Aggregate] [page 480]
REGR_SXX Function [Aggregate] [page 482]
REGR_SXY Function [Aggregate] [page 484]
REGR_SYY Function [Aggregate] [page 485]
STDDEV Function [Aggregate] [page 524]
STDDEV_POP Function [Aggregate] [page 526]
STDDEV_SAMP Function [Aggregate] [page 527]
SUM Function [Aggregate] [page 540]
VAR_POP Function [Aggregate] [page 554]
VAR_SAMP Function [Aggregate] [page 556]
VARIANCE Function [Aggregate] [page 558]
WEIGHTED_AVG Function [Aggregate] [page 563]

SAP IQ SQL Reference


SQL Functions INTERNAL 195
6.2 Analytical Functions

Analytical functions include simple aggregates, window functions, and numeric functions.

● Simple aggregates – AVG, COUNT, MAX, MIN, and SUM, STDDEV, and VARIANCE

 Note

You can use all simple aggregates, except the Grouping() function, with an OLAP windowed function.

● Window functions:
○ Windowing aggregates – AVG, COUNT, MAX, MIN, and SUM.
○ Ranking functions – RANK, DENSE_RANK, PERCENT_RANK, ROW_NUMBER, and NTILE.
○ Statistical functions – STDDEV, STDDEV_SAMP, STDDEV_POP, VARIANCE, VAR_SAMP, and VAR_POP.
○ Distribution functions – PERCENTILE_CONT and PERCENTILE_DISC.
○ Interrow functions – LAG and LEAD.
● Numeric functions – WIDTH_BUCKET, CEIL, and LN, EXP, POWER, SQRT, and FLOOR.

 Note

The ranking and inverse distribution analytical functions are not supported by SAP Adaptive Server
Enterprise.

Unlike some aggregate functions, you cannot specify DISTINCT in window functions.

* The OLAP SQL standard allows Grouping() in GROUP BY CUBE, or GROUP BY ROLLUP operations only.

In this section:

Windowing Aggregate Function Usage [page 197]


A major feature of the ISO/ANSI SQL extensions for OLAP is a construct called a window.

Ranking Functions Usage [page 198]


The OLAP ranking functions let application developers compose single-statement SQL queries that
answer questions such as "Name the top 10 products shipped this year by total sales," or "Give the top
5% of salespeople who sold orders to at least 15 different companies."

Statistical Aggregate Analytic Function Usage [page 199]


Statistical aggregate analytic functions summarize data over a group of rows from the database.

Distribution Functions Usage [page 199]


The inverse distribution analytical functions PERCENTILE_CONT and PERCENTILE_DISC take a
percentile value as the function argument and operate on a group of data specified in the WITHIN
GROUP clause, or operate on the entire data set.

Interrow Functions Usage [page 200]


The interrow functions LAG and LEAD enable access to previous values or subsequent values in a data
series.

SAP IQ SQL Reference


196 INTERNAL SQL Functions
Related Information

Aggregate Functions [page 194]


AVG Function [Aggregate] [page 277]
COUNT Function [Aggregate] [page 314]
DENSE_RANK Function [Analytical] [page 344]
GROUPING Function [Aggregate] [page 367]
MAX Function [Aggregate] [page 420]
MIN Function [Aggregate] [page 423]
NTILE Function [Analytical] [page 440]
PERCENT_RANK Function [Analytical] [page 451]
PERCENTILE_CONT Function [Analytical] [page 453]
PERCENTILE_DISC Function [Analytical] [page 455]
RANK Function [Analytical] [page 469]
ROW_NUMBER Function [Analytical] [page 498]
STDDEV Function [Aggregate] [page 524]
STDDEV_POP Function [Aggregate] [page 526]
STDDEV_SAMP Function [Aggregate] [page 527]
SUM Function [Aggregate] [page 540]
VAR_POP Function [Aggregate] [page 554]
VAR_SAMP Function [Aggregate] [page 556]
VARIANCE Function [Aggregate] [page 558]

6.2.1 Windowing Aggregate Function Usage

A major feature of the ISO/ANSI SQL extensions for OLAP is a construct called a window.

This windowing extension let users divide result sets of a query (or a logical partition of a query) into groups of
rows called partitions and determine subsets of rows to aggregate with respect to the current row.

You can use three classes of window functions with a window: ranking functions, the row numbering function,
and window aggregate functions.

Windowing extensions specify a window function type over a window name or specification and are applied to
partitioned result sets within the scope of a single query expression.

Windowing operations let you establish information such as the ranking of each row within its partition, the
distribution of values in rows within a partition, and similar operations. Windowing also lets you compute
moving averages and sums on your data, enhancing the ability to evaluate your data and its impact on your
operations.

A window partition is a subset of rows returned by a query, as defined by one or more columns in a special
OVER() clause:

OVER (PARTITION BY <col1>, <col2>...)

SAP IQ SQL Reference


SQL Functions INTERNAL 197
For information on analytical function support of the LONG BINARY and LONG VARCHAR data types, see
Function Support in SAP IQ Administration: Unstructured Data Analytics.

Related Information

CORR Function [Aggregate] [page 307]


COUNT Function [Aggregate] [page 314]
EXP_WEIGHTED_AVG Function [Aggregate] [page 359]
FIRST_VALUE Function [Aggregate] [page 361]
GROUPING Function [Aggregate] [page 367]
LAST_VALUE Function [Aggregate] [page 399]
MAX Function [Aggregate] [page 420]
MEDIAN Function [Aggregate] [page 422]
MIN Function [Aggregate] [page 423]
REGR_AVGX Function [Aggregate] [page 472]
REGR_COUNT Function [Aggregate] [page 476]
REGR_INTERCEPT Function [Aggregate] [page 477]
REGR_R2 Function [Aggregate] [page 479]
REGR_SLOPE Function [Aggregate] [page 480]
REGR_SXX Function [Aggregate] [page 482]
REGR_SXY Function [Aggregate] [page 484]
REGR_SYY Function [Aggregate] [page 485]
STDDEV Function [Aggregate] [page 524]
STDDEV_POP Function [Aggregate] [page 526]
STDDEV_SAMP Function [Aggregate] [page 527]
SUM Function [Aggregate] [page 540]
VAR_POP Function [Aggregate] [page 554]
VAR_SAMP Function [Aggregate] [page 556]
VARIANCE Function [Aggregate] [page 558]
WEIGHTED_AVG Function [Aggregate] [page 563]

6.2.2 Ranking Functions Usage

The OLAP ranking functions let application developers compose single-statement SQL queries that answer
questions such as "Name the top 10 products shipped this year by total sales," or "Give the top 5% of
salespeople who sold orders to at least 15 different companies."

These functions include the ranking functions, RANK(), DENSE_RANK(), PERCENT_RANK(), ROW_NUMBER(),
and NTILE().

SAP IQ SQL Reference


198 INTERNAL SQL Functions
Rank analytical functions rank items in a group, compute distribution, and divide a result set into a number of
groupings. The rank analytical functions, RANK(), DENSE_RANK(), PERCENT_RANK(), ROW_NUMBER(), and
NTILE() all require an OVER (ORDER BY) clause. For example:

RANK() OVER ( [PARTITION BY] ORDER BY <expression>


[ ASC | DESC ] )

The ORDER BY clause specifies the parameter on which ranking is performed and the order in which the rows
are sorted in each group. This ORDER BY clause is used only within the OVER clause and is not an ORDER BY for
SELECT. No aggregation functions in the rank query ROW are allowed to specify DISTINCT.

 Note

The OVER (ORDER_BY) clause of the ROW_NUMBER() function cannot contain a ROWS or RANGE clause.

The OVER clause indicates that the function operates on a query result set. The result set is the rows that are
returned after the FROM, WHERE, GROUP BY, and HAVING clauses have all been evaluated. The OVER clause
defines the data set of the rows to include in the computation of the rank analytical function.

The value <expression> is a sort specification that can be any valid expression involving a column reference,
aggregates, or expressions invoking these items.

The ASC or DESC parameter specifies the ordering sequence as ascending or descending. Ascending order is
the default.

Rank analytical functions are only allowed in the select list of a SELECT or INSERT statement or in the ORDER
BY clause of the SELECT statement. Rank functions can be in a view or a union. You cannot use rank functions
in a subquery, a HAVING clause, or in the select list of an UPDATE or DELETE statement. More than one rank
analytical function is allowed per query in SAP IQ 16.1.

6.2.3 Statistical Aggregate Analytic Function Usage

Statistical aggregate analytic 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. These functions include
STDDEV, STDDEV_POP, STDDEV_SAMP, VARIANCE, VAR_POP, and VAR_SAMP.

The OLAP functions can be used as a window function with an OVER() clause in a SQL query specification that
conceptually creates a moving window over a result set as it is processed.

6.2.4 Distribution Functions Usage

The inverse distribution analytical functions PERCENTILE_CONT and PERCENTILE_DISC take a percentile
value as the function argument and operate on a group of data specified in the WITHIN GROUP clause, or
operate on the entire data set.

These functions return one value per group. For PERCENTILE_DISC, the data type of the results is the same as
the data type of its ORDER BY item specified in the WITHIN GROUP clause. For PERCENTILE_CONT, the data

SAP IQ SQL Reference


SQL Functions INTERNAL 199
type of the results is either numeric, if the ORDER BY item in the WITHIN GROUP clause is a numeric, or double,
if the ORDER BY item is an integer or floating-point.

The inverse distribution analytical functions require a WITHIN GROUP (ORDER BY) clause. For example:

PERCENTILE_CONT ( <expression1> ) WITHIN GROUP ( ORDER BY <expression2> [ASC |


DESC ] )

The value of <expression1> must be a constant of numeric data type and range from 0 to 1 (inclusive). If the
argument is NULL, then a "wrong argument for percentile" error is returned. If the argument value is less than
0, or greater than 1, then a "data value out of range" error is returned.

The ORDER BY clause, which must be present, specifies the expression on which the percentile function is
performed and the order in which the rows are sorted in each group. This ORDER BY clause is used only within
the WITHIN GROUP clause and is not an ORDER BY for the SELECT.

The WITHIN GROUP clause distributes the query result into an ordered data set from which the function
calculates a result.

The value <expression2> is a sort specification that must be a single expression involving a column
reference. Multiple expressions are not allowed and no rank analytical functions, set functions, or subqueries
are allowed in this sort expression.

The ASC or DESC parameter specifies the ordering sequence as ascending or descending. Ascending order is
the default.

Inverse distribution analytical functions are allowed in a subquery, a HAVING clause, a view, or a union. The
inverse distribution functions can be used anywhere the simple non analytical aggregate functions are used.
The inverse distribution functions ignore the NULL value in the data set.

6.2.5 Interrow Functions Usage

The interrow functions LAG and LEAD enable access to previous values or subsequent values in a data series.

These functions provide access to more than one row of a table or partition simultaneously without a self join.
The LAG function provides access to a row at a given physical offset prior to the CURRENT ROW in the table or
partition. The LEAD function provides access to a row at a given physical offset after the CURRENT ROW in the
table or partition. Use the LAG and LEAD functions to create queries such as, "What was the stock price two
intervals before the current row?" and "What was the stock price one interval after the current row?"

Interrow functions require an OVER (ORDER_BY) clause.

In this section:

Interrow Functions [page 201]


The interrow functions, LAG and LEAD, provide access to previous or subsequent values in a data
series, or to multiple rows in a table.

SAP IQ SQL Reference


200 INTERNAL SQL Functions
6.2.5.1 Interrow Functions
The interrow functions, LAG and LEAD, provide access to previous or subsequent values in a data series, or to
multiple rows in a table.

Interrow functions also partition simultaneously without a self-join. LAG provides access to a row at a given
physical offset prior to the CURRENT ROW in the table or partition. LEAD provides access to a row at a given
physical offset after the CURRENT ROW in the table or partition.

LAG and LEAD syntax is identical. Both functions require an OVER (ORDER_BY) window specification.

● LAG syntax:

LAG (<value_expr>) [, <offset> [, <default>]])


OVER ([PARTITION BY <window partition>] ORDER BY <window ordering>)

● LEAD syntax:

LEAD (<value_expr>) [, <offset> [, <default>]])


OVER ([PARTITION BY <window partition>] ORDER BY <window ordering>)

The PARTITION BY clause in the OVER (ORDER_BY) clause is optional. The OVER (ORDER_BY) clause cannot
contain a window frame ROWS/RANGE specification.

<value_expr >is a table column or expression that defines the offset data to return from the table. You can
define other functions in the <value_expr>, with the exception of analytic functions.

For both functions, specify the target row by entering a physical offset. The <offset >value is the number of
rows above or below the current row. Enter a non-negative numeric data type (entering a negative value
generates an error). If you enter 0, SAP IQ returns the current row.

The optional <default> value defines the value to return if the <offset >value goes beyond the scope of the
table. The default value of <default> is NULL. The data type of <default> must be implicitly convertible to
the data type of the <value_expr> value, or SAP IQ generates a conversion error.

The inter-row functions are useful in financial services applications that perform calculations on data streams,
such as stock transactions. The following example uses the LAG function to calculate the percentage change in
the trading price of a particular stock. Consider the following trading data from a fictional table called
stock_trades:

traded at symbol price


------------------- ------ ------
2009-07-13 06:07:12 SQL 15.84
2009-07-13 06:07:13 TST 5.75
2009-07-13 06:07:14 TST 5.80
2009-07-13 06:07:15 SQL 15.86
2009-07-13 06:07:16 TST 5.90
2009-07-13 06:07:17 SQL 15.86

 Note

The fictional stock_trades table is not available in the iqdemo database.

The query partitions the trades by stock symbol, orders them by time of trade, and uses the LAG function to
calculate the percentage increase or decrease in trade price between the current trade and the previous trade:

select stock_symbol as 'Stock',

SAP IQ SQL Reference


SQL Functions INTERNAL 201
traded_at as 'Date/Time of Trade',
trade_price as 'Price/Share',
cast ( ( ( (trade_price
- (lag(trade_price, 1)
over (partition by stock_symbol
order by traded_at)))
/ trade_price)
* 100.0) as numeric(5, 2) )
as '% Price Change vs Previous Price'
from stock_trades
order by 1, 2

The query returns these results:

Stock Date/Time of Trade Price/ % Price Change_vs


symbol Share Previous Price
------ ------------------- ----- -----------------
SQL 2009-07-13 06:07:12 15.84 NULL
SQL 2009-07-13 06:07:15 15.86 0.13
SQL 2009-07-13 06:07:17 15.86 0.00
TST 2009-07-13 06:07:13 5.75 NULL
TST 2009-07-13 06:07:14 5.80 0.87
TST 2009-07-13 06:07:16 5.90 1.72

The NULL result in the first and fourth output rows indicates that the LAG function is out of scope for the first
row in each of the two partitions. Since there is no previous row to compare to, SAP IQ returns NULL as
specified by the <default> variable.

6.3 Data Type Conversion Functions

Data type conversion functions convert arguments from one data type to another.

The database server carries out many data type conversions automatically. For example, if a string is supplied
where a numerical expression is required, the string is automatically converted to a number.

Related Information

Data Type Conversions [page 143]


Storage Size [page 126]
BIGINTTOHEX Function [Data Type Conversion] [page 280]
CAST Function [Data Type Conversion] [page 288]
CONVERT Function [Data Type Conversion] [page 303]
HEXTOBIGINT Function [Data Type Conversion] [page 369]
HEXTOINT Function [Data Type Conversion] [page 370]
INTTOHEX Function [Data Type Conversion] [page 391]
ISNUMERIC Function [Miscellaneous] [page 396]

SAP IQ SQL Reference


202 INTERNAL SQL Functions
6.4 Date and Time Functions

Date and time functions perform conversion, extraction, or manipulation operations on date and time data
types and can return date and time information.

The date and time functions allow manipulation of time units. Most time units (such as MONTH) have four
functions for time manipulation, although only two names are used (such as MONTH and MONTHS).

These functions are Transact-SQL date and time functions. They allow an alternative way of accessing and
manipulating date and time functions:

● DATEADD
● DATEDIFF
● DATENAME
● DATEPART
● GETDATE

You should convert arguments to date functions to dates before using them. For example:

● Incorrect: days ( '1995-11-17', 2 )


● Correct: days ( date( '1995-11-17' ), 2 )

SAP IQ does not have the same constants or data type promotions as SAP SQL Anywhere, with which it shares
a common user interface. If you issue a SELECT statement without a FROM clause, the statement is passed to
SAP SQL Anywhere. The following statement is handled exclusively by SAP SQL Anywhere:

SELECT WEEKS('1998/11/01');

The following statement, processed by SAP IQ, uses a different starting point for the WEEKS function and
returns a different result than the statement above:

SELECT WEEKS('1998/11/01') FROM iq_dummy;

Consider another example. The MONTHS function returns the number of months since an “arbitrary starting
date.” The “arbitrary starting date” of SAP IQ, the imaginary date 0000-01-01, is chosen to produce the most
efficient date calculations and is consistent across various data parts. SAP SQL Anywhere does not have a
single starting date. The following statements, the first processed by SAP SQL Anywhere, the second by SAP
IQ, both return the answer 12:

SELECT MONTHS('0001/01/01');

SELECT MONTHS('0001/01/01') FROM iq_dummy;

However, also consider these statements:

SELECT DAYS('0001/01/01');

SELECT DAYS('0001/01/01') FROM iq_dummy;

The first, processed by SAP SQL Anywhere, yields the value 307, but the second, processed by SAP IQ, yields
166.

SAP IQ SQL Reference


SQL Functions INTERNAL 203
For the most consistent results, therefore, always include the table name in the FROM clause whether you need
it or not.

 Note

Create a dummy table with only one column and row. You can then reference this table in the FROM clause
for any SELECT statement that uses date or time functions, thus ensuring processing by SAP IQ, and
consistent results.

In this section:

Date Parts [page 205]


Many of the date functions use dates built from date parts.

Related Information

ISDATE Function [Date and Time] [page 393]


DATE Function [Date and Time] [page 318]
DATEADD Function [Date and Time] [page 319]
DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATEFORMAT Function [Date and Time] [page 328]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
DATETIME Function [Date and Time] [page 335]
DAY Function [Date and Time] [page 336]
DAYNAME Function [Date and Time] [page 337]
DAYS Function [Date and Time] [page 338]
DOW Function [Date and Time] [page 348]
GETDATE Function [Date and Time] [page 364]
HOUR Function [Date and Time] [page 372]
HOURS Function [Date and Time] [page 373]
ISDATE Function [Date and Time] [page 393]
MINUTE Function [Date and Time] [page 425]
MINUTES Function [Date and Time] [page 425]
MONTH Function [Date and Time] [page 428]
MONTHNAME Function [Date and Time] [page 429]
MONTHS Function [Date and Time] [page 430]
NOW Function [Date and Time] [page 439]
QUARTER Function [Date and Time] [page 465]
QUARTERSTR Function [Date and Time] [page 466]
SECOND Function [Date and Time] [page 503]

SAP IQ SQL Reference


204 INTERNAL SQL Functions
SECONDS Function [Date and Time] [page 505]
TODAY Function [Date and time] [page 545]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]
YMD Function [Date and Time] [page 570]

6.4.1 Date Parts

Many of the date functions use dates built from date parts.

This table displays allowed values of <date-part>.

Date Part Abbreviation Values

Year yy 0001 – 9999

Quarter qq 1–4

Month mm 1 – 12

Week wk 1 – 54

Day dd 1 – 31

Dayofyear dy 1 – 366

Weekday dw 1 – 7 (Sun. – Sat.)

Hour hh 0 – 23

Minute mi 0 – 59

Second ss 0 – 59

Millisecond ms 0 – 999

Microsecond mcs or us 0 – 999999

Calyearofweek cyr Integer. The year in which the week begins. The week containing
the first few days of the year can be part of the last week of the pre­
vious year, depending upon which day it begins. If the new year
starts on a Thursday through Saturday, its first week starts on the
last Sunday of the previous year. If the new year starts on a Sunday
through Wednesday, none of its days are part of the previous year.

Calweekofyear cwk An integer from 1 to 54 representing the week number within the
year that contains the specified date.

Caldayofweek cdw The day number within the week (Sunday = 1, Saturday = 7).

 Note

By default, Sunday is the first day of the week. To make Monday the first day, use:

set option 'Date_First_Day_Of_Week' = '1'

SAP IQ SQL Reference


SQL Functions INTERNAL 205
Compatibility

For compatibility with SAP Adaptive Server Enterprise, use the Transact-SQL date and time functions.

Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]

6.5 HTTP Functions

HTTP functions facilitate the handling of HTTP requests within Web services.

 Note

Ensure your Web services use best coding practices to safeguard against cross-site scripting (XSS) attacks.
Open-source resources are available at organizations such as OWASP .

Related Information

HTML_DECODE function [Miscellaneous] [page 375]


HTML_ENCODE function [Miscellaneous] [page 376]
HTML_PLAN Function [String] [page 378]
HTTP_DECODE function [Web service] [page 379]
HTTP_ENCODE function [Web service] [page 380]
HTTP_HEADER function [Web service] [page 382]
HTTP_VARIABLE function [Web service] [page 386]
HTML_PLAN Function [String] [page 378]

SAP IQ SQL Reference


206 INTERNAL SQL Functions
6.6 Numeric Functions
Numeric functions perform mathematical operations on numerical data types or return numeric information.

SAP IQ does not have the same constants or data type promotions as SAP SQL Anywhere, with which it shares
a common user interface. If you issue a SELECT statement without a FROM clause, the statement is passed
through to SAP SQL Anywhere. For the most consistent results, include the table name in the FROM clause
whether you need it or not.

 Note

Consider creating a dummy table to use in such cases.

Related Information

ABS Function [Numeric] [page 266]


ACOS Function [Numeric] [page 267]
ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
CEIL Function [Numeric] [page 290]
CEILING Function [Numeric] [page 291]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
DEGREES Function [Numeric] [page 344]
EXP Function [Numeric] [page 358]
FLOOR Function [Numeric] [page 363]
LN Function [Numeric] [page 408]
LOG Function [Numeric] [page 412]
LOG10 Function [Numeric] [page 416]
MOD Function [Numeric] [page 427]
PI Function [Numeric] [page 457]
POWER Function [Numeric] [page 458]
RADIANS Function [Numeric] [page 467]
RAND Function [Numeric] [page 468]
REMAINDER Function [Numeric] [page 487]
ROUND Function [Numeric] [page 496]
SIGN Function [Numeric] [page 506]
SIN Function [Numeric] [page 508]
SQRT Function [Numeric] [page 520]
SQUARE Function [Numeric] [page 521]
TAN Function [Numeric] [page 544]
TRUNCNUM Function [Numeric] [page 547]

SAP IQ SQL Reference


SQL Functions INTERNAL 207
WIDTH_BUCKET Function [Numerical] [page 565]

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

Most of the string functions accept binary data (hexadecimal strings) in the <string-expr> parameter, but
some of the functions, such as LCASE, UCASE, LOWER, and LTRIM, expect the string expression to be a
character string.

Unless you supply a constant LENGTH argument to a function that produces a LONG VARCHAR result (such as
SPACE or REPEAT), the default length is the maximum allowed.

SAP IQ queries containing one or more of these functions might return one of the following errors:
ASA Error -1009080: Key doesn't fit on a single database page: 65560(4, 1)
ASA Error -1009119: Record size too large for database page size

For example:

SELECT COUNT(*) FROM test1 a WHERE (a.col1 + SPACE(4-LENGTH(a.col1))


+ a.col2 + space(2- LENGTH(a.col2))) IN (SELECT (b.col3) FROM test1 b);

To avoid such errors, cast the function result with an appropriate maximum length; for example:

SELECT COUNT(*) FROM test1 a WHERE (a.col1 + CAST(SPACE(4-LENGTH(a.col1))


AS VARCHAR(4)) + a.col2 + CAST(SPACE(2-LENGTH (a.col2)) AS VARCHAR(4)))
IN (SELECT (b.col3) FROM test1 b);

The errors are more likely with a page size of 64K or a multibyte collation.

 Note

For information on string functions that support the LONG BINARY and LONG VARCHAR data types, see
Function Support in SAP IQ Administration: Unstructured Data Analytics.

Related Information

ASCII Function [String] [page 272]


BIT_LENGTH Function [String] [page 281]
BYTE_LENGTH Function [String] [page 283]
CHAR function [String] [page 292]
CHAR_LENGTH Function [String] [page 293]
CHARINDEX Function [String] [page 296]

SAP IQ SQL Reference


208 INTERNAL SQL Functions
DIFFERENCE Function [String] [page 346]
GRAPHICAL_PLAN Function [String] [page 365]
HTML_PLAN Function [String] [page 378]
INSERTSTR Function [String] [page 390]
LCASE Function [String] [page 401]
LEFT Function [String] [page 404]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
LOCATE Function [String] [page 409]
LOWER Function [String] [page 417]
LTRIM Function [String] [page 419]
PATINDEX Function [String] [page 448]
REPEAT Function [String] [page 488]
REPLACE Function [String] [page 489]
REPLICATE Function [String] [page 492]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
RTRIM Function [String] [page 502]
SIMILAR Function [String] [page 507]
SORTKEY Function [String] [page 509]
SOUNDEX Function [String] [page 514]
SPACE Function [String] [page 517]
STR Function [String] [page 529]
STR_REPLACE Function [String] [page 530]
STRING Function [String] [page 532]
STRTOUUID Function [String] [page 533]
STUFF Function [String] [page 535]
SUBSTRING Function [String] [page 536]
SUBSTRING64 Function [String] [page 539]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]
UUIDTOSTR Function [String] [page 553]

SAP IQ SQL Reference


SQL Functions INTERNAL 209
6.8 System Functions

System functions return system information.

Description

Databases currently running on a server are identified by a database name and a database ID number. The
db_id and db_name functions provide information on these values.

A set of system functions provides information about properties of a currently running database, or of a
connection, on the database server. These system functions take the database name or ID, or the connection
name, as an optional argument to identify the database or connection for which the property is requested.

Performance

System functions are processed differently than other SAP IQ functions. When queries to SAP IQ tables include
system functions, performance is reduced.

In this section:

SAP ASE System Function Compatibility [page 211]


Not all SAP Adaptive Server Enterprise system functions are implemented in SAP IQ.

Connection Properties [page 212]


Retrieve the value of a specific connection property or the values of all connection properties.

Properties Available for the Server [page 213]


Retrieve the value of a specific server property or the values of all server properties.

Properties Available for Each Database [page 236]


You can retrieve the value of a specific database property or the values of all database properties.
Database properties apply to an entire database.

Related Information

CEIL Function [Numeric] [page 290]


COL_LENGTH Function [System] [page 299]
COL_NAME Function [System] [page 300]
CONNECTION_PROPERTY Function [System] [page 302]
DATALENGTH Function [System] [page 316]
DB_ID Function [System] [page 339]
DB_NAME Function [System] [page 341]

SAP IQ SQL Reference


210 INTERNAL SQL Functions
DB_PROPERTY Function [System] [page 342]
EVENT_CONDITION Function [System] [page 354]
EVENT_CONDITION_NAME Function [System] [page 356]
EVENT_PARAMETER Function [System] [page 357]
GROUP_MEMBER Function [System] [page 368]
INDEX_COL Function [System] [page 389]
NEXT_CONNECTION Function [System] [page 433]
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]
PROPERTY Function [System] [page 459]
PROPERTY_DESCRIPTION Function [System] [page 460]
PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]
SUSER_ID Function [System] [page 542]
SUSER_NAME Function [System] [page 543]
USER_ID Function [System] [page 551]
USER_NAME Function [System] [page 552]

6.8.1 SAP ASE System Function Compatibility

Not all SAP Adaptive Server Enterprise system functions are implemented in SAP IQ.

Some of the system functions are implemented in SAP IQ as system stored procedures.

Function Status

col_length Implemented.

col_name Implemented.

db_id Implemented – the db_id function is implemented as a built-in function.

db_name Implemented – the db_name function is implemented as a built-in function.

index_col Implemented.

object_id Implemented.

object_name Implemented.

proc_role Always returns 0.

show_role Always returns NULL.

tsequal Not implemented.

user_id Implemented.

user_name Implemented.

suser_id Implemented – the suser_id function is implemented as a built-in function.

SAP IQ SQL Reference


SQL Functions INTERNAL 211
Function Status

suser_name Implemented – the suser_name function is implemented as a built-in function.

datalength Implemented.

curunreservedpgs Not implemented.

data_pgs Not implemented.

host_id Not implemented.

host_name Not implemented.

lct_admin Not implemented.

reserved_pgs Not implemented.

rowcnt Not implemented.

used_pgs Not implemented.

valid_name Not implemented

valid_user Not implemented.

6.8.2 Connection Properties

Retrieve the value of a specific connection property or the values of all connection properties.

Use the following to retrieve connection property information:

connection_property system function

Retrieves the value of a connection property. The following statement returns the number of pages that
have been read from file by the current connection:

select connection_property ( 'DiskRead' )

sa_conn_properties system procedure

Retrieves the values of all connection properties. The following statement returns separate row appears for
each connection, for each property:

call sa_conn_properties

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


PROPERTY Function [System] [page 459]
PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]

SAP IQ SQL Reference


212 INTERNAL SQL Functions
6.8.3 Properties Available for the Server

Retrieve the value of a specific server property or the values of all server properties.

Server properties apply across the server as a whole.

The Server Edition property returns the SAP SQL Anywhere edition, not the SAP IQ edition. To show SAP SQL
Anywhere license information, use the sp_iqlmconfig system procedure.

Use the following to retrieve the value of a server property:

property system function

Retrieves the value of a server property. The following statement returns the number of cache pages being
used to hold the main heap:

select property ( 'MainHeapPages') from iq_dummy

sa_eng_properties system procedure

Retrieves the values of all server properties:

call sa_eng_properties

In this section:

Database server property tracking [page 214]


The database server can store the values of numeric database server properties so that you can track
the changes of numeric database server properties over time.

List of connection properties [page 216]


Connection properties are available for each connection to a database. Connection property names are
case insensitive. Use the CONNECTION_PROPERTY system function or the sa_conn_properties system
procedure to retrieve connection properties.

Related Information

sp_iqlmconfig Procedure [page 689]


CONNECTION_PROPERTY Function [System] [page 302]
PROPERTY Function [System] [page 459]
PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]

SAP IQ SQL Reference


SQL Functions INTERNAL 213
6.8.3.1 Database server property tracking

The database server can store the values of numeric database server properties so that you can track the
changes of numeric database server properties over time.

Tracking database server property values over time aids in evaluating the overall health of a database server.
For example, a brief increase in CPU usage may not be an issue, but if the CPU usage is at 100 percent for an
extended period of time, it could indicate that the hardware is insufficient.

Rather than having to poll, analyze, and store database server property values at regular intervals, configure
the database server to track database server properties that return numeric values. These values are stored in
memory for a period of time so that polling can be done at larger intervals, reducing the load on the database
server.

When database server property tracking is enabled, property values are tracked at fixed intervals and you can
query historic property values by using the sp_property_history system procedure.

In this section:

Viewing all trackable database server property values [page 214]


View the list of database server property values that can be tracked.

Configuring database server property tracking [page 215]


Configure your database server to track the values of numeric database server properties.

6.8.3.1.1 Viewing all trackable database server property


values

View the list of database server property values that can be tracked.

Context

Only database server properties with numeric values can be tracked.

You can find the PropNum of the database server property by running the sa_eng_properties system procedure
or by calling the PROPERTY_NUMBER function.

Procedure

Execute the following statement:

SELECT * FROM sa_eng_properties()


WHERE PROPERTY_IS_TRACKABLE( PropNum ) = 1;

SAP IQ SQL Reference


214 INTERNAL SQL Functions
Results

The list of database server properties that can be tracked is returned.

Related Information

sa_eng_properties system procedure [page 852]


PROPERTY_NUMBER Function [System] [page 463]

6.8.3.1.2 Configuring database server property tracking

Configure your database server to track the values of numeric database server properties.

Context

Only database server properties with numeric values can be tracked.

Procedure

Choose one or both of the following options:

Option Action

Specify ○ When starting the database server, use the -phl and -phs database server options to turn on history track­
data­
ing for a list of specified database server properties and to specify the maximum amount of memory to use
base
server for tracking property history. For example, run the following command:
proper­ start_iq -n myserver -phl ProcessCPUSystem, ProcessCPUUser -phs 250K
ties to ○ If the database server is already running, then use the sa_server_option system procedure to configure
be
property tracking for the database server. For example, execute the following statement:
tracked
for the CALL
data­ sa_server_option( 'PropertyHistoryList,ProcessCPUSystem,ProcessCPUUser,P
base ropertyHistorySize,250K' );
server

Specify
Use the sa_db_option system procedure to configure property tracking of database server properties for the da­
data­
base tabase. For example, execute the following statement:
server CALL sa_db_option( 'PropertyHistoryList,ProcessCPUSystem,ProcessCPUUser' );
proper­
ties to
be

SAP IQ SQL Reference


SQL Functions INTERNAL 215
Option Action

tracked
for the
data­
base

Results

The values of the specified database server properties are tracked for either the specified amount of time or
until the specified maximum amount of memory has been reached.

6.8.3.2 List of connection properties

Connection properties are available for each connection to a database. Connection property names are case
insensitive. Use the CONNECTION_PROPERTY system function or the sa_conn_properties system procedure
to retrieve connection properties.

 Example

The following statement returns the number of pages that have been read from file by the current
connection.

SELECT CONNECTION_PROPERTY ( 'DiskRead' );

Use the sa_conn_properties system procedure to retrieve the values of all connection properties:

CALL sa_conn_properties( );

Connection properties

Property name Description

allow_nulls_by_default Whether columns created without specifying either NULL or NOT NULL are allowed to contain
NULL values. This property corresponds to the allow_nulls_by_default option for the connection.

allow_read_client_file Whether the database server allows the reading of files on a client computer. This property cor­
responds to the allow_read_client_file option for the connection.

allow_snapshot_isola­ Whether snapshot isolation is enabled or disabled. This property corresponds to the allow_snap­
tion shot_isolation option for the connection.

SAP IQ SQL Reference


216 INTERNAL SQL Functions
Property name Description

allow_write_client_file Whether the database server allows the writing of files to a client computer. This property corre­
sponds to the allow_write_client_file option for the connection.

ansi_blanks Indicates when character data is truncated at the client side. This property corresponds to
ansi_blanks option for the connection.

ansi_close_cur­ Whether cursors opened WITH HOLD are closed when a ROLLBACK is performed. This property
sors_on_rollback corresponds to the ansi_close_cursors_on_rollback option for the connection.

ansi_permissions Whether privileges are checked for DELETE and UPDATE statements. This property corresponds
to the ansi_permissions option for the connection.

ansi_substring The behavior of the SUBSTRING (SUBSTR) function when negative values are provided for the
start or length parameters. This property corresponds to the ansi_substring option for the con­
nection.

ansi_update_constraints The range of updates that are permitted. This property corresponds to the ansi_update_con­
straints option for the connection.

ansinull How NULL values are interpreted. This property corresponds to the ansinull option.

AppInfo Information about the client that made the connection. For HTTP connections, this includes in­
formation about the browser. For connections using older versions of SAP Open Client or jCon­
nect, the information may be incomplete.

ApproximateCPUTime The estimate of the amount of CPU time accumulated by a given connection, in seconds. The
value returned may differ from the actual value by as much as 50%, although typical variations
are in the 5-10% range. On multi-processor computers, each CPU (or hyperthread or core) accu­
mulates time, so the sum of accumulated times for all connections may be greater than the
elapsed time.

audit_log The location where audit logs are directed.

auditing Whether auditing is enabled for the database(On) or not (Off). This option corresponds to the
auditing option.

auditing_options This property is reserved for system use.

Authenticated Whether the application sent a valid connection authentication string (Yes) or not (No).

AuthType The type of authentication used when connecting. The value returned is one of Standard, Inte­
grated, Kerberos, LDAPUA, or an empty string. The value is an empty string when the connection
is an internal connection or for connections for HTTP services that use AUTHORIZATION OFF.

auto_commit Whether the database server automatically commits after each statement. By default, the data­
base server operates in manual commit mode. To turn on automatic commits, set the auto_com­
mit database option (a server-side option). Do not confuse this option with the Interactive SQL
option of the same name.

SAP IQ SQL Reference


SQL Functions INTERNAL 217
Property name Description

auto_commit_on_cre­ Whether the database server performs a COMMIT before an index is created on a local tempo­
ate_local_temp_index rary table. This property corresponds to the value of the auto_commit_on_create_lo­
cal_temp_index option.

background_priority This property is deprecated. The value of the background_priority option for the connection,
which indicates how much impact the current connection has on the performance of other con­
nections.

BlockedOn Whether the current connection is blocked or not (zero). When the connection is blocked be­
cause of a locking conflict, the value is the connection number on which the connection is
blocked.

blocking The database server's behavior in response to locking conflicts. This property corresponds to
the blocking option for the connection.

blocking_others_time­ The length of time that another connection can block on the current connection's row and table
out locks before the current connection is rolled back. This property corresponds to the value of the
blocking_others_timeout option.

blocking_timeout The length of time, in milliseconds, a transaction waits to obtain a lock. This property corre­
sponds to the blocking_timeout option.

BytesReceived The number of bytes received during client/server communications. This value is updated for
HTTP and HTTPS connections.

BytesReceivedUncomp The number of bytes that would have been received during client/server communications if
compression was disabled. This value is the same as the value for BytesReceived if compression
is disabled.

BytesSent The number of bytes sent during client/server communications. This value is updated for HTTP
and HTTPS connections.

BytesSentUncomp The number of bytes that would have been sent during client/server communications if com­
pression was disabled. This value is the same as the value for BytesSent if compression is disa­
bled.

CacheHits The number of successful reads of the cache.

CacheRead The number of database pages that have been looked up in the cache.

CacheReadIndInt The number of index internal-node pages that have been read from the cache.

CacheReadIndLeaf The number of index leaf pages that have been read from the cache.

CacheReadTable The number of table pages that have been read from the cache.

CacheReadWorkTable The number of cache work table reads.

CarverHeapPages The number of heap pages used for short-term purposes such as query optimization.

SAP IQ SQL Reference


218 INTERNAL SQL Functions
Property name Description

chained The value of the chained option, which indicates the transaction mode used in the absence of a
BEGIN TRANSACTION statement.

CharSet The CHAR character set used by the connection. This property has extensions that you can
specify when querying the property value.

checkpoint_time The value of the checkpoint_time option, which indicates the maximum time, in minutes, that
the database server runs without doing a checkpoint.

cis_option Specifies 7 if debugging information for remote data access appears in the database server mes­
sages window. Specifies 0 if the debugging information for remote data access does not appear
in the database server messages window. This property corresponds to the cis_option option.

cis_rowset_size The number of rows that are returned from remote servers for each fetch. This property corre­
sponds to the value of the cis_rowset_size option.

ClientLibrary The connection library type. The value is jConnect for jConnect connections; CT_Library for SAP
Open Client connections; None for HTTP connections, and CmdSeq for ODBC, Embedded SQL,
OLE DB, ADO.NET, and SQL Anywhere JDBC driver connections.

ClientNodeAddress The node for the client in a client/server connection. When the client and server are both on the
same computer, an empty string is returned. This property is a synonym for the NodeAddress
property.

The value is NA if the request that is currently executing is part of an event handler.

ClientPort The client's TCP/IP port number or 0 if the connection isn't a TCP/IP connection.

ClientStmtCacheHits The number of prepares that were not required for this connection because of the client state­
ment cache. This value is the number of additional prepares that would be required if client
statement caching was disabled.

ClientStmtCacheMisses The number of statements in the client statement cache for this connection that were prepared
again. This value is the number of times a cached statement was considered for reuse, but could
not be reused because of a schema change, a database option setting, or a DROP VARIABLE
statement.

close_on_endtrans Whether cursors are closed at the end of a transaction. This property corresponds to the
close_on_endtrans option.

collect_statis­ Whether statistics are gathered during the execution of data-altering DML statements such as
tics_on_dml_updates INSERT, DELETE, and UPDATE. This property corresponds to the collect_statistics_on_dml_up­
dates option.

Commit The number of Commit requests that have been handled.

CommLink The communication link for the connection. The value is one of the supported network protocols
supported, or local for a same-computer connection. The value is NA if the request that is cur­
rently executing is part of an event handler.

SAP IQ SQL Reference


SQL Functions INTERNAL 219
Property name Description

CommNetworkLink The communication link for the connection. This value returned is one of the supported network
protocols. Values include SharedMemory and TCPIP. The value always includes the name of the
link, regardless of whether it is same-computer or not. The value is NA if the request that is cur­
rently executing is part of an event handler.

CommProtocol The communication protocol. The value is TDS for SAP Open Client and jConnect connections,
HTTP for HTTP connections, HTTPS for HTTPS connections. The value is CmdSeq for ODBC,
Embedded SQL, OLE DB, ADO.NET, and SQL Anywhere JDBC driver connections.

Compression Whether communication compression is enabled on the connection. The value is NA if the re­
quest that is currently executing is part of an event handler.

conn_auditing Whether auditing is enabled or disabled for the connection when the auditing option is also set
to On. This property corresponds to the conn_auditing option.

ConnectedTime The total length of time, in seconds, that a connection has been connected.

connection_authentica­ The string used to authenticate the client. Authentication is required before the database can be
tion modified. This property corresponds to the connection_authentication option.

connection_type The value of the connection_type database option: one of: Event, Internal, Standard, or Monitor

continue_after_raiserror Whether execution of a procedure or trigger is stopped whenever the RAISERROR statement is
encountered. This property corresponds to the continue_after_raiserror option

conversion_error Whether data type conversion failures are reported when fetching information from the data­
base This property corresponds to the value of the conversion_error option.

cooperative_com­ This property is deprecated. The value of the cooperative_commit_timeout option, which is the
mit_timeout time, in milliseconds, that the database server waits for other connections to fill a page of the log
before writing to disk.

cooperative_commits This property is deprecated. The value of the cooperative_commits option, which is On or Off to
indicate when commits are written to disk.

CurrentLineNumber The current line number of the procedure or compound statement a connection is executing.
The procedure can be identified using the CurrentProcedure property. If the line is part of a com­
pound statement from the client, an empty string is returned.

CurrentProcedure The name of the procedure that a connection is currently executing. If the connection is execut­
ing nested procedure calls, the name is the name of the current procedure. If there is no proce­
dure executing, an empty string is returned.

Cursor The number of declared cursors that are currently being maintained by the database server.

CursorOpen The number of open cursors that are currently being maintained by the database server.

SAP IQ SQL Reference


220 INTERNAL SQL Functions
Property name Description

database_authentication Indicates the string used to authenticate the database. Authentication is required for authenti­
cated database servers before the database can be modified. This property corresponds to the
database_authentication option

date_format The value of the date_format option, which is a string indicating the format for dates retrieved
from the database.

date_order The value of the date_order option, which is a string indicating how dates are formatted.

DBNumber The ID number of the database.

db_publisher The user ID of the database publisher. This property corresponds to the db_publisher option.

debug_messages Whether MESSAGE statements that include a DEBUG ONLY clause are executed. This property
corresponds to the debug_messages option

dedicated_task Whether a request handling task is dedicated exclusively to handling requests for the connec­
tion. This property corresponds to the dedicated_task option

default_dbspace The name of the default dbspace, or an empty string if the default dbspace has not been speci­
fied. This property corresponds to the default_dbspace option,

default_timestamp_in­ The number of microseconds that is added to a column of type TIMESTAMP to keep values in
crement the column unique. This property corresponds to the default_timestamp_increment.

delayed_commit_time­ The time, in milliseconds, that the database server waits to return control to an application fol­
out lowing a COMMIT. This property corresponds to the delayed_commit_timeout option.

delayed_commits Whether the database server returns control to an application following a COMMIT or not. This
property corresponds to the delayed_commits option.

DiskRead The number of pages that have been read from disk.

DiskReadHint The number of disk read hints.

DiskReadHintPages The number of disk read hint pages.

DiskReadIndInt The number of index internal-node pages that have been read from disk.

DiskReadIndLeaf The number of index leaf pages that have been read from disk.

DiskReadTable The number of table pages that have been read from disk.

DiskReadWorkTable The number of disk work table reads.

disk_sandbox Whether the read-write file operations of the database are restricted to the directory where the
main database file is located. This property corresponds to the disk_sandbox option.

DiskSyncRead The number of disk reads issued synchronously.

SAP IQ SQL Reference


SQL Functions INTERNAL 221
Property name Description

DiskSyncWrite The number of writes issued synchronously.

DiskWaitRead The number of times the database server waited for an asynchronous read.

DiskWaitWrite The number of times the database server waited for an asynchronous write.

DiskWrite The number of modified pages that have been written to disk.

DiskWriteHint The number of disk write hints.

DiskWriteHintPages The number of disk write hint pages.

divide_by_zero_error Whether if division by zero results in an error (On) or not (Off). This property corresponds to the
divide_by_zero_error option.

Encryption Whether the connection is encrypted or not

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

EventName The name of the associated event if the connection is running an event handler. Otherwise, an
empty string is returned.

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

ExprCacheAbandons The number of times that the expression cache was abandoned because the hit rate was too low.

ExprCacheDropsToRea­ The number of times that the expression cache dropped to read-only status because the hit rate
dOnly was low.

ExprCacheEvicts The number of evictions from the expression cache.

ExprCacheHits The number of hits in the expression cache.

ExprCacheInserts The number of values inserted into the expression cache.

ExprCacheLookups The number of lookups done in the expression cache.

ExprCacheResumesO­ The number of times that the expression cache resumed read-write status because the hit rate
fReadWrite increased.

ExprCacheStarts The number of times that the expression cache was started.

extern_login_credentials Whether remote connections are attempted using the logged in user's external login credentials
or the effective user's external login credentials. This property corresponds to the ex­
tern_login_credentials option.

extended_join_syntax Whether queries with duplicate correlation name syntax for multi-table joins are allowed, or
whether they are reported as errors. This property corresponds to the extended_join_syntax op­
tion.

SAP IQ SQL Reference


222 INTERNAL SQL Functions
Property name Description

fire_triggers Whether triggers are fired in the database. This property corresponds to the fire_triggers option.

first_day_of_week The number that is used for the first day of the week, where 7=Sunday and 1=Monday. This prop­
erty corresponds to the first_day_of_week option.

for_xml_null_treatment The value is Omit if elements and attributes that contain NULL values are omitted from the re­
sult. The value is Empty if empty elements or attributes are generated for NULL values when the
FOR XML clause is used in a query. This property corresponds to the for_xml_null_treatment op­
tion.

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

FullCompare The number of comparisons that have been performed beyond the hash value in an index.

GetData The number of GETDATA requests.

global_database_id The starting value used for columns created with DEFAULT GLOBAL AUTOINCREMENT. This
property corresponds to the global_database_id option.

HashForcedPartitions The number of times that a hash operator was forced to partition because of competition for
memory.

HashRowsFiltered The number of probe rows rejected by bit-vector filters.

HashRowsPartitioned The number of rows written to hash work tables.

HasSecuredFeature Whether at least one feature of the feature set is secured (Yes) or not (No). This property has
extensions that you can specify when querying the property value.

HashWorkTables The number of work tables created for hash-based operations.

HeapsCarver The number of heaps used for short-term purposes such as query optimization.

HeapsLocked The number of relocatable heaps currently locked in the cache.

HeapsQuery The number of heaps used for query processing (hash and sort operations).

HeapsRelocatable The number of relocatable heaps.

http_connec­ The nominal threshold size of database connections. This property corresponds to the http_con­
tion_pool_basesize nection_pool_basesize option.

http_connec­ The maximum length of time that unused connections are stored in the connection pool. This
tion_pool_timeout property corresponds to the http_connection_pool_timeout option.

http_session_timeout The current HTTP session timeout, in minutes. This property corresponds to http_session_time­
out option.

SAP IQ SQL Reference


SQL Functions INTERNAL 223
Property name Description

HttpServiceName The service name entry point for the current HTTP request. This property is useful for error re­
porting and flow control. An empty string is returned when this property is selected from a
stored procedure that did not originate from an HTTP request or if the connection is currently
inactive or waiting to continue an HTTP session.

IdleTimeout The idle timeout value of the connection. The value is NA if the request that is currently execut­
ing is part of an event handler.

IndAdd The number of entries that have been added to indexes.

IndLookup The number of entries that have been looked up in indexes.

integrated_server_name The name of the Domain Controller server used for looking up Windows user group membership
for integrated logins. This property corresponds to the integrated_server_name option.

isolation_level The isolation level of the connection. This property corresponds to the isolation_level option.

java_class_path The list of additional directories or JAR files that are searched for classes. This property corre­
sponds to the java_class_path option.

java_location The path of the Java VM for the database if one has been specified. This property corresponds to
the java_location option.

java_vm_options The command line options that the database server uses when it launches the Java VM. This
property corresponds to the java_vm_options option.

java_main_userid This property is deprecated.

Language The locale language.

LastCommitRedoPos The redo log position after the last COMMIT operation was written to the transaction log by the
connection.

LastIdle The number of ticks between requests.

LastPlanText The long text plan of the last query executed on the connection. You control the remembering of
the last plan by setting the RememberLastPlan option of the sa_server_option system proce­
dure, or using the -zp server option.

LastReqTime The time at which the last request for the specified connection started, in the timezone of the
database. This property can return an empty string for internal connections, such as events. If
the database has the time_zone option set, then the value is returned using the database's time
zone.

SAP IQ SQL Reference


224 INTERNAL SQL Functions
Property name Description

LastStatement The most recently prepared SQL statement for the current connection. The LastStatement value
is set when a statement is prepared, and is cleared when a statement is dropped. Only one state­
ment string is remembered for each connection. When client statement caching is enabled and a
cached statement is reused, the value is an empty string. If sa_conn_activity reports a non-
empty value for a connection, it is most likely the statement that the connection is currently exe­
cuting. If the statement had completed, it would likely have been dropped and the property value
would have been cleared. If an application prepares multiple statements and retains their state­
ment handles, then the LastStatement value does not reflect what a connection is currently do­
ing.

LivenessTimeout The liveness timeout period for the current connection. The value is NA if the request that is cur­
rently executing is part of an event handler.

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

LockCount The number of locks held by the connection.

LockObjectOID The value is zero if the connection isn't blocked on a table, mutex, or a semaphore, or if the con­
nection is on a different database than the connection calling CONNECTION_PROPERTY. Other­
wise, LockObjectOID is the object ID of the table, permanent mutex, or permanent semaphore
that the connection is blocked on. A negative value indicates the ID of a temporary mutex or
semaphore. LockObjectOID can be used to look up information about temporary mutexes and
semaphores using the sp_list_mutexes_semaphores system procedure. If the object is a table,
LockObjectOID can be used to look up table information using the SYSTAB system view.

LockObjectType The ID for the type of object the connection is blocked on. Use the ID to look up the object type in
the SYSOBJECT view. Can be one of 'TABLE' or 'MUTEX SEMAPHORE'.

LockIndexID The identifier of the locked index.

LockName The 64-bit unsigned integer value representing the lock for which a connection is waiting.

LockRowID The identifier of the locked row.

LockTableOID Zero if the connection isn't blocked, or isn't blocked on a table, or if the connection is on a differ-
ent database than the connection calling CONNECTION_PROPERTY. Otherwise, this is the ob­
ject ID of the table for the lock on which this connection is waiting. The object ID can be used to
look up table information using the SYSTAB system view.

log_deadlocks Whether deadlock information is recorded (On) or not (Off). This property corresponds to the
log_deadlocks option.

LogFreeCommit The number of redo free commits. A redo free commit occurs when a commit of the transaction
log is requested but the log has already been written (so the commit was done for free.)

login_mode The type of login that is supported. This property corresponds to the login_mode option.

login_procedure The name of the stored procedure used to set compatibility options at startup. This property
corresponds to the login_procedure option.

SAP IQ SQL Reference


SQL Functions INTERNAL 225
Property name Description

LoginTime The date and time the connection was established. If the database has the time_zone option set,
then the value is returned using the database's time zone.

LogWrite The number of pages that have been written to the transaction log.

materialized_view_opti­ The value of the materialized_view_optimization option for the connection, which indicates
mization whether materialized views are used during query optimization.

max_connections The value of the max_connections option, which indicates the number of concurrent connec­
tions allowed to the database.

max_client_state­ The value of the max_client_statements_cached option, which indicates the number of state­
ments_cached ments cached by the client.

max_cursor_count The maximum number of cursors that a connection can use at once. This property corresponds
to the max_cursor_count option.

max_hash_size This property is deprecated.

max_plans_cached The maximum number of execution plans to be stored in a cache. This property corresponds to
the max_plans_cached option.

max_priority The maximum priority level a connection can have. This property corresponds to the max_prior­
ity option for the connection.

max_query_tasks The maximum number of requests that the database server can use to process a query. This
property corresponds to the max_query_tasks option.

max_recursive_itera­ The maximum number of iterations a recursive common table expression can make. This prop­
tions erty corresponds to the max_recursive_iterations option.

max_statement_count The maximum number of prepared statements that a connection can use simultaneously. This
property corresponds to max_statement_count option.

max_temp_space The maximum amount of temporary file space available for a connection. This property corre­
sponds to f the max_temp_space option for the connection.

MessageReceived The string that was generated by the MESSAGE statement that caused the WAITFOR statement
to be interrupted. Otherwise, an empty string is returned.

min_password_length The minimum length for new passwords in the database. This property corresponds to
min_password_length option.

min_role_admins The minimum number of administrators required for a role. This property corresponds to the
min_role_admins option.

Name The name of the current connection. You can specify a connection name using the Connection­
Name (CON) connection parameter.

SAP IQ SQL Reference


226 INTERNAL SQL Functions
Property name Description

NcharCharSet The NCHAR character set used by the connection. This property has extensions that you can
specify when querying the property value.

nearest_century The value of the nearest_century option, which indicates how two-digit years are interpreted in
string-to-date conversions.

NodeAddress The node for the client in a client/server connection. When the client and server are both on the
same computer, an empty string is returned.

non_keywords The value of the non_keywords option, which is a list of keywords, if any, that are turned off so
they can be used as identifiers.

NumLocalTempTables The number of local temporary tables in use by the connection.

Number The connection ID (a number) for the current connection.

odbc_describe_bi­ The value is Off if the SAP IQ ODBC driver describes both BINARY and VARBINARY columns as
nary_as_varbinary SQL_BINARY. The value is On if the ODBC driver describes BINARY and VARBINARY columns as
SQL_VARBINARY. This property corresponds to the odbc_describe_binary_as_varbinary option.

odbc_distin­ Whether CHAR columns are described as SQL_CHAR (On) or they are described as SQL_VAR­
guish_char_and_varchar CHAR (OFF). This property corresponds to the odbc_distinguish_char_and_varchar option.

oem_string The string stored in the header page of the database file. This property corresponds to the
oem_string option.

on_charset_conver­ The behavior when an error is encountered during character set conversion. This property corre­
sion_failure sponds to the on_charset_conversion_failure option.

on_tsql_error The behavior when an error is encountered while executing a stored procedure or T-SQL batch.
This property corresponds to the on_tsql_error option.

optimization_goal How query processing is optimized. This property corresponds to the optimization_goal option.

optimization_level The value of the optimization_level option, which is a value between 0 and 15. This number is
used to control the level of effort made by the SAP IQ query optimizer to find an access plan for a
SQL statement.

optimization_workload The level of effort made by the SAP IQ query optimizer to find an access plan for a SQL state­
ment. This property corresponds to the optimization_workload option for the connection.t

OSUser The operating system user name associated with the client process. If the client process is im­
personating another user (or the set ID bit is set on Unix), the impersonated user name is re­
turned. An empty string is returned for version 10.0.1 and earlier clients, and for HTTP and TDS
clients.

PacketSize The packet size used by the connection, in bytes. The value is NA if the request that is currently
executing is part of an event handler. This property corresponds to the CommBufferSize
(CBSIZE) connection parameter.

SAP IQ SQL Reference


SQL Functions INTERNAL 227
Property name Description

PacketsReceived The number of client/server communication packets received. This value is not updated for
HTTP or HTTPS connections.

PacketsReceivedUn­ The number of packets that would have been received during client/server communications if
comp compression was disabled. (This value is the same as the value for PacketsReceived if compres­
sion is disabled.)

PacketsSent The number of client/server communication packets sent. This value is not updated for HTTP or
HTTPS connections.

PacketsSentUncomp The number of packets that would have been sent during client/server communications if com­
pression was disabled. (This value is the same as the value for PacketsSent if compression is dis­
abled.)

parameterization_level The value of the parameterization_level option for the connection, which indicates the statement
parameterization behavior.

ParameterizationPrepar­ The number of prepares for statements that have been automatically parameterized.
eCount

ParentConnection The connection ID of the connection that created a temporary connection to perform a database
operation (such as performing a backup or creating a database). For other types of connections,
the value is NULL.

pinned_cursor_per­ The value of the pinned_cursor_percent_of_cache option, which indicates the percentage of the
cent_of_cache cache that can be used for pinning cursors.

post_login_procedure The name of the procedure whose result set contains messages that should be displayed by ap­
plications when a user connects .This property corresponds to the post_login_procedure option.

precision The value of the precision option, which indicates the decimal and numeric precision setting.

prefetch The value of the prefetch option. The value is Off if no prefetching is done. The value is Condi­
tional if prefetching occurs unless the cursor type is SENSITIVE or the query includes a proxy
table. The value is Always if prefetching is done even for SENSITIVE cursor types and cursors
that involve a proxy table.

Prepares The number of statement preparations performed for the connection.

PrepStmt The number of prepared statements currently being maintained by the database server for this
connection.

preserve_source_format Whether the original source definition of procedures, triggers, views, and event handlers is saved
in system tables (On) or not (Off). This property corresponds to the preserve_source_format op­
tion.

prevent_arti­ Whether updates are not allowed to the primary key columns of tables involved in publications
cle_pkey_update (On) or not (Off). This property corresponds to the prevent_article_pkey_update option.

SAP IQ SQL Reference


228 INTERNAL SQL Functions
Property name Description

priority The value of the priority option for the connection, which indicates the priority level of a connec­
tion.

Progress Information about how long a query has been running. This property has extensions that you can
specify when querying the property value.

progress_messages The value of the progress_messages option.

query_mem_timeout The value of the query_mem_timeout option.

QueryBypassed The number of requests optimized by the optimizer bypass.

QueryBypassedCosted The number of requests processed by the optimizer bypass using costing.

QueryBypassedHeuris­ The number of requests processed by the optimizer bypass using heuristics.
tic

QueryBypassedOpti­ The number of requests initially processed by the optimizer bypass and subsequently fully opti­
mized mized by the optimizer.

QueryCachedPlans The number of query execution plans currently cached for the connection.

QueryCachePages The number of cache pages used to cache execution plans.

QueryDescribedBypass The number of describe requests processed by the optimizer bypass.

QueryDescribedOptim­ The number of describe requests processed by the optimizer.


izer

QueryHeapPages The number of cache pages used for query processing (hash and sort operations).

QueryJHToJNLOptUsed The number of times a hash join was converted to a nested loops join.

QueryLowMemoryStrat­ The number of times the server changed its execution plan during execution as a result of low
egy memory conditions. The strategy can change because less memory is currently available than
the optimizer estimated, or because the execution plan required more memory than the opti­
mizer estimated.

QueryMemActiveCurr The number of requests actively using query memory.

QueryMemGrantFailed The total number of times a request waited for query memory, but failed to get it.

QueryMemGrant­ The number of pages currently granted to requests.


Granted

QueryMemGrantRe­ The total number of times any request attempted to acquire query memory.
quested

QueryMemGrantWaited The total number of times any request waited for query memory.

SAP IQ SQL Reference


SQL Functions INTERNAL 229
Property name Description

QueryMemGrantWaiting The current number of requests waiting for query memory.

QueryOpened The number of OPEN requests for execution.

QueryOptimized The number of requests fully optimized.

QueryReused The number of requests that have been reused from the plan cache.

QueryRowsFetched The number of rows that have been read from base tables, either by a sequential scan or an in­
dex scan, for this connection.

QueryRowsMaterialized The number of rows that are written to work tables during query processing.

quoted_identifier Whether strings enclosed in double quotes are interpreted as identifiers (On), or if they are inter­
preted as literal strings (Off). This property corresponds to the quoted_identifier option.

read_past_deleted Whether sequential scans at isolation levels 1 and 2 skip uncommitted deleted rows (On), or se­
quential scans block on uncommitted deleted rows at isolation levels 1 and 2 (Off). This property
corresponds to the read_past_deleted option.

recovery_time The maximum length of time, in minutes, that the database server will take to recover from sys­
tem failure. This property corresponds to the recovery_time option.

RecursiveIterations The number of iterations for recursive unions.

RecursiveIterationsHash The number of times recursive hash join used a hash strategy.

RecursiveIterations­ The number of times recursive hash join used a nested loops strategy.
Nested

RecursiveJNLMisses The number of index probe cache misses for recursive hash join.

RecursiveJNLProbes The number of times recursive hash join attempted an index probe.

remote_idle_timeout The time, in seconds, of inactivity that web service client procedures and functions will tolerate.
This property corresponds to the remote_idle_timeout option.

replicate_all For internal use only.

ReqCountActive The number of requests processed, or NULL if the RequestTiming server property is set to Off.

ReqCountBlockConten­ The number of times the connection waited for atomic access, or NULL if the -zt option was not
tion specified.

ReqCountBlockIO The number of times the connection waited for I/O to complete, or NULL if the -zt option was
not specified.

ReqCountBlockLock The number of times the connection waited for a lock, or NULL if the -zt option was not speci­
fied.

SAP IQ SQL Reference


230 INTERNAL SQL Functions
Property name Description

ReqCountUnscheduled The number of times the connection waited for scheduling, or NULL if the -zt option was not
specified.

ReqStatus The status of the request. The value is Idle when the connection is not currently processing a
request. The value is Unscheduled* when the connection has work to do and is waiting for an
available database server worker. The value is BlockedIO* when the connection is blocked wait­
ing for an I/O. The value is BlockedContention* when the connection is blocked waiting for ac­
cess to shared database server data structures. The value is BlockedLock when the connection
is blocked waiting for a locked object. The value is Executing when the connection is executing a
request. The values marked with an asterisk (*) are only returned when logging of request timing
information has been turned on for the database server using the -zt server option. If request
timing information is not being logged (the default), the values are reported as Executing.

ReqTimeActive The amount of time, in seconds, spent processing requests, or NULL if the -zt option was not
specified.

ReqTimeBlockConten­ The amount of time, in seconds, spent waiting for atomic access, or NULL if the RequestTiming
tion server property is set to Off.

ReqTimeBlockIO The amount of time, in seconds, spent waiting for I/O to complete, or NULL if the -zt option was
not specified.

ReqTimeBlockLock The amount of time, in seconds, spent waiting for a lock, or NULL if the -zt option was not speci­
fied.

ReqTimeUnscheduled The amount of unscheduled time, or NULL if the -zt option was not specified.

ReqType The type of the last request. If a connection has been cached by connection pooling, its ReqType
value is CONNECT_POOL_CACHE.

request_timeout The value of the request_timeout option, which indicates the maximum time a single request can
run.

RequestsReceived The number of client/server communication requests or round trips. It is different from Packets­
Received in that multi-packet requests count as one request, and liveness packets are not in­
cluded.

reserved_connections The number of connections that are reserved for standard connections. This property corre­
sponds to the reserved_connections option.

reserved_keywords The value of the reserved_keywords option, which specifies a list of non-default reserved key­
words that are enabled for the database.

re­ Whether DATE, TIME, and TIMESTAMP values are returned to applications as a string (On), or
turn_date_time_as_strin they are returned as a DATE, TIME, or TIMESTAMP data type (Off). This property corresponds to
g the return_date_time_as_string option.

Rlbk The number of rollback requests that have been handled.

SAP IQ SQL Reference


SQL Functions INTERNAL 231
Property name Description

rollback_on_deadlock Whether transaction are automatically rolled back if it encounters a deadlock (On) or not (Off).
This property corresponds to the rollback_on_deadlock option.

RollbackLogPages The number of pages in the rollback log.

row_counts Whether the row count is always accurate (On), or the row count is usually an estimate (Off).
This property corresponds to the row_counts option.

scale The decimal and numeric scale for the connection. This property corresponds to the scale op­
tion.

secure_feature_key This property is deprecated. The value of the secure_feature_key option, which stores the key
that is used to enable and disable features for a database server. Selecting the value of this prop­
erty always returns an empty string.

ServerNodeAddress The node for the server in a client/server connection. When the client and server are both on the
same computer, an empty string is returned. The value is NA if the request that is currently exe­
cuting is part of an event handler.

ServerPort The database server's TCP/IP port number or 0.

SessionCreateTime The time the HTTP session was created. If the database has the time_zone option set, then the
value is returned using the database's time zone.

SessionID The session ID for the connection if it exists, otherwise, an empty string.

SessionLastTime The time of the last request for the HTTP session. If the database has the time_zone option set,
then the value is returned using the database's time zone.

SessionTimeout The time, in minutes, the HTTP session persists during inactivity.

SnapshotCount The number of snapshots associated with the connection.

sort_collation The value of the sort_collation option. The value is Internal if the ORDER BY clause remains un­
changed; otherwise, the value is the collation name or the collation ID.

SortMergePasses The number of merge passes used during sorting.

SortRowsMaterialized The number of rows written to sort work tables.

SortRunsWritten The number of sorted runs written during sorting.

SortSortedRuns The number of sorted runs created during run formation.

SortWorkTables The number of work tables created for sorting.

sql_flagger_error_level The value of the sql_flagger_error_level option, which controls the response to any SQL that is
not part of the specified standard. This property corresponds to the sql_flagger_error_level op­
tion.

SAP IQ SQL Reference


232 INTERNAL SQL Functions
Property name Description

sql_flagger_warn- The value of the sql_flagger_warning_level. This property corresponds to the sql_flagger_warn-
ing_level ing_level option.

st_geometry_asbi­ How spatial values are converted from a geometry to a binary format. This property corresponds
nary_format to the st_geometry_asbinary_format option.

st_geometry_astext_for­ How spatial values are converted from a geometry to text. This property corresponds to the
mat st_geometry_astext_format option.

st_geometry_asxml_for­ How spatial values are converted from a geometry to XML. This property corresponds to the
mat st_geometry_asxml_format option.

st_geometry_de­ How spatial values are described. This property corresponds to the st_geometry_describe_type
scribe_type option.

st_geometry_interpola­ The interpolation setting for ST_CircularString geometries. This property corresponds to st_ge­
tion ometry_interpolation option.

st_geometry_on_invalid The behavior when a geometry fails surface validation. This property corresponds to the st_ge­
ometry_on_invalid option.

StatementDescribes The total number of statements processed by DESCRIBE requests.

StatementPostAnno­ The number of statements processed by the semantic query transformation phase.
tates

StatementPostAnnota­ The number of statements processed by the semantic query transformation phase, but that
tesSimple skipped some of the semantic transformations.

StatementPostAnnota­ The number of statements that have completely skipped the semantic query transformation
tesSkipped phase.

string_rtruncation Whether an error is raised when a string is truncated (On), or no error is not raised (Off) This
property corresponds to the string_rtruncation option.

subsume_row_locks Whether the database server acquires individual row locks for a table (On), or not (Off). This
property corresponds to the subsume_row_locks option.

suppress_tds_debug­ Whether TDS debugging information appears in the database server messages window (Off), or
ging the debugging information does not appear in the database server messages window (On). This
property corresponds to the suppress_tds_debugging option.

synchronize_mir­ Whether the database mirror server is synchronized on commit (On) or not (Off). This property
ror_on_commit corresponds to the synchronize_mirror_on_commit option.

tds_empty_string_is_nul Whether empty strings are returned as NULL for TDS connections (On), or if a string containing
l one blank character is returned for TDS connections (Off). This property corresponds to the
tds_empty_string_is_null option.

SAP IQ SQL Reference


SQL Functions INTERNAL 233
Property name Description

temp_space_limit_check Whether the database server checks the amount of temporary space available for a connection
(On), or the database server does not check the amount of space available for a connection
(Off). This property corresponds to the temp_space_limit_check option.

TempFilePages The number of temporary file pages used by the connection.

TempTablePages The number of pages in the temporary file used for temporary tables.

time_format The string format used for times retrieved from the database. This property corresponds to the
time_format option.

time_zone The time zone that the database uses for time zone calculations. This property corresponds to
the time_zone option.

time_zone_adjustment The number of minutes that must be added to the Coordinated Universal Time (UTC) to display
time local to the connection. This property corresponds to the time_zone_adjustment option.

timestamp_format The format for timestamps that are retrieved from the database. This property corresponds to
the timestamp_format option.

time­ The format for TIMESTAMP WITH TIME ZONE values retrieved from the database. This property
stamp_with_time_zone_ corresponds to the timestamp_with_time_zone_format option.
format

TimeZoneAdjustment The number of minutes that must be added to the Coordinated Universal Time (UTC) to display
time local to the connection.

TransactionStartTime The value is a string containing the time the database was first modified after a COMMIT or
ROLLBACK, or an empty string if no modifications have been made to the database since the
last COMMIT or ROLLBACK. If the database has the time_zone option set, then the value is re­
turned using the database's time zone.

truncate_time­ Whether the number of decimal places used in the TIMESTAMP values is limited (On) or not
stamp_values (Off). This property corresponds to the truncate_timestamp_values option.

trusted_certificates_file The file that contains the list of trusted Certificate Authority certificates when the database
server acts as a client to an LDAP server. This property corresponds to the trusted_certifi-
cates_file option.

tsql_outer_joins Whether Transact-SQL outer joins can be used in DML statement (On) or not (Off). This property
corresponds to the value of the tsql_outer_joins option.

tsql_variables Whether you can use the @ sign instead of the colon as a prefix for host variable names in Em­
bedded SQL (On) or not (Off). This property corresponds to the value of the tsql_variables op­
tion.

UncommitOp The number of uncommitted operations.

SAP IQ SQL Reference


234 INTERNAL SQL Functions
Property name Description

updatable_state­ The isolation level (0, 1, 2, or 3) used by updatable statements when the isolation_level option is
ment_isolation set to Readonly-statement-snapshot. This property corresponds to the updatable_state­
ment_isolation option.

update_statistics Whether the connection can send query feedback to the statistics governor (On) or the statistics
governor does not receive query feedback from the current connection (Off). This property cor­
responds to the update_statistics option.

upgrade_database_ca­ This property is reserved for system use. Do not change the setting of this option.
pability

user_estimates The value that controls whether selectivity estimates in query predicates are respected or ig­
nored by the query optimizer. This property corresponds to the user_estimates option.:

UserAppInfo The string specified by the AppInfo connection parameter in a connection string.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate01 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate02 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate03 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate04 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate05 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw01 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw02 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw03 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw04 defined by the client application.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw05 defined by the client application.

UserID The user ID for the connection.

SAP IQ SQL Reference


SQL Functions INTERNAL 235
Property name Description

UtilCmdsPermitted Whether SQL statements such as CREATE DATABASE, DROP DATABASE, and RESTORE DATA­
BASE are permitted for the connection or not. The value is an empty string if the specified con­
nection ID is not for the current connection.

uuid_has_hyphens The format of unique identifier values when they are converted to strings. When the option is set
to On, the resulting strings contain four hyphens. This property corresponds to the uuid_has_hy­
phens option.

verify_password_func­ The name of the function used for password verification if one has been specified. This property
tion corresponds to the verify_password_function.

wait_for_commit Whether the database does not check foreign key integrity until the next COMMIT statement
(On), or all foreign keys that are not created with the CHECK ON COMMIT clause are checked as
they are inserted, updated or deleted (Off). This property corresponds to the wait_for_commit
option.

WaitStartTime The time at which the connection started waiting (or an empty string if the connection is not
waiting). If the database has the time_zone option set, then the value is returned using the data­
base's time zone.

WaitType The reason for the wait, if it is available. The value is lock when the connection is waiting on a
lock The value is waitfor when the connection is executing a waitfor statement. The value is an
empty-string when the connection is not waiting, or when the reason for the wait is not available.

webservice_name­ The hostname to be used as the XML namespace within generated WSDL documents if one has
space_host been specified. This property corresponds to the webservice_namespace_host option,

webservice_sessio­ The session identifier name that is used by the web server to determine whether session man­
nid_name agement is being used. This property corresponds to the webservice_sessionid_name option.

6.8.4 Properties Available for Each Database

You can retrieve the value of a specific database property or the values of all database properties. Database
properties apply to an entire database.

The server properties QueryBypassedCosted, QueryBypassedOptimized, QueryDescribedOptimizer,


and StatementPostAnnotatesSimple are updated only for queries against catalog store tables.

Use the following to retrieve database property information:

db_property system function

Retrieves the value of a database property. The following statement returns the page size of the current
database:

select db_property ( 'PageSize')

sa_db_properties system procedure

SAP IQ SQL Reference


236 INTERNAL SQL Functions
Retrieves the values of all database properties:

call sa_db_properties

In this section:

List of database server properties [page 237]


Database server properties are available for each connection to a database. Use the PROPERTY system
function to retrieve the value for an individual property and use the sa_eng_properties system
procedure to retrieve the values of all database server properties.

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


PROPERTY Function [System] [page 459]
PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]

6.8.4.1 List of database server properties

Database server properties are available for each connection to a database. Use the PROPERTY system
function to retrieve the value for an individual property and use the sa_eng_properties system procedure to
retrieve the values of all database server properties.

 Example

The following statement returns the number of cache pages used for global server data structures:

SELECT PROPERTY ( 'MainHeapPages' );

Use the sa_eng_properties system procedure to retrieve the values of all database server properties:

CALL sa_eng_properties;

Database server properties

Property name Description

ActiveReq The number of server workers that are currently handling client-side requests.

SAP IQ SQL Reference


SQL Functions INTERNAL 237
Property name Description

ApproximateCPUTime An estimate of the amount of CPU time accumulated by the database server, in seconds. The
value may differ from the actual value by as much as 50%, although typical variations are in
the 5-10% range. On multi-processor computers, each CPU (or hyperthread or core) accumu­
lates time, so the sum of accumulated times for all connections may be greater than the
elapsed time.

AutoMultiProgrammingLe­ Whether the database server is automatically adjusting its multiprogramming level.
vel

AutoMultiProgrammingLe­ Whether messages about automatic adjustments to the database server's multiprogramming
velStatistics level are displayed in the database server message log.

AvailIO The current number of available I/O control blocks.

BuildChange Reserved for system use.

BuildClient Reserved for system use. Do not change the setting of this property.

BuildProduction Whether the database server is compiled for production use (Yes) or whether the database
server is a debug build (No)..

BuildReproducible Reserved for system use.

BytesReceived The number of bytes received during client/server communications. This value is updated for
HTTP and HTTPS connections.

BytesReceivedUncomp The number of bytes that would have been received during client/server communications if
compression was disabled. (This value is the same as the value for BytesReceived if compres­
sion is disabled.)

BytesSent The number of bytes sent during client/server communications. This value is updated for
HTTP and HTTPS connections.

BytesSentUncomp The number of bytes that would have been sent during client/server communications if com­
pression was disabled. (This value is the same as the value for BytesSent if compression is dis­
abled.)

CacheAllocated The number of cache pages that have been allocated for server data structures.

CacheFile The number of cache pages used to hold data from database files.

CacheFileDirty The number of cache pages that are dirty (needing a write).

CacheFree The number of cache pages not being used.

CacheHits The number of database page lookups.

CacheMisses The number of times a page was not in the cache.

CachePanics The number of times the cache manager has failed to find a page to allocate.

SAP IQ SQL Reference


238 INTERNAL SQL Functions
Property name Description

CachePinned The number of pinned cache pages.

CacheRead The number of cache reads.

CacheReplacements The number of pages in the cache that have been replaced.

CacheScavenges The number of times the cache manager has scavenged for a page to allocate.

CacheScavengeVisited The number of pages visited while scavenging for a page to allocate.

CacheSizingStatistics Whether the database server is displaying cache sizing statistics when the cache is resized.

CarverHeapPages The number of heap pages used for short-term purposes, such as query optimization.

CharSet The CHAR character set in use by the database server.

ClientStmtCacheHits The number of prepares that were not required because of the client statement cache. This is
the number of additional prepares that would be required if client statement caching was disa­
bled.

ClientStmtCacheMisses The number of statements in the client statement cache that were prepared again. This is the
number of times a cached statement was considered for reuse, but could not be reused be­
cause of a schema change, a database option setting, or a DROP VARIABLE statement.

CockpitDB The set of options currently being used by the database server, as well as the Temp parameter.
When Temp is set to yes, the Cockpit database is a temporary database.

CockpitURL A semicolon-delimited list of valid URLs for the Cockpit.

CollectStatistics Whether the database server is collecting performance statistics.

CommandLine The command line arguments that were used to start the database server.

If the encryption key for a database was specified using the -ek option, the key is replaced with
a constant string of asterisks in the value for this property.

Commit The number of Commit requests that have been handled.

CompactPlatformVer A condensed version of the PlatformVer property.

CompanyName The name of the company owning this software.

CompletedReq The number of requests that have been completed.

ConnCount The number of connections to the database server. This property value does not include con­
nections used for internal operations, but does include connections used for events and exter­
nal environment support.

SAP IQ SQL Reference


SQL Functions INTERNAL 239
Property name Description

ConnectedTime The total length of time, in seconds, that all connections have been connected to the database
server.

The value is updated only when a request completes for a connection or when a connection
disconnects. As a result, the value can lag behind for connections that are idle or busy execut­
ing for a long time in the database server. The value includes time accrued by any connection,
including database events and background server connections (such as the database
cleaner).

ConnsDisabled Whether the server option is set to disable new connections.

ConsoleLogFile The name of the file where database server messages are logged if the -o option was specified.
If the -option was not specified, the value is an empty string.

ConsoleLogMaxSize The maximum size in bytes of the file used to log database server messages.

CurrentCacheSize The current cache size, in kilobytes.

CurrentMirrorBackground­ The number of workers currently being used for database mirroring background tasks. These
Workers workers are separate from those controlled by the multiprogramming level.

CurrentMultiProgrammin­ The current number of tasks that the database server can process concurrently.
gLevel

CurrRead The current number of file reads that were issued by the database server, but that have not
completed yet.

CurrWrite The current number of file writes that were issued by the database server, but that have not
completed yet.

Cursor The number of declared cursors that are currently being maintained by the database server.

CursorOpen The number of open cursors that are currently being maintained by the database server.

DebuggingInformation Whether the server is displaying diagnostic messages for troubleshooting.

DefaultCollation The collation that would be used for new databases if none is explicitly specified.

DefaultNcharCollation The name of the default NCHAR collation on the server computer (UCA if ICU is installed, and
UTF8BIN otherwise).

DiskRead The number of disk reads.

DiskReadHintScatterLimit The imposed limit on the size (in bytes) of a scatter read hint.

DiskRetryRead The number of disk read retries.

DiskRetryReadScatter The number of disk read retries for scattered reads.

DiskRetryWrite The number of disk write retries.

SAP IQ SQL Reference


240 INTERNAL SQL Functions
Property name Description

DiskSandbox Whether the read-write file operations of the database are restricted to the directory where
the main database file is located (On) or not (Off).

DiskWrite The number of modified pages that have been written to disk.

EventTypeDesc The description of the event type associated with a given event type ID.

EventTypeName The system event type name associated with a given event type ID.

ExchangeTasks The number of tasks currently being used for parallel execution of queries.

ExchangeTasksCompleted The total number of internal tasks that have been used for intra-query parallelism since the
database server started.

FipsMode Whether the -fips option was specified when the database server was started.

FirstOption The number that represents the first connection property that corresponds to a database op­
tion.

FreeBuffers The number of available network buffers.

FunctionMaxParms The maximum number of parameters that can be specified by a function. The function is iden­
tified by the value specified by the <function-number>, which is a positive integer. For ex­
ample:

SELECT PROPERTY ( 'FunctionMaxParms', <function-number> );

The <function-number> is subject to change between releases.

FunctionMinParms The minimum number of parameters that must be specified by a function. The function is
identified by the value specified by the <function-number>, which is a positive integer. For
example:

SELECT PROPERTY ( 'FunctionMinParms', <function-number> );

The <function-number> is subject to change between releases.

FunctionName The name of the function identified by the value specified by the <function-number> (which
is a positive integer):

SELECT PROPERTY ( 'FunctionName', <function-number> );

The <function-number> is subject to change between releases.

HasSecuredFeature Whether at least one feature of the all feature set is secured at the global server level. This
property has extensions that you can specify when querying the property value.

HasSecureFeatureKey Whether the database server has at least one secure feature key. This property has extensions
that you can specify when querying the property value.

HeapsCarver The number of heaps used for short-term purposes such as query optimization.

SAP IQ SQL Reference


SQL Functions INTERNAL 241
Property name Description

HeapsLocked The number of relocatable heaps currently locked in the cache.

HeapsQuery The number of heaps used for query processing (hash and sort operations).

HeapsRelocatable The number of relocatable heaps.

HttpAddresses A semicolon-delimited list of the IP addresses that the database server is listening to for HTTP
connections from clients. For example:

(::1):80;127.0.0.1:80

HttpConnectionsQueued The number of connections that are currently in the queue.

HttpListeners A semicolon-delimited list of <IP address>:<port> pairs that the database server is using
to listen for HTTP connections.

HttpNumActiveReq The number of HTTP connections that are actively processing an HTTP request. An HTTP con­
nection that has sent its response is not included.

HttpNumConnections The number of HTTP connections that are currently open within the database server. They
may be actively processing a request or waiting in a queue of long lived (keep-alive) connec­
tions.

HttpNumSessions The number of active and dormant HTTP sessions within the database server.

HttpPorts The HTTP port numbers for the web server as a comma-delimited list.

HttpQueueCount The total number of connections that have been queued since the database server started.

HttpQueueMaxCount The maximum number of connections that have been in the queue at one time.

HttpQueueTimedOut The total number of connections that have timed out after sitting in the queue.

HttpsAddresses A semicolon-delimited list of the IP addresses that the server is listening to for HTTPS connec­
tions from clients. For example:

(::1):443;127.0.0.1:443

HttpsListeners A semicolon-delimited list of <IP address>:<port> pairs that the database server is using
to listen for HTTPS connections.

HttpsNumActiveReq The number of secure HTTPS connections that are actively processing an HTTPS request. An
HTTPS connection that has sent its response is not included.

HttpsNumConnections The number of HTTPS connections that are currently open within the database server. They
may be actively processing a request or waiting in a queue of long lived (keep-alive) connec­
tions.

HttpsPorts The HTTPS port numbers for the web server as a comma-delimited list.

SAP IQ SQL Reference


242 INTERNAL SQL Functions
Property name Description

IdleTimeout The default idle timeout.

IPAddressMonitorPeriod The time in seconds that a database server checks for new IP addresses.

IsAesniAvailable Whether the database server computer's CPU supports the Intel AES-NI instruction set and
the computer is running a supported operating system.

IsFipsAvailable Whether the FIPS-certified DLL is installed.

IsIQ Reserved for system use.

IsNetworkServer Whether the connection is to a network database server (Yes), or to a personal database
server (No).

IsPortableDevice Whether the database server is running on a laptop, notebook, or other portable device.

VMWare is not taken into account, so the value is No for a database server running on a VM
that is running on a laptop.

On Windows, if it is not possible to determine whether the device is portable, the value is
NULL.

This property is always NULL on Unix.

IsRsaAvailable Whether the RSA DLL is installed.

IsRuntimeServer This property is No for all versions of the database server.

IsService Whether the database server is running as a service.

JavaVM An empty string if the database server uses one Java VM per database. If the database server
uses one Java VM for all databases, this property indicates the path to the JAVA executable.

Language The locale language for the server.

LastConnectionProperty The number that represents the last connection property.

LastDatabaseProperty The number that represents the last database property.

LastOption The number that represents the last connection property that corresponds to a database op­
tion.

LastServerProperty The number that represents the last server property.

LegalCopyright The copyright string for the software.

LegalTrademarks The trademark information for the software.

LicenseCount The number of licensed seats or processors.

LicensedCompany The name of the licensed company.

SAP IQ SQL Reference


SQL Functions INTERNAL 243
Property name Description

LicensedUser The name of the licensed user.

LicenseKey Reserved for system use.

LicenseType The license type. Can be networked seat (per-seat) or CPU-based.

LivenessTimeout The client liveness timeout default.

LockedCursorPages The number of pages used to keep cursor heaps pinned in memory.

LockedHeapPages The number of heap pages locked in the cache.

MachineName The name of the computer running a database server. Typically, this is the computer's host
name.

MainHeapBytes The number of bytes used for global server data structures.

MainHeapPages The number of pages used for global server data structures.

MapPhysicalMemoryEng The number of database page address space windows mapped to physical memory in the
cache using Address Windowing Extensions.

MaxCacheSize The maximum cache size allowed, in kilobytes.

MaxConnections The maximum number of concurrent connections that the database server allows. For the net­
work database servers the default depends upon your license. The default value can be low­
ered using the -gm server option.

MaxEventType The maximum valid event type ID.

MaxMessage This property is deprecated. The current maximum line number that can be retrieved from the
database server messages window. This represents the most recent message displayed in the
database server messages window.

MaxMirrorBackground­ The highest number of workers used for database mirroring background tasks since the server
Workers started. These workers are separate from those controlled by the multiprogramming level.

MaxMultiProgrammingLe­ The maximum number of tasks that the database server can process concurrently. When Au­
vel toMultiProgrammingLevel is enabled, the server may increase the multiprogramming level up
to this value.

MaxRemoteCapability The maximum valid capability ID.

SAP IQ SQL Reference


244 INTERNAL SQL Functions
Property name Description

Message,linenumber A line from the database server messages window, prefixed by the date and time the message
appeared. The second parameter specifies the line number. This property is deprecated.

The value for PROPERTY( "message" ) is the first line of output that was written to the
database server messages window. Calling PROPERTY( "message", n ) The nth line of
server output (with zero being the first line). The buffer is finite, so as messages are generated,
the first lines are dropped and may no longer be available in memory. In this case, the value is
NULL.

MessageCategoryLimit The minimum number of messages of each severity and category that can be retrieved using
the sa_server_messages system procedure. The default value is 400.

MessageText, This property is deprecated. The text associated with the specified line number in the data­
linenumber base server messages window, without a date and time prefix. The second parameter specifies
the line number.

MessageTime, This property is deprecated. The date and time associated with the specified line number in
linenumber the database server messages window. The second parameter specifies the line number.

MessageWindowSize This property is deprecated. The maximum number of lines that can be retrieved from the da­
tabase server messages window.

MinCacheSize The minimum cache size allowed, in kilobytes.

MinMultiProgrammingLe­ The minimum number of tasks that the server can process concurrently. When AutoMulti­
vel ProgrammingLevel is enabled, the server may decrease the multiprogramming level down to
this value.

MultiPacketsReceived The number of multi-packet requests received during client/server communications.

MultiPacketsSent The number of multi-packet responses sent during client/server communications.

MultiPageAllocs The number of multi-page cache allocations.

MultiProgrammingLevel The current maximum number of concurrent tasks the server will process simultaneously. Re­
quests are queued if there are more concurrent tasks than this value. This can be changed
with the -gn server option.

Name The alternate name of the server used to connect to the database if one was specified, other­
wise, The real server name.

If the client is connected to a copy node and specified NodeType=COPY in the connection
string, then the value of this property may be different than the database server name speci­
fied in the client connection string by the ServerName connection parameter.

SAP IQ SQL Reference


SQL Functions INTERNAL 245
Property name Description

NativeProcessorArchitec­ A string that identifies the native processor type on which the software is running. For plat­
ture forms where a processor can be emulated (such as x86 on x64), the actual processor type -
not the OS architecture type - is returned.

The value does not indicate whether the operating system is 32-bit or 64-bit.

Values can include:

● Windows - X86 or X86_64


● Solaris - SPARC or X86_64
● AIX - PPC
● HP - IA64
● Linux - X86 or X86_64

X86 represents a 32-bit hardware architecture. X86_64 represents a 64-bit hardware architec­
ture.

NumLogicalProcessors The number of logical processors (including cores and hyperthreads) enabled on the server
computer.

NumLogicalProcessor­ The number of logical processors the database server will use. On Windows, use the -gtc op­
sUsed tion to change the number of logical processors used.

NumPhysicalProcessors The number of physical processors enabled on the server computer. This value is NumLogical­
Processors divided by the number of cores or hyperthreads per physical processor. On some
non-Windows platforms, cores or hyperthreads may be counted as physical processors.

NumPhysicalProcessor­ The number of physical processors the database server will use. On Windows, you can use the
sUsed -gt option to change the number of physical processors used by the network database server.

ObjectType The type of database object. This value is used by the SYSOBJECT system view.

ODataAddresses A semicolon-delimited list of the TCP/IP addresses and ports that the OData server is using to
listen for OData connections.

ODataSecureAddresses A semicolon-delimited lists of TCP/IP address and ports that the OData server is using to lis­
ten for secure OData connections.

OmniIdentifier Reserved for system use.

PacketsReceived The number of client/server communication packets received. This value is not updated for
HTTP or HTTPS connections.

PacketsReceivedUncomp The number of packets that would have been received during client/server communications if
compression was disabled. (This value is the same as the value for PacketsReceived if com­
pression is disabled.)

PacketsSent The number of client/server communication packets sent. This value is not updated for HTTP
or HTTPS connections.

SAP IQ SQL Reference


246 INTERNAL SQL Functions
Property name Description

PacketsSentUncomp The number of packets that would have been sent during client/server communications if
compression was disabled. (This value is the same as the value for PacketsSent if compres­
sion is disabled.)

PageSize The size of the database server cache pages. This can be set using the -gp option, otherwise, it
is the maximum database page size of the databases specified on the command line.

ParameterizationPrepare­ The number of prepares for statements that have been automatically parameterized.
Count

PeakCacheSize The largest value the cache has reached in the current session, in kilobytes.

PlanStatisticsStored For internal use only.

PlanStatisticsStoredMax For internal use only.

Platform The operating system on which the software is running.

PlatformVer The operating system on which the software is running, including build numbers, service
packs, and so on.

PrepStmt The number of prepared statements currently being maintained by the database server for all
databases and connections.

ProcessCPU The CPU usage for the database server process. Values are in seconds. This property is sup­
ported on Windows and Unix computers.

The value is cumulative since the database server was started. The value will not match the
instantaneous value displayed in applications such as the Windows Task Manager or the Win­
dows Performance Monitor.

ProcessCPU, ProcessCPUSystem, and ProcessCPUUser have a fairly poor resolution on Win­


dows. For example, if the resolution is 0.015625 seconds (1/64 second), it means you could
execute some queries thousands of times before the value changes.

ProcessCPUSystem The CPU usage for the database server process CPU. This is the amount of CPU time that the
database server spent inside the operating system kernel. Values are in seconds. This property
is supported on Windows and Unix computers.

The value is cumulative since the database server was started. The value will not match the
instantaneous value displayed in applications such as the Windows Task Manager or the Per­
formance Monitor.

ProcessCPU, ProcessCPUSystem, and ProcessCPUUser have a fairly poor resolution on Win­


dows. For example, if the resolution is 0.015625 seconds (1/64 second), it means you could
execute some queries thousands of times before the value changes.

SAP IQ SQL Reference


SQL Functions INTERNAL 247
Property name Description

ProcessCPUUser User CPU usage for the database server process. Values are in seconds. This excludes the
amount of CPU time that the database server spent inside the operating system kernel. This
property is supported on Windows and Unix computers.

The value is cumulative since the database server was started. The value will not match the
instantaneous value displayed in applications such as the Windows Task Manager or the Per­
formance Monitor.

ProcessCPU, ProcessCPUSystem, and ProcessCPUUser have a fairly poor resolution on Win­


dows. For example, if the resolution is 0.015625 seconds (1/64 second), it means you could
execute some queries thousands of times before the value changes.

ProcessID The process ID of the database server process.

ProcessorAffinity The logical processors being used by the database server as specified by the -gta option or by
the sa_server_option system procedure and the ProcessorAffinity option.

ProcessorArchitecture A string that identifies the processor type that the current software was built for. Values in­
clude:

● Windows X86 or X86_64


● Solaris - SPARC or X86_64
● AIX - PPC
● HP - IA64
● Linux - X86 or X86_64

X86 represents a 32-bit database server. X86_64 represents a 64-bit database server.

ProductName The name of the software.

ProductVersion The version of the software being run.

ProfileFilterConn The ID of the connection being monitored if procedure profiling for a specific connection is
turned on. If profiling is not turned on, the value is an empty string.

ProfileFilterUser The user ID being monitored if procedure profiling for a specific user is turned on. If procedure
profiling for a specific user is not turned on, the value is an empty string.

PropertyHistoryList The current minimal set of properties being tracked.

PropertyHistoryListActual The current set of properties being tracked.

PropertyHistorySize Indicates either the minimum amount of time to store tracked property values or the maxi­
mum amount of memory to use to store tracked property values.

PropertyHistorySizeBytes The current amount of memory, in bytes, that is currently being used for property history
tracking.

QueryHeapPages The number of cache pages used for query processing (hash and sort operations).

QueryMemActiveCurr The number of requests actively using query memory.

SAP IQ SQL Reference


248 INTERNAL SQL Functions
Property name Description

QueryMemActiveEst The database server's estimate of the steady state average of the number of requests actively
using query memory.

QueryMemActiveMax The maximum number of requests that are allowed to actively use query memory.

QueryMemExtraAvail The amount of memory available to grant beyond the base memory-intensive grant.

QueryMemGrantBase The minimum amount of memory granted to all requests.

QueryMemGrantBaseMI The minimum amount of memory granted to memory-intensive requests.

QueryMemGrantExtra The number of query memory pages that can be distributed among active memory-intensive
requests beyond QueryMemGrantBaseMI.

QueryMemGrantFailed The total number of times a request waited for query memory, but failed to get it.

QueryMemGrantGranted The number of pages currently granted to requests.

QueryMemGrantRe­ The total number of times any request attempted to acquire query memory.
quested

QueryMemGrantWaited The total number of times any request waited for query memory.

QueryMemGrantWaiting The current number of requests waiting for query memory.

QueryMemPages The amount of memory that is available for query execution algorithms, expressed as a num­
ber of pages.

QueryMemPercentOfC­ The amount of memory that is available for query execution algorithms, expressed as a per­
ache cent of maximum cache size.

QuittingTime The shutdown time for the server. If none is specified, the value is none. If the database has
the time_zone option set, then the value is returned using the database's time zone.

RememberLastPlan Whether the database server is recording the last query optimization plan returned by the op­
timizer.

RememberLastStatement Whether the database server is recording the last statement prepared by each connection.

RemoteCapability The remote capability name associated with a given capability ID.

RemoteputWait The number of times the server had to block while sending a communication packet. Typically,
blocking only occurs if the database server is sending data faster than the client or network
can receive it. It does not indicate an error condition.

Req The number of times the server has been asked to handle a new request or continue process­
ing an existing request.

ReqCountActive The number of active requests.

SAP IQ SQL Reference


SQL Functions INTERNAL 249
Property name Description

ReqCountBlockContention The number of times that any connection has blocked due to contention for an internal server
resource.

ReqCountBlockIO The number of times that any connection has blocked while waiting for an IO request to com­
plete.

ReqCountBlockLock The number of times that any connection has blocked while waiting for a row lock held by an­
other connection.

ReqCountUnscheduled The number of times that any connection has blocked while waiting for a server thread to
process it.

ReqTimeActive The total amount of time that the server has spent directly servicing requests.

ReqTimeBlockContention The total amount of time that any connection has blocked due to contention for an internal
server resource.

ReqTimeBlockIO The total amount of time that any connection has blocked while waiting for an IO request to
complete.

ReqTimeBlockLock The total amount of time that any connection has blocked while waiting for a row lock held by
another connection.

ReqTimeUnscheduled The total amount of time that any connection has blocked while waiting for a server thread to
process it.

RequestFilterConn The ID of the connection that logging information is being filtered for. If no filtering is being
performed, the value is -1.

RequestFilterDB The ID of the database that logging information is being filtered for. If no filtering is being per­
formed, the value is -1.

RequestLogFile The name of the request logging file, or an empty string if there is no request logging.

RequestLogging The current setting for request logging. Values can be one of SQL, PLAN, HOSTVARS, PROCE­
DURES, TRIGGERS, OTHER, BLOCKS, REPLACE, ALL, or NONE.

RequestLogMaxSize The maximum size of the request log file.

RequestLogNumFiles The number of request log files being kept.

RequestsReceived The number of client/server communication requests or round trips. It is different from Pack­
etsReceived in that multi-packet requests count as one request, and liveness packets are not
included.

RequestTiming Whether logging of request timing information is turned on. The logging of request timing in­
formation is turned on using the -zt database server option.

Rlbk The number of rollback requests that have been handled.

SAP IQ SQL Reference


250 INTERNAL SQL Functions
Property name Description

SendFail The number of times that the underlying communications protocols have failed to send a
packet.

ServerEdition A space-separated list of words describing the database server type. Values include:

● Evaluation
● Developer
● Web
● Educational
● Standard
● Advanced
● Workgroup
● OEM
● Authenticated

If you have a separate license for any of the following features, then the appropriate string(s)
are added to the license string value:

● HighAvailability
● InMemory
● FIPS

ServerName The real server name (never an alternate server name). You can use this value to determine
which of the operational servers is currently acting as primary in a database mirroring configu-
ration.

SharedMemoryListener Whether the database server is accepting shared memory connections, and No otherwise.

SingleCLR The version number of the CLR if the database server uses a single CLR external environment
for all databases or NONE if the database server uses one CLR external environment per data­
base when executing CLR stored procedures.

SingleJVM Whether the database server uses a single Java VM for all databases running on the database
server (Yes), or whether the database server uses one Java VM per database when executing
Java stored procedures (No).

StartDBPermission The setting of the -gd server option, which can be one of DBA, all, or none.

StartTime The date/time that the server started. If the database has the time_zone option set, then the
value is returned using the database's time zone.

StreamsUsed The number of database server streams in use.

TcpIpAddresses A semicolon-delimited list of the IP addresses that the server is listening to for Command Se­
quence and TDS connections from clients. For example:

(::1):2638;127.0.0.1:2638

TcpIpListeners A semicolon-delimited list of IP addresses and IP address:port pairs that the database server
is using to listen for TCP/IP connections.

SAP IQ SQL Reference


SQL Functions INTERNAL 251
Property name Description

TempDir The directory in which temporary files are stored by the server.

ThreadDeadlocksAvoided The number of times a thread deadlock error was detected but not reported to client applica­
tions. When the database server starts, the value of this property is 0.

To avoid thread deadlock errors, the database server dynamically increases the multiprogram­
ming level. If the multiprogramming level cannot be increased, a thread deadlock error is re­
turned to the client application and the ThreadDeadlocksReported property is incremented.

ThreadDeadlocksReported The number of times a thread deadlock error was reported to client applications. When the da­
tabase server starts, the value of this property is 0.

TimeZoneAdjustment The number of minutes that must be added to the Coordinated Universal Time (UTC) to dis­
play time local to the server.

TopologyAwareScheduling Whether topology aware scheduling is in use.

TotalBuffers The total number of network buffers.

UniqueClientAddresses The number of unique client network addresses connected to a network server, excluding
shared memory and local TCP/IP connections. This is the number of seats currently used for
per-seat licensing.

UnschReq The number of requests that are currently queued up waiting for an available server worker.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate01 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the change in the value of the counter over time.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate02 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the change in the value of the counter over time.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate03 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the change in the value of the counter over time.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate04 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the change in the value of the counter over time.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Rate05 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the change in the value of the counter over time.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw01 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the absolute value of the counter.

SAP IQ SQL Reference


252 INTERNAL SQL Functions
Property name Description

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw02 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the absolute value of the counter.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw03 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the absolute value of the counter.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw04 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the absolute value of the counter.

UserDefinedCounter- The current value of the user-defined performance counter. The semantics of this property are
Raw05 defined by the client application. This counter can also be accessed from the Performance
Monitor. The Performance Monitor displays the absolute value of the counter.

WebClientLogFile The name of the web service client log file.

WebClientLogging Whether web service client information is being logged to a file.

6.9 SQL and External Environment User-Defined Functions

There are two mechanisms for creating user-defined functions in SAP IQ. You can use the SQL language to
write the function, or you can use the ESQL, ODBC, Java, Perl, or PHP external environments.

Do not confuse SQL UDFs with external C and C++ UDFs. External UDFs require a special license. For
information on external UDFs, see the SAP IQ Administration: User-Defined Functions manual.

In this section:

User-Defined Functions in SQL [page 254]


You can implement your own functions in SQL using the CREATE FUNCTION statement. The RETURN
statement inside the CREATE FUNCTION statement determines the data type of the function.

User-Defined Functions in Java [page 254]


Although SQL functions are useful, Java classes provide a more powerful and flexible way of
implementing user-defined functions, with the additional advantage that you can move them from the
database server to a client application if desired.

SAP IQ SQL Reference


SQL Functions INTERNAL 253
6.9.1 User-Defined Functions in SQL

You can implement your own functions in SQL using the CREATE FUNCTION statement. The RETURN
statement inside the CREATE FUNCTION statement determines the data type of the function.

Once you have created a SQL user-defined function, you can use it anywhere a built-in function of the same
data type is used.

 Note

Avoid using the CONTAINS predicate in a view that has a user-defined function, because the CONTAINS
criteria is ignored. Instead, use the LIKE predicate or issue the query outside of a view.

6.9.2 User-Defined Functions in Java

Although SQL functions are useful, Java classes provide a more powerful and flexible way of implementing
user-defined functions, with the additional advantage that you can move them from the database server to a
client application if desired.

Any class method of an installed Java class can be used as a user-defined function anywhere a built-in function
of the same data type is used.

Instance methods are tied to particular instances of a class, and so have different behavior from standard user-
defined functions.

For more information on creating Java classes, and on class methods, see Java in the Database in SAP IQ
Programming Reference.

6.10 Miscellaneous Functions

Miscellaneous functions perform operations on arithmetic, string, or date/time expressions, including the
return values of other functions.

Compatibility

SAP Adaptive Server Enterprise supports only the COALESCE, ISNULL, and NULLIF functions.

Related Information

ARGN Function [Miscellaneous] [page 271]

SAP IQ SQL Reference


254 INTERNAL SQL Functions
COALESCE Function [Miscellaneous] [page 298]
IFNULL Function [Miscellaneous] [page 388]
ISNULL Function [Miscellaneous] [page 394]
ISNUMERIC Function [Miscellaneous] [page 396]
NEWID Function [Miscellaneous] [page 432]
NULLIF Function [Miscellaneous] [page 442]
NUMBER Function [Miscellaneous] [page 443]
ROWID Function [Miscellaneous] [page 499]

6.11 Alphabetical List of Functions

This section describes each SQL function individually.

The function type, for example, Numeric or String, is indicated in brackets next to the function name.

Some of the results in the examples have been rounded or truncated.

The actual values of database object IDs, such as the object ID of a table or the column ID of a column, might
differ from the values shown in the examples.

In this section:

ABS Function [Numeric] [page 266]


Returns the absolute value of a numeric expression.

ACOS Function [Numeric] [page 267]


Returns the arc-cosine, in radians, of a numeric expression.

AES_ENCRYPT Function [String] [page 268]


Encrypts the specified values using the supplied encryption key, and returns a VARBINARY or LONG
VARBINARY.

AES_DECRYPT Function [String] [page 270]


Decrypts the string using the supplied key, and returns, by default, a VARBINARY or LONG BINARY, or
the original plaintext type.

ARGN Function [Miscellaneous] [page 271]


Returns a selected argument from a list of arguments.

ASCII Function [String] [page 272]


Returns the integer ASCII value of the first byte in a string-expression.

ASIN Function [Numeric] [page 273]


Returns the arc-sine, in radians, of a number.

ATAN Function [Numeric] [page 274]


Returns the arc-tangent, in radians, of a number.

ATAN2 Function [Numeric] [page 275]


Returns the arc-tangent, in radians, of the ratio of two numbers.

AVG Function [Aggregate] [page 277]

SAP IQ SQL Reference


SQL Functions INTERNAL 255
Computes the average of a numeric expression for a set of rows, or computes the average of a set of
unique values.

BFILE Function [Data Extraction] [page 278]


Extracts individual LONG BINARY and LONG VARCHAR cells to individual operating system files on the
server.

BIGINTTOHEX Function [Data Type Conversion] [page 280]


Returns the hexadecimal equivalent in VARCHAR(16) of a decimal integer.

BIT_LENGTH Function [String] [page 281]


Returns an unsigned 64-bit value containing the bit length of the column parameter.

BYTE_LENGTH Function [String] [page 283]


Returns the number of bytes in a string.

BYTE_LENGTH64 Function [String] [page 284]


BYTE_LENGTH64 returns an unsigned 64-bit value containing the byte length of the LONG BINARY
column parameter.

BYTE_REPLACE function [page 285]


Replaces a string with another string, and returns the new result.

BYTE_SUBSTR function [String] [page 286]


Returns a substring of a string. The substring is determined using bytes, not characters.

BYTE_SUBSTR64 and BYTE_SUBSTR Functions [String] [page 287]


BYTE_SUBSTR64 and BYTE_SUBSTR return the long binary byte substring of the LONG BINARY column
parameter.

CAST Function [Data Type Conversion] [page 288]


Returns the value of an expression converted to a supplied data type.

CEIL Function [Numeric] [page 290]


Returns the smallest integer greater than or equal to the specified expression.

CEILING Function [Numeric] [page 291]


Returns the ceiling (smallest integer not less than) of a number.

CHAR function [String] [page 292]


Returns the character with the ASCII value of a number.

CHAR_LENGTH Function [String] [page 293]


Returns the number of characters in a string.

CHAR_LENGTH64 Function [String] [page 295]


The CHAR_LENGTH64 function returns an unsigned 64-bit value containing the character length of the
LONG VARCHAR column parameter, including the trailing blanks.

CHARINDEX Function [String] [page 296]


Returns the position of the first occurrence of a specified string in another string.

COALESCE Function [Miscellaneous] [page 298]


Returns the first non-NULL expression from a list.

COL_LENGTH Function [System] [page 299]


Returns the defined length of a column.

COL_NAME Function [System] [page 300]


Returns the column name.

SAP IQ SQL Reference


256 INTERNAL SQL Functions
CONNECTION_PROPERTY Function [System] [page 302]
Returns the value of a given connection property as a string.

CONVERT Function [Data Type Conversion] [page 303]


Returns an expression converted to a supplied data type.

CORR Function [Aggregate] [page 307]


Returns the correlation coefficient of a set of number pairs.

COS Function [Numeric] [page 308]


Returns the cosine of a number, expressed in radians.

COT Function [Numeric] [page 310]


Returns the cotangent of a number, expressed in radians.

COVAR_POP Function [Aggregate] [page 311]


Returns the population covariance of a set of number pairs.

COVAR_SAMP Function [Aggregate] [page 312]


Returns the sample covariance of a set of number pairs.

COUNT Function [Aggregate] [page 314]


Counts the number of rows in a group, depending on the specified parameters.

CUME_DIST Function [Analytical] [page 315]


The CUME_DIST function is a rank analytical function that calculates the relative position of one value
among a group of rows. It returns a decimal value between 0 and 1.

DATALENGTH Function [System] [page 316]


Returns the length of the expression in bytes.

DATE Function [Date and Time] [page 318]


Converts the expression into a date, and removes any hours, minutes, or seconds.

DATEADD Function [Date and Time] [page 319]


Returns the date produced by adding the specified number of the specified date parts to a date.

DATECEILING Function [Date and Time] [page 320]


Calculates a new date, time, or datetime value by increasing the provided value up to the nearest larger
value of the specified granularity.

DATEDIFF Function [Date and Time] [page 323]


Returns the interval between two dates.

DATEFLOOR Function [Date and Time] [page 326]


Calculates a new date, time, or datetime value by reducing the provided value down to the nearest
lower value of the specified multiple with the specified granularity.

DATEFORMAT Function [Date and Time] [page 328]


Returns a string representing a date expression in the specified format.

DATENAME Function [Date and Time] [page 330]


Returns the name of the specified part (such as the month “June”) of a date/time value, as a character
string.

DATEPART Function [Date and Time] [page 331]


Returns an integer value for the specified part of a date/time value.

DATEROUND Function [Date and Time] [page 333]

SAP IQ SQL Reference


SQL Functions INTERNAL 257
Calculates a new date, time, or datetime value by rounding the provided value up or down to the
nearest multiple of the specified value with the specified granularity.

DATETIME Function [Date and Time] [page 335]


Converts an expression into a timestamp.

DAY Function [Date and Time] [page 336]


Returns an integer from 1 to 31 corresponding to the day of the month of the date specified.

DAYNAME Function [Date and Time] [page 337]


Returns the name of the day of the week from the specified date.

DAYS Function [Date and Time] [page 338]


Returns the number of days since an arbitrary starting date, returns the number of days between two
specified dates, or adds the specified <integer-expression> number of days to a given date.

DB_ID Function [System] [page 339]


Returns the database ID number.

DB_NAME Function [System] [page 341]


Returns the database name.

DB_PROPERTY Function [System] [page 342]


Returns the value of the given property.

DEGREES Function [Numeric] [page 344]


Converts a number from radians to degrees.

DENSE_RANK Function [Analytical] [page 344]


Ranks items in a group.

DIFFERENCE Function [String] [page 346]


Compares two strings, evaluates the similarity between them, and returns a value from 0 to 4.

DOW Function [Date and Time] [page 348]


Returns a number from 1 to 7 representing the day of the week of the specified date, with Sunday=1,
Monday=2, and so on.

ENCRYPT function [String] [page 349]


Encrypts the specified value using the supplied encryption key and returns a LONG BINARY value.

ERRORMSG Function [Miscellaneous] [page 353]


Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.

EVENT_CONDITION Function [System] [page 354]


Specifies when an event handler is triggered.

EVENT_CONDITION_NAME Function [System] [page 356]


Can be used to list the possible parameters for EVENT_CONDITION.

EVENT_PARAMETER Function [System] [page 357]


Provides context information for event handlers.

EXP Function [Numeric] [page 358]


Returns the exponential function, e to the power of a number.

EXP_WEIGHTED_AVG Function [Aggregate] [page 359]


Calculates an exponential weighted moving average. Weightings determine the relative importance of
each quantity that makes up the average.

FIRST_VALUE Function [Aggregate] [page 361]

SAP IQ SQL Reference


258 INTERNAL SQL Functions
Returns the first value from a set of values.

FLOOR Function [Numeric] [page 363]


Returns the floor of (largest integer not greater than) a number.

GETDATE Function [Date and Time] [page 364]


Returns the current date and time.

GRAPHICAL_PLAN Function [String] [page 365]


Returns the graphical query plan to Interactive SQL in an XML format string.

GROUPING Function [Aggregate] [page 367]


Identifies whether a column in a ROLLUP or CUBE operation result set is NULL because it is part of a
subtotal row, or NULL because of the underlying data.

GROUP_MEMBER Function [System] [page 368]


Identifies whether the user belongs to the specified group.

HEXTOBIGINT Function [Data Type Conversion] [page 369]


Returns the BIGINT equivalent of a hexadecimal string.

HEXTOINT Function [Data Type Conversion] [page 370]


Returns the unsigned BIGINT equivalent of a hexadecimal string.

HOUR Function [Date and Time] [page 372]


Returns a number from 0 to 23 corresponding to the hour component of the specified date/time.

HOURS Function [Date and Time] [page 373]


Returns the number of hours since an arbitrary starting date and time, the number of whole hours
between two specified times, or adds the specified integer-expression number of hours to a time.

HTML_DECODE function [Miscellaneous] [page 375]


Decodes special character entities that appear in HTML literal strings.

HTML_ENCODE function [Miscellaneous] [page 376]


Encodes special characters within strings to be inserted into HTML documents.

HTML_PLAN Function [String] [page 378]


Returns query plans in an HTML format string.

HTTP_DECODE function [Web service] [page 379]


Decodes HTTP encoded strings. This is also known as URL decoding.

HTTP_ENCODE function [Web service] [page 380]


Encodes strings for use with HTTP. This is also known as URL encoding.

HTTP_HEADER function [Web service] [page 382]


Returns the value of an HTTP request header.

HTTP_RESPONSE_HEADER function [Web service] [page 384]


Returns the value of an HTTP response header.

HTTP_VARIABLE function [Web service] [page 386]


Returns the value of an HTTP variable.

IFNULL Function [Miscellaneous] [page 388]


Returns the first non-null expression, or NULL.

INDEX_COL Function [System] [page 389]


Returns the name of the indexed column.

SAP IQ SQL Reference


SQL Functions INTERNAL 259
INSERTSTR Function [String] [page 390]
Inserts a string into another string at a specified position.

INTTOHEX Function [Data Type Conversion] [page 391]


Returns the hexadecimal equivalent of a decimal integer.

ISDATE Function [Date and Time] [page 393]


Tests whether a string argument can be converted to a date.

ISNULL Function [Miscellaneous] [page 394]


Returns the value of the first non-NULL expression in the parameter list.

ISNUMERIC Function [Miscellaneous] [page 396]


Tests whether a string argument can be converted to a numeric.

LAG Function [Analytical] [page 397]


An interrow function that returns the value of an attribute in a previous row in the table or table
partition.

LAST_VALUE Function [Aggregate] [page 399]


Returns the last value from a set of values.

LCASE Function [String] [page 401]


Converts all characters in a string to lowercase.

LEAD Function [Analytical] [page 402]


An interrow function that returns the value of an attribute in a subsequent row in the table or table
partition.

LEFT Function [String] [page 404]


Returns a specified number of characters from the beginning of a string.

LEN Function [String] [page 405]


Takes one argument as an input of type BINARY or STRING and returns the number of characters, as
defined by the database's collation sequence, of a specified string expression, excluding trailing blanks.

LENGTH Function [String] [page 406]


Returns the number of characters in the specified string.

LN Function [Numeric] [page 408]


Returns the natural logarithm of the specified expression.

LOCATE Function [String] [page 409]


Returns the position of one string within another.

LOG Function [Numeric] [page 412]


Returns the natural logarithm of a number.

LIST Function [Aggregate] [page 413]


Returns a delimited list of values for every row in a group.

LOG10 Function [Numeric] [page 416]


Returns the base 10 logarithm of a number.

LOWER Function [String] [page 417]


Converts all characters in a string to lowercase.

LPAD Function [String] [page 418]


Left-pads a string with spaces, or a specified pattern, to make a string of a specified number of
characters in length.

SAP IQ SQL Reference


260 INTERNAL SQL Functions
LTRIM Function [String] [page 419]
Returns a string, trimmed of all the leading characters present in the trim character set.

MAX Function [Aggregate] [page 420]


Returns the maximum <expression> value found in each group of rows.

MEDIAN Function [Aggregate] [page 422]


Returns the median of an expression.

MIN Function [Aggregate] [page 423]


Returns the minimum expression value found in each group of rows.

MINUTE Function [Date and Time] [page 425]


Returns a number from 0 to 59 corresponding to the minute component of the specified date/time
value.

MINUTES Function [Date and Time] [page 425]


Returns the number of minutes since an arbitrary date and time, the number of whole minutes between
two specified times, or adds the specified integer-expression number of minutes to a time.

MOD Function [Numeric] [page 427]


Returns the remainder when one whole number is divided by another.

MONTH Function [Date and Time] [page 428]


Returns a number from 1 to 12 corresponding to the month of the given date.

MONTHNAME Function [Date and Time] [page 429]


Returns the name of the month from the specified date expression.

MONTHS Function [Date and Time] [page 430]


Returns the number of months since an arbitrary starting date/time or the number of months between
two specified date/times, or adds the specified integer-expression number of months to a date/time.

NEWID Function [Miscellaneous] [page 432]


Generates a UUID (Universally Unique Identifier) value.

NEXT_CONNECTION Function [System] [page 433]


Returns the next connection number, or the first connection if the parameter is NULL.

NEXT_DATABASE Function [System] [page 435]


Returns the next database ID number, or the first database if the parameter is NULL.

NEXT_HTTP_HEADER function [Web service] [page 437]


Returns the next HTTP header name.

NEXT_HTTP_VARIABLE function [Web service] [page 438]


Returns the next HTTP variable name.

NOW Function [Date and Time] [page 439]


Returns the current date and time. This is the historical syntax for CURRENT TIMESTAMP.

NTILE Function [Analytical] [page 440]


Distributes query results into a specified number of buckets and assigns the bucket number to each
row in the bucket.

NULLIF Function [Miscellaneous] [page 442]


Provides an abbreviated CASE expression by comparing expressions.

NUMBER Function [Miscellaneous] [page 443]


Generates numbers starting at 1 for each successive row in the results of the query.

SAP IQ SQL Reference


SQL Functions INTERNAL 261
OBJECT_ID Function [System] [page 445]
Returns the object ID.

OBJECT_NAME Function [System] [page 446]


Returns the object name.

OCTET_LENGTH Function [String] [page 447]


Returns an unsigned 64-bit value containing the byte length of the column parameter.

PATINDEX Function [String] [page 448]


Returns the starting position of the first occurrence of a specified pattern.

PERCENT_RANK Function [Analytical] [page 451]


Computes the (fractional) position of one row returned from a query with respect to the other rows
returned by the query, as defined by the ORDER BY clause.

PERCENTILE_CONT Function [Analytical] [page 453]


Given a percentile, returns the value that corresponds to that percentile. Assumes a continuous
distribution data model.

PERCENTILE_DISC Function [Analytical] [page 455]


Given a percentile, returns the value that corresponds to that percentile. Assumes a discrete
distribution data model.

PI Function [Numeric] [page 457]


Returns the numeric value pi.

POWER Function [Numeric] [page 458]


Calculates one number raised to the power of another.

PROPERTY Function [System] [page 459]


Returns the value of the specified server-level property as a string.

PROPERTY_DESCRIPTION Function [System] [page 460]


Returns a description of a property.

PROPERTY_IS_TRACKABLE function [System] [page 461]


Returns whether or not you can maintain historical data for the specified database server property by
storing its tracked values.

PROPERTY_NAME Function [System] [page 462]


Returns the name of the property with the supplied property number.

PROPERTY_NUMBER Function [System] [page 463]


Returns the property number of the property with the supplied property name.

QUARTER Function [Date and Time] [page 465]


Returns a number indicating the quarter of the year from the supplied date expression.

QUARTERSTR Function [Date and Time] [page 466]


Returns a number indicating the quarter of the year from the supplied date expression and quarter
start month.

RADIANS Function [Numeric] [page 467]


Converts a number from degrees to radians.

RAND Function [Numeric] [page 468]


Returns a DOUBLE precision, random number x, where 0 <= x <1, with an optional seed.

RANK Function [Analytical] [page 469]

SAP IQ SQL Reference


262 INTERNAL SQL Functions
Ranks items in a group.

READ_SERVER_FILE function [String] [page 471]


Reads data from the specified file on the server and returns the full or partial contents of the file as a
LONG BINARY value.

REGR_AVGX Function [Aggregate] [page 472]


Computes the average of the independent variable of the regression line.

REGR_AVGY Function [Aggregate] [page 474]


Computes the average of the dependent variable of the regression line.

REGR_COUNT Function [Aggregate] [page 476]


Returns an integer that represents the number of non-NULL number pairs used to fit the regression
line.

REGR_INTERCEPT Function [Aggregate] [page 477]


Computes the y-intercept of the linear regression line that best fits the dependent and independent
variables.

REGR_R2 Function [Aggregate] [page 479]


Computes the coefficient of determination (also referred to as R-squared or the goodness-of-fit
statistic) for the regression line.

REGR_SLOPE Function [Aggregate] [page 480]


Computes the slope of the linear regression line, fitted to non-NULL pairs.

REGR_SXX Function [Aggregate] [page 482]


Computes the slope of the linear regression line, fitted to non-NULL pairs.

REGR_SXY Function [Aggregate] [page 484]


Returns the sum of products of the dependent and independent variables. Use REGR_SXY to evaluate
the statistical validity of a regression model.

REGR_SYY Function [Aggregate] [page 485]


Returns values that can evaluate the statistical validity of a regression model.

REMAINDER Function [Numeric] [page 487]


Returns the remainder when one whole number is divided by another.

REPEAT Function [String] [page 488]


Concatenates a string a specified number of times.

REPLACE Function [String] [page 489]


Replaces all occurrences of a substring with another substring.

REPLICATE Function [String] [page 492]


Concatenates a string a specified number of times.

REVERSE Function [String] [page 493]


Takes one argument as an input of type BINARY or STRING and returns the specified string with
characters listed in reverse order.

RIGHT Function [String] [page 495]


Returns the rightmost characters of a string.

ROUND Function [Numeric] [page 496]


Rounds the <numeric-expression> to the specified <integer-expression> number of places
after the decimal point.

SAP IQ SQL Reference


SQL Functions INTERNAL 263
ROW_NUMBER Function [Analytical] [page 498]
A ranking function that returns a unique row number for each row in a window partition, restarting the
row numbering at the start of every window partition.

ROWID Function [Miscellaneous] [page 499]


Returns the internal row ID value for each row of the table.

RPAD Function [String] [page 501]


Right-pads a string with spaces or a specified pattern to make a string that is a specified number of
characters in length.

RTRIM Function [String] [page 502]


Returns a string, trimmed of all the trailing characters present in the trim character set.

SECOND Function [Date and Time] [page 503]


Returns a number from 0 to 59 corresponding to the second component of the given date/time value.

SECONDS Function [Date and Time] [page 505]


Returns the number of seconds since an arbitrary starting date and time, the number of seconds
between two times, or adds an integer amount of seconds to a time.

SIGN Function [Numeric] [page 506]


Returns the sign of a number.

SIMILAR Function [String] [page 507]


Returns an integer between 0 and 100 representing the similarity between two strings.

SIN Function [Numeric] [page 508]


Returns the sine of a number, expressed in radians.

SORTKEY Function [String] [page 509]


Generates values that can be used to sort character strings based on alternate collation rules.

SOUNDEX Function [String] [page 514]


Returns a number representing the sound of a string.

SP_HAS_ROLE Function [System] [page 515]


Returns an integer value indicating whether the invoking user has been granted a specified system
privilege or user-defined role. When used for privilege checking within user-defined stored procedures,
SP_HAS_ROLE returns an error message when a user fails a privilege check.

SPACE Function [String] [page 517]


Returns a specified number of spaces.

SQLFLAGGER Function [Miscellaneous] [page 518]


Returns the conformity of a given SQL statement to a specified standard.

SQRT Function [Numeric] [page 520]


Returns the square root of a number.

SQUARE Function [Numeric] [page 521]


Returns the square of the specified expression as a float.

STACK_TRACE function [Miscellaneous] [page 521]


Returns information about the stack trace for the current statement.

STDDEV Function [Aggregate] [page 524]


Returns the standard deviation of a set of numbers.

STDDEV_POP Function [Aggregate] [page 526]

SAP IQ SQL Reference


264 INTERNAL SQL Functions
Computes the standard deviation of a population consisting of a numeric-expression, as a DOUBLE.

STDDEV_SAMP Function [Aggregate] [page 527]


Computes the standard deviation of a sample consisting of a numeric-expression, as a DOUBLE.

STR Function [String] [page 529]


Returns the string equivalent of a number.

STR_REPLACE Function [String] [page 530]


Takes three arguments as input of type BINARY or STRING and replaces any instances of the second
string expression (<string_expr2>) that occur within the first string expression (<string_expr1>)
with a third expression (<string_expr3>).

STRING Function [String] [page 532]


Concatenates one or more strings into one large string.

STRTOUUID Function [String] [page 533]


Converts a string value to a unique identifier (UUID or GUID) value.

STUFF Function [String] [page 535]


Deletes a number of characters from one string and replaces them with another string.

SUBSTRING Function [String] [page 536]


Returns a substring of a string.

SUBSTRING64 Function [String] [page 539]


The SUBSTRING64 function returns a variable-length character string of the large object column or
variable parameter.

SUM Function [Aggregate] [page 540]


Returns the total of the specified expression for each group of rows.

SUSER_ID Function [System] [page 542]


Returns an integer user identification number.

SUSER_NAME Function [System] [page 543]


Returns the user name.

TAN Function [Numeric] [page 544]


Returns the tangent of a number.

TODAY Function [Date and time] [page 545]


Returns the current date. This is the historical syntax for CURRENT DATE.

TRIM Function [String] [page 546]


Returns a string, trimmed of all the leading and trailing characters present in the trim character set.

TRUNCNUM Function [Numeric] [page 547]


Truncates a number at a specified number of places after the decimal point.

UCASE Function [String] [page 548]


Converts all characters in a string to uppercase.

UPPER Function [String] [page 549]


Converts all characters in a string to uppercase.

USER_ID Function [System] [page 551]


Returns an integer user identification number.

USER_NAME Function [System] [page 552]


Returns the user name.

SAP IQ SQL Reference


SQL Functions INTERNAL 265
UUIDTOSTR Function [String] [page 553]
Converts a unique identifier value (UUID, also known as GUID) to a string value.

VAR_POP Function [Aggregate] [page 554]


Computes the statistical variance of a population consisting of a numeric-expression, as a DOUBLE.

VAR_SAMP Function [Aggregate] [page 556]


Computes the statistical variance of a sample consisting of a numeric-expression, as a DOUBLE.

VAREXISTS function [Miscellaneous] [page 557]


Returns 1 if a user-defined variable exists with the specified name. Returns 0 if no such variable exists.

VARIANCE Function [Aggregate] [page 558]


Returns the variance of a set of numbers.

WEEKS Function [Date and Time] [page 561]


Returns the number of weeks since an arbitrary starting date/time, returns the number of weeks
between two specified date/times, or adds the specified integer-expression number of weeks to a
date/time.

WEIGHTED_AVG Function [Aggregate] [page 563]


Calculates an arithmetically (or linearly) weighted average.

WIDTH_BUCKET Function [Numerical] [page 565]


For a given expression, the WIDTH_BUCKET function returns the bucket number that the result of this
expression will be assigned after it is evaluated.

YEAR Function [Date and Time] [page 566]


Returns a 4-digit number corresponding to the year of the given date/time.

YEARS Function [Date and Time] [page 568]


Returns a 4-digit number corresponding to the year of a given date/time, returns the number of years
between two specified date/times, or adds the specified integer-expression number of years to a date/
time.

YMD Function [Date and Time] [page 570]


Returns a date value corresponding to the given year, month, and day of the month.

6.11.1 ABS Function [Numeric]

Returns the absolute value of a numeric expression.

 Syntax

ABS ( <numeric-expression> )

Parameters

numeric-expression

The number that has the absolute value to be returned.

SAP IQ SQL Reference


266 INTERNAL SQL Functions
Returns

An absolute value of the numeric expression.

Numeric Expression Data Type Returns

INT INT

FLOAT FLOAT

DOUBLE DOUBLE

NUMERIC NUMERIC

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 66:

SELECT ABS( -66 ) FROM iq_dummy

6.11.2 ACOS Function [Numeric]

Returns the arc-cosine, in radians, of a numeric expression.

 Syntax

ACOS ( <numeric-expression> )

Parameters

numeric-expression

The cosine of the angle.

SAP IQ SQL Reference


SQL Functions INTERNAL 267
Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 1.023945:

SELECT ACOS( 0.52 ) FROM iq_dummy

Related Information

ASIN Function [Numeric] [page 273]


ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

6.11.3 AES_ENCRYPT Function [String]

Encrypts the specified values using the supplied encryption key, and returns a VARBINARY or LONG
VARBINARY.

Syntax

AES_ENCRYPT( <string-expression>, <key> )

SAP IQ SQL Reference


268 INTERNAL SQL Functions
Parameters

<string-expression> – the data to be encrypted. You can also pass binary values to AES_ENCRYPT. This
parameter is case-sensitive, even in case-insensitive databases.

<key> – the encryption key used to encrypt the <string-expression>. To obtain the original value, also use
the same key to decrypt the value. This parameter is case-sensitive, even in case-insensitive databases.

As you should for most passwords, choose a key value that is difficult to guess. Choose a value that is at least
16 characters long, contains a mix of uppercase and lowercase letters, and includes numbers and special
characters. You need this key each time you want to decrypt the data.

 Caution

Protect your key; store a copy of your key in a safe location. If you lose your key, encrypted data becomes
completely inaccessible and unrecoverable.

Usage

AES_ENCRYPT returns a VARBINARY value, which is at most 31 bytes longer than the input <string-
expression>. The value returned by this function is the ciphertext, which is not human-readable. You can use
the AES_DECRYPT function to decrypt a <string-expression> that was encrypted with the AES_ENCRYPT
function. To successfully decrypt a <string-expression>, use the same encryption key and algorithm used
to encrypt the data. If you specify an incorrect encryption key, an error is generated.

If you are storing encrypted values in a table, the column should be of data type VARBINARY or VARCHAR, and
greater than or equal to 32 bytes, so that character set conversion is not performed on the data. (Character set
conversion prevents data decryption.) If the length of the VARBINARY or VARCHAR column is fewer than 32
bytes, the AES_DECRYPT function returns an error.

The result data type of an AES_ENCRYPT function may be a LONG BINARY. If you use AES_ENCRYPT in a
SELECT INTO statement, you must have an Unstructured Data Analytics Option license, or use CAST and set
AES_ENCRYPT to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP Database Products – not supported by SAP ASE.

Related Information

AES_DECRYPT Function [String] [page 270]


REPLACE Function [String] [page 489]

SAP IQ SQL Reference


SQL Functions INTERNAL 269
AES_DECRYPT Function [String] [page 270]
REPLACE Function [String] [page 489]

6.11.4 AES_DECRYPT Function [String]

Decrypts the string using the supplied key, and returns, by default, a VARBINARY or LONG BINARY, or the
original plaintext type.

Syntax

AES_DECRYPT( <string-expression>, <key> [, <data-type> ] )

Parameters

<string-expression> – the string to be decrypted. You can also pass binary values to this function. This
parameter is case sensitive, even in case-insensitive databases.

<key> – the encryption key required to decrypt the <string-expression>. To obtain the original value that
was encrypted, the key must be the same encryption key that was used to encrypt the <string-
expression>. This parameter is case-sensitive, even in case-insensitive databases.

 Caution

Protect your key; store a copy of your key in a safe location. If you lose your key, the encrypted data
becomes completely inaccessible and unrecoverable.

<data-type> – this optional parameter specifies the data type of the decrypted <string-expression> and
must be the same data type as the original plaintext.

If you do not use a CAST statement while inserting data using the AES_ENCRYPT function, you can view the
same data using the AES_DECRYPT function by passing VARCHAR as the <data-type>. If you do not pass
<data-type> to AES_DECRYPT, VARBINARY data type is returned.

Usage

You can use the AES_DECRYPT function to decrypt a <string-expression> that was encrypted with the
AES_ENCRYPT function. This function returns a VARBINARY or LONG VARBINARY value with the same number
of bytes as the input string, if no data type is specified. Otherwise, the specified data type is returned.

To successfully decrypt a <string-expression>, you must use the same encryption key that was used to
encrypt the data. An incorrect encryption key returns an error.

SAP IQ SQL Reference


270 INTERNAL SQL Functions
Example

Decrypt the password of a user from the user_info table.

SELECT AES_DECRYPT(user_pwd, '8U3dkA', CHAR(100))


FROM user_info;

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP Database Products – not supported by SAP ASE.

Related Information

AES_ENCRYPT Function [String] [page 268]


REPLACE Function [String] [page 489]
AES_ENCRYPT Function [String] [page 268]
REPLACE Function [String] [page 489]

6.11.5 ARGN Function [Miscellaneous]

Returns a selected argument from a list of arguments.

 Syntax

ARGN ( <integer-expression>, <expression> [ , …] )

Parameters

integer-expression

The position of an argument within a list of expressions.


expression

An expression of any data type passed into the function. All supplied expressions must be of the same data
type.

SAP IQ SQL Reference


SQL Functions INTERNAL 271
Returns

Using the value of the <integer-expression> as <n>, returns the <n>th argument (starting at 1) from the
remaining list of arguments.

Remarks

Using the value of <integer-expression> as <n> returns the <n>th argument (starting at 1) from the
remaining list of arguments. While the expressions can be of any data type, they must all be of the same data
type. The integer expression must be from one to the number of expressions in the list or NULL is returned.
Multiple expressions are separated by a comma.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 6:

SELECT ARGN( 6, 1,2,3,4,5,6 ) FROM iq_dummy

6.11.6 ASCII Function [String]

Returns the integer ASCII value of the first byte in a string-expression.

 Syntax

ASCII ( <string-expression> )

Parameters

string-expression

The string.

SAP IQ SQL Reference


272 INTERNAL SQL Functions
Returns

SMALLINT

Remarks

If the string is empty, ASCII returns zero. Literal strings must be enclosed in quotes.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 90, when the collation sequence is set to the default ISO_BINENG:

SELECT ASCII( 'Z' ) FROM iq_dummy

6.11.7 ASIN Function [Numeric]

Returns the arc-sine, in radians, of a number.

 Syntax

ASIN ( <numeric-expression> )

Parameters

numeric-expression

The sine of the angle.

SAP IQ SQL Reference


SQL Functions INTERNAL 273
Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 0.546850:

SELECT ASIN( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

6.11.8 ATAN Function [Numeric]

Returns the arc-tangent, in radians, of a number.

 Syntax

ATAN ( <numeric-expression> )

Parameters

numeric-expression

SAP IQ SQL Reference


274 INTERNAL SQL Functions
The tangent of the angle.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 0.479519:

SELECT ATAN( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN2 Function [Numeric] [page 275]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

6.11.9 ATAN2 Function [Numeric]

Returns the arc-tangent, in radians, of the ratio of two numbers.

 Syntax

ATAN2 ( <numeric-expression1>, <numeric-expression2> )

SAP IQ SQL Reference


SQL Functions INTERNAL 275
Parameters

numeric-expression1

The numerator in the ratio whose arc tangent is calculated.


numeric-expression2

The denominator in the ratio whose arc-tangent is calculated.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 0.00866644968879073143:

SELECT ATAN2( 0.52, 060 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

SAP IQ SQL Reference


276 INTERNAL SQL Functions
6.11.10 AVG Function [Aggregate]

Computes the average of a numeric expression for a set of rows, or computes the average of a set of unique
values.

 Syntax

AVG ( <numeric-expression> | DISTINCT <column-name>)

Parameters

numeric-expression

The value that is the average calculated over a set of rows.


DISTINCT column-name

Computes the average of the unique values in <column-name>. This is of limited usefulness, but provides
for completeness

Returns

Returns the NULL value for a group containing no rows.

Returns DOUBLE if the argument is DOUBLE, otherwise NUMERIC.

Remarks

This average does not include rows where <numeric-expression> is the NULL value. Returns the NULL
value for a group containing no rows.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 277
Example

The following statement returns the value 49988.6:

SELECT AVG ( salary ) FROM Employees

Related Information

COUNT Function [Aggregate] [page 314]


SUM Function [Aggregate] [page 540]

6.11.11 BFILE Function [Data Extraction]

Extracts individual LONG BINARY and LONG VARCHAR cells to individual operating system files on the server.

The IQ data extraction facility includes the BFILE function, which allows you to extract individual LONG
BINARY and LONG VARCHAR cells to individual operating system files on the server. You can use BFILE with or
without the data extraction facility.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

In this section:

BFILE Function [Unstructured Data Analytics] [page 278]


Extracts individual LONG BINARY and LONG VARCHAR cells to individual operating system files on the
server.

6.11.11.1 BFILE Function [Unstructured Data Analytics]

Extracts individual LONG BINARY and LONG VARCHAR cells to individual operating system files on the server.

 Syntax

BFILE( <file-name-expression>, <large-object-column> )

Parameters

file-name-expression

SAP IQ SQL Reference


278 INTERNAL SQL Functions
The name of the output file into which the LONG BINARY or LONG VARCHAR data is written. This file name
can be up to (32K -1) bytes in length, but must be a valid path name that is supported by the file system.
large-object-column

The name of the LONG BINARY or LONG VARCHAR column.

Returns

● 1, if the file is successfully written


● 0, if the file is not successfully opened or written
● NULL, if the LONG BINARY or LONG VARCHAR cell value is NULL

Remarks

If the LONG BINARY or LONG VARCHAR cell value is NULL, no file is opened and no data is written.

The file path is relative to where the server was started and the open and write operations execute with the
permissions of the server process. Tape devices are not supported for the BFILE output file.

LONG BINARY and LONG VARCHAR cells retrieved other than with the BFILE function (that is, retrieved
through the client/server database connection later) are limited in size to a maximum length of 2 GB. Use
SUBSTRING64 or BYTE_SUBSTR64 to retrieve LONG BINARY cells greater than 2 GB using a SELECT (SELECT,
OPEN CURSOR). Use SUBSTRING64 to retrieve LONG VARCHAR cells greater than 2 GB using a SELECT
(SELECT, OPEN CURSOR). Some connection drivers, for example ODBC, JDBC, and Open Client, do not allow
more than 2 GB to be returned in one SELECT.

You can use BFILE with or without the data extraction facility.

Examples

1. Create table LobA:

create table LobA


(rowid int primary key,
col1 clob null,
col2 blob null)

Assume LobA has two rows of data.


2. Extract the non-LOB data and the paths to the files into which the LOB data is extracted:

BEGIN
SET TEMPORARY OPTION
Temp_Extract_Name1 = LobA_data.txt';
SELECT rowid,
'row' + string(rowid) + '.' + 'col1',
'row' + string(rowid) + '.' + 'col2'
FROM LobA;

SAP IQ SQL Reference


SQL Functions INTERNAL 279
END

The file LobA_data.txt is created and contains this non-LOB data and these filenames:

1,row1.col1,row1.col2,
2,row2.col1,row2.col2,

3. Perform the LOB data extraction:

SELECT
BFILE('row' + string(rowid) + '.' + 'col1',col1),
BFILE('row' + string(rowid) + '.' + 'col2',col2)
FROM LobA;

After the extraction, there is a file for each cell of LOB data extracted. For example, if table LobA contains
two rows of data with rowid values of 1 and 2, you have these files:
○ row1.col1
○ row1.col2
○ row2.col1
○ row2.col2
4. Reload the extracted data:

LOAD TABLE LobA


(rowid,
col1 ASCII FILE (',') NULL('NULL'),
col2 BINARY FILE (',') NULL('NULL'))
FROM LobA_data.txt'
DELIMITED BY ','
ROW DELIMITED BY '\n'
ESCAPES OFF;

6.11.12 BIGINTTOHEX Function [Data Type Conversion]

Returns the hexadecimal equivalent in VARCHAR(16) of a decimal integer.

 Syntax

BIGINTTOHEX ( <integer-expression> )

Parameters

integer-expression

The integer to be converted to hexadecimal.

SAP IQ SQL Reference


280 INTERNAL SQL Functions
Remarks

BIGINTTOHEX accepts an integer expression that evaluates to BIGINT and returns the hexadecimal
equivalent. Returned values are left appended with zeros up to a maximum of 16 digits. All types of unscaled
integer data types are accepted as integer expressions.

Conversion is done automatically, if required. Constants are truncated, only if the fraction values are zero. A
column cannot be truncated, if the column is declared with a positive scale value. If conversion fails, SAP IQ
returns an error unless the CONVERSION_ERROR option is OFF. In that case, the result is NULL.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● Returns the value 0000000000000009:

SELECT BIGINTTOHEX(9) FROM iq_dummy

● Returns the value FFFFFFFFFFFFFFF7:

SELECT BIGINTTOHEX (-9) FROM iq_dummy

Related Information

HEXTOBIGINT Function [Data Type Conversion] [page 369]


HEXTOINT Function [Data Type Conversion] [page 370]
INTTOHEX Function [Data Type Conversion] [page 391]

6.11.13 BIT_LENGTH Function [String]

Returns an unsigned 64-bit value containing the bit length of the column parameter.

 Syntax

BIT_LENGTH( <column-name> )

SAP IQ SQL Reference


SQL Functions INTERNAL 281
Parameters

column-name

The name of a column

Returns

INT

Remarks

The return value of a NULL argument is NULL.

The BIT_LENGTH function supports all SAP IQ data types.

Unstructured Data Analytics


If you are licensed to use the Unstructured Data Analytics functionality the BIT_LENGTH function returns an
unsigned 64-bit value containing the bit length of the large object column or variable parameter. Use the
following syntax, where <large-object-column> is the name of a LONG VARCHAR or LONG BINARY column
or variable:

BIT_LENGTH( <large-object-column> )

The BIT_LENGTH function supports all SAP IQ data types and LONG BINARY and LONG VARCHAR variables of
any size of data, and returns an unsigned 64-bit value containing the bit length of the large object column or
variable parameter.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Related Information

BYTE_LENGTH Function [String] [page 283]


CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]

SAP IQ SQL Reference


282 INTERNAL SQL Functions
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.14 BYTE_LENGTH Function [String]

Returns the number of bytes in a string.

 Syntax

BYTE_LENGTH ( <string-expression> )

Parameters

string-expression

The string that has the length to be calculated.

Returns

INT

Remarks

Trailing white space characters are included in the length returned.

The return value of a NULL string is NULL.

If the string is in a multibyte character set, the BYTE_LENGTH value differs from the number of characters
returned by CHAR_LENGTH.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data. The BYTE_LENGTH function supports both LONG BINARY columns and variables and LONG
VARCHAR columns and variables, only if the query returns less than 2 GB. If the byte length of the returned
LONG BINARY or LONG VARCHAR data is greater than or equal to 2 GB, BYTE_LENGTH returns an error that
says you must use the BYTE_LENGTH64 function.

SAP IQ SQL Reference


SQL Functions INTERNAL 283
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

Returns the value 12:

SELECT BYTE_LENGTH( 'Test Message' ) FROM iq_dummy

Related Information

BIT_LENGTH Function [String] [page 281]


CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.15 BYTE_LENGTH64 Function [String]

BYTE_LENGTH64 returns an unsigned 64-bit value containing the byte length of the LONG BINARY column
parameter.

BYTE_LENGTH64 also supports the LONG VARCHAR data type and LONG BINARY and LONG VARCHAR variables
of any data size.

Unstructured Data Analytics


If you are licensed to use the Unstructured Data Analytics functionality, the BYTE_LENGTH64 function returns
an unsigned 64-bit value containing the byte length of the large object column or variable parameter. Use the
following syntax, where <large-object-column> is the name of a LONG VARCHAR or LONG BINARY column
or variable:

BYTE_LENGTH64( <large-object-column> )

The BYTE_LENGTH64 function supports both LONG BINARY and LONG VARCHAR columns and LONG BINARY
and LONG VARCHAR variables of any size of data.

SAP IQ SQL Reference


284 INTERNAL SQL Functions
See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.16 BYTE_REPLACE function

Replaces a string with another string, and returns the new result.

 Syntax

BYTE_REPLACE( <source-string>, <search-string>, <replace-string> )

Parameters

source-string

The string to be searched.


search-string

The string to be searched for and replaced by <replace-string>. <search-string> is limited to 255
bytes. If <search-string> is an empty string, then <source-string> is returned unchanged.
replace-string

The string that replaces all instances of <search-string>. If <replacement-string> is an empty


string, then all occurrences of <search-string> are deleted.

Returns

LONG BINARY

 Example

The following statement returns the binary value 0x78782e6465662e78782e676869 which is the
hexadecimal representation of the string xx.def.xx.ghi:

SELECT BYTE_REPLACE( 'abc.def.abc.ghi', 'abc', 'xx' );

SAP IQ SQL Reference


SQL Functions INTERNAL 285
6.11.17 BYTE_SUBSTR function [String]

Returns a substring of a string. The substring is determined using bytes, not characters.

 Syntax

BYTE_SUBSTR( <source-string>, <start-position> [, <length> ] )

Parameters

source-string

The data from which the binary substring is taken.


start-position

An integer expression indicating the start of the substring. A positive integer starts from the beginning of
the data, with the first byte being position 1. A negative integer specifies a substring starting from the end
of the data, the final byte 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 or LONG BINARY, depending on the length of the result.

Remarks

Both <start-position> and <length> can be either positive or negative. Use appropriate combinations of
negative and positive numbers, to get a substring from either the beginning or end of the string. If <length> is
specified, the maximum length of the substring is ABS(<length>).

If <start-position> is zero and length is non-negative, then a <start-position> value of 1 is used. If


<start-position> is zero and <length> is negative, then a start value of -1 is used.

The argument <source-string> can be any data type that can be converted to a binary data type, and is
treated as a binary string.

SAP IQ SQL Reference


286 INTERNAL SQL Functions
 Example

The following statement returns the binary value 0x54657374 which is the hexadecimal representation of
Test:

SELECT BYTE_SUBSTR( 'Test Message', 1, 4 );

6.11.18 BYTE_SUBSTR64 and BYTE_SUBSTR Functions


[String]

BYTE_SUBSTR64 and BYTE_SUBSTR return the long binary byte substring of the LONG BINARY column
parameter.

The BYTE_SUBSTR64 and BYTE_SUBSTR functions also support the LONG VARCHAR data type and LONG
BINARY and LONG VARCHAR variables of any data size.

CHAR_LENGTH64 also supports LONG VARCHAR variables of any data size.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

In this section:

BYTE_SUBSTR64 and BYTE_SUBSTR Functions [Unstructured Data Analytics] [page 287]


The BYTE_SUBSTR64 and BYTE_SUBSTR functions return the byte substring of the large object column
or variable parameter.

6.11.18.1 BYTE_SUBSTR64 and BYTE_SUBSTR Functions


[Unstructured Data Analytics]

The BYTE_SUBSTR64 and BYTE_SUBSTR functions return the byte substring of the large object column or
variable parameter.

 Syntax

Syntax 1

BYTE_SUBSTR64( <large-object-column>, <start>, <length> )

Syntax 2

BYTE_SUBSTR( <large-object-column>, <start>, <length> )

SAP IQ SQL Reference


SQL Functions INTERNAL 287
Parameters

large-object-column

The name of a LONG VARCHAR or LONG BINARY column or variable.


start

An integer expression indicating the start of the substring. A positive integer starts from the beginning of
the string, with the first byte at position 1. A negative integer specifies a substring starting from the end of
the string, with the final byte at position -1.
length

An integer expression indicating the length of the substring. A positive length specifies the number of bytes
to return, starting at the <start> position. A negative length specifies the number of bytes to return,
ending at the <start> position.

Remarks

Nested operations of the functions BYTE_LENGTH64, BYTE_SUBSTR64, and BYTE_SUBSTR do not support
large object columns or variables.

The BYTE_SUBSTR64 and BYTE_SUBSTR functions support both LONG BINARY and LONG VARCHAR columns
and LONG BINARY and LONG VARCHAR variables of any size of data. Currently, a SQL variable can hold up to 2
GB - 1 in length.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.19 CAST Function [Data Type Conversion]

Returns the value of an expression converted to a supplied data type.

 Syntax

CAST ( <expression> AS <data type> )

Parameters

expression

The expression to be converted.


data type

The data type to cast the expression into. Set the data type explicitly, or specify the %TYPE attribute to set
the data type to the data type of a column in a table or view, or to the data type of a variable.

SAP IQ SQL Reference


288 INTERNAL SQL Functions
Returns

The specified data type.

Remarks

If you do not indicate a length for character string types, SAP IQ chooses an appropriate length. If neither
precision nor scale is specified for a DECIMAL conversion, the database server selects appropriate values.

Set the data type explicitly, or specify the %TYPE attribute to set the data type to the data type of a column in a
table or view, or to the data type of a variable. For example:

SELECT CAST( NULL AS NUMERIC ) A,


CAST( NULL AS NUMERIC(15,2) ) B

is described as:

A NUMERIC(1,0)
B NUMERIC(15,2)

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following function ensures a string is used as a date:

CAST( '2000-10-31' AS DATE )

● The following is the value of the expression 1 + 2. The data type to cast the expression into. Set the data
type is calculated, and the result cast into a single-character string, the length the data server assigns:

CAST( 1 + 2 AS CHAR )

● You can use the CAST function to shorten strings:

SELECT CAST( lname AS CHAR(5) ) FROM Customers

Related Information

%TYPE and %ROWTYPE attributes [page 93]

SAP IQ SQL Reference


SQL Functions INTERNAL 289
CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]
DAYS Function [Date and Time] [page 338]
GRAPHICAL_PLAN Function [String] [page 365]
HTML_PLAN Function [String] [page 378]

6.11.20 CEIL Function [Numeric]

Returns the smallest integer greater than or equal to the specified expression.

 Syntax

CEIL ( <numeric-expression> )

Parameters

numeric-expression

A column, variable, or expression with a data type that is either exact numeric, approximate numeric,
money, or any type that can be implicitly converted to one of these types. For other data types, CEIL
generates an error. The return value has the same data type as the value supplied.

Remarks

CEIL is as synonym for CEILING.

For a given expression, the CEIL function takes one argument. For example, CEIL (-123.45) returns -123.
CEIL (123.45) returns 124.

SAP IQ SQL Reference


290 INTERNAL SQL Functions
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Related Information

FLOOR Function [Numeric] [page 363]


CEILING Function [Numeric] [page 291]

6.11.21 CEILING Function [Numeric]

Returns the ceiling (smallest integer not less than) of a number.

 Syntax

CEILING ( <numeric-expression> )

Parameters

numeric-expression

The number that has the ceiling to be calculated.

Returns

DOUBLE

Remarks

CEIL is a synonym for CEILING.

SAP IQ SQL Reference


SQL Functions INTERNAL 291
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 60.00000:

SELECT CEILING( 59.84567 ) FROM iq_dummy

● The following statement returns the value 123:

SELECT CEILING( 123 ) FROM iq_dummy

● The following statement returns the value 124.00:

SELECT CEILING( 123.45 ) FROM iq_dummy

● The following statement returns the value -123.00:

SELECT CEILING( -123.45 ) FROM iq_dummy

Related Information

FLOOR Function [Numeric] [page 363]


CEIL Function [Numeric] [page 290]

6.11.22 CHAR function [String]

Returns the character with the ASCII value of a number.

 Syntax

CHAR ( <integer-expression> )

Parameters

integer-expression

The number to be converted to an ASCII character. The number must be in the range 0 to 255, inclusive.

SAP IQ SQL Reference


292 INTERNAL SQL Functions
Returns

VARCHAR

Remarks

The character in the current database character set corresponding to the supplied numeric expression modulo
256 is returned.

CHAR returns NULL for integer expressions with values greater than 255 or less than zero.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value “Y”:

SELECT CHAR( 89 ) FROM iq_dummy

● The following statement returns the value “S”:

SELECT CHAR( 83 ) FROM iq_dummy

6.11.23 CHAR_LENGTH Function [String]

Returns the number of characters in a string.

 Syntax

CHAR_LENGTH ( <string-expression> )

Parameters

string-expression

SAP IQ SQL Reference


SQL Functions INTERNAL 293
The string that has the length to be calculated.

Returns

INT

Remarks

Trailing white space characters are included in the length returned.

The return value of a NULL string is NULL.

If the string is in a multibyte character set, the CHAR_LENGTH value may be less than the BYTE_LENGTH value.

CHAR_LENGTH64 also supports LONG VARCHAR variables of any data size.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data. The CHAR_LENGTH function supports LONG VARCHAR columns and LONG VARCHAR variables of
any size of data. If the character length exceeds 2GB - 1 (2147483647), an error is returned.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 8:

SELECT CHAR_LENGTH( 'Chemical' ) FROM iq_dummy

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]

SAP IQ SQL Reference


294 INTERNAL SQL Functions
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.24 CHAR_LENGTH64 Function [String]

The CHAR_LENGTH64 function returns an unsigned 64-bit value containing the character length of the LONG
VARCHAR column parameter, including the trailing blanks.

CHAR_LENGTH64 also supports LONG VARCHAR variables of any data size.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

In this section:

CHAR_LENGTH64 Function [Unstructured Data Analytics] [page 295]


The CHAR_LENGTH64 function returns an unsigned 64-bit value containing the character length of the
LONG VARCHAR column or variable parameter, including the trailing blanks.

6.11.24.1 CHAR_LENGTH64 Function [Unstructured Data


Analytics]

The CHAR_LENGTH64 function returns an unsigned 64-bit value containing the character length of the LONG
VARCHAR column or variable parameter, including the trailing blanks.

 Syntax

CHAR_LENGTH64( <long-varchar-object> )

Parameters

long-varchar-object

The name of a LONG VARCHAR column in a table or a LONG VARCHAR variable.

SAP IQ SQL Reference


SQL Functions INTERNAL 295
Remarks

CHAR_LENGTH64 supports LONG VARCHAR columns and LONG VARCHAR variables of any size of data.
Currently, a SQL variable can hold up to 2 GB - 1 in length.

If the argument is NULL, CHAR_LENGTH64 returns NULL.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.25 CHARINDEX Function [String]

Returns the position of the first occurrence of a specified string in another string.

 Syntax

CHARINDEX ( <string-expression1>, <string-expression2> )

Parameters

string-expression1

The string for which you are searching. This string is limited to 255 bytes.
string-expression2

The string to be searched. The position of the first character in the string being searched is 1.

Returns

INT

Remarks

All the positions or offsets, returned or specified, in the CHARINDEX function are always character offsets and
may be different from the byte offset for multibyte data.

If the string being searched:

● Contains more than one instance of the specified string, CHARINDEX returns the position of the first
instance.
● Does not contain the specified string, CHARINDEX returns zero (0).

Searching for a zero-length string returns 1.

SAP IQ SQL Reference


296 INTERNAL SQL Functions
If any of the arguments is NULL, the result is NULL.

CHARINDEX returns a 32 bit signed integer position for CHAR and VARCHAR columns.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

This example uses the following statement:

SELECT Surname, GivenName


FROM Employees
WHERE CHARINDEX('K', Surname ) = 1

The statement returns the following values:

Surname GivenName

Klobucher James

Kuo Felicia

Kelly Moira

In this section:

CHARINDEX Function [Unstructured Data Analytics] [page 298]


The CHARINDEX function returns a 64-bit signed integer containing the position of the first occurrence
of the specified string in the large object column or variable parameter. For CHAR and VARCHAR
columns, CHARINDEX returns a 32-bit signed integer position.

Related Information

SUBSTRING Function [String] [page 536]

SAP IQ SQL Reference


SQL Functions INTERNAL 297
6.11.25.1 CHARINDEX Function [Unstructured Data
Analytics]
The CHARINDEX function returns a 64-bit signed integer containing the position of the first occurrence of the
specified string in the large object column or variable parameter. For CHAR and VARCHAR columns, CHARINDEX
returns a 32-bit signed integer position.

 Syntax

CHARINDEX( <string-expression>, <large-object-column> )

Parameters

string-expression

The string of up to 255 bytes, for which you are searching.


large-object-column

The name of the LONG VARCHAR or LONG BINARY column or variable.

Remarks

● All the positions or offsets, returned or specified, in the CHARINDEX function are always character offsets
and may be different from the byte offset for multibyte data.
● If the large object cell being searched contains more than one instance of <string-expression>,
CHARINDEX returns only the position of the first instance.
● If the column does not contain the string, the CHARINDEX function returns zero (0).
● Searching for a string longer than 255 bytes returns NULL.
● Searching for a zero-length string returns 1.
● If any of the arguments is NULL, the result is NULL.
● CHARINDEX supports searching LONG VARCHAR and LONG BINARY columns and LONG VARCHAR and
LONG BINARY variables of any size of data. Currently, a SQL variable can hold up to 2 GB - 1 in length.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.26 COALESCE Function [Miscellaneous]


Returns the first non-NULL expression from a list.

 Syntax

COALESCE ( <expression>, <expression> [ , … ] )

SAP IQ SQL Reference


298 INTERNAL SQL Functions
Parameters

expression

Any expression.

Returns

ANY

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 34:

SELECT COALESCE( NULL, 34, 13, 0 ) FROM iq_dummy

Related Information

ISNULL Function [Miscellaneous] [page 394]

6.11.27 COL_LENGTH Function [System]

Returns the defined length of a column.

 Syntax

COL_LENGTH ( <table-name>, <column-name> )

SAP IQ SQL Reference


SQL Functions INTERNAL 299
Parameters

table-name

The table name.


column-name

The column name.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Example

Returns the column length 35:

SELECT COL_LENGTH ( 'CUSTOMERS', 'ADDRESS' ) FROM iq_dummy

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.28 COL_NAME Function [System]

Returns the column name.

 Syntax

COL_NAME ( <table-id>, <column-id> [ , <database-id> ] )

SAP IQ SQL Reference


300 INTERNAL SQL Functions
Parameters

table-id

The object ID of the table.


column-id

The column ID of the column.


database-id

The database ID.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Examples

● The following statement returns the column name lname:

SELECT COL_NAME( 100209, 3, 0 ) FROM iq_dummy

The object ID of the Customers table is 100209, as returned by the OBJECT_ID function. The column ID is
stored in the column_id column of the syscolumn system table. The database ID of the iqdemo database
is 0, as returned by the DB_ID function.
● The following statement returns the column name city:

SELECT COL_NAME ( 100209, 5 )FROM iq_dummy

Related Information

DB_ID Function [System] [page 339]


DB_NAME Function [System] [page 341]
DB_PROPERTY Function [System] [page 342]
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]

SAP IQ SQL Reference


SQL Functions INTERNAL 301
6.11.29 CONNECTION_PROPERTY Function [System]

Returns the value of a given connection property as a string.

 Syntax

CONNECTION_PROPERTY ( { <integer-expression1> | <string-expression> }


… [ , <integer-expression2> ] )

Parameters

integer-expression1

In most cases, it is more convenient to supply a string expression as the first argument. If you do supply
integer-expression1, it is the connection property ID. You can determine this using the
PROPERTY_NUMBER function.
string-expression

The connection property name. You must specify either the property ID or the property name.
integer-expression2

The connection ID of the current database connection. The current connection is used if this argument is
omitted.

Returns

VARCHAR

Remarks

 Note

CIS functional compensation performance considerations apply.

The current connection is used if the second argument is omitted.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


302 INTERNAL SQL Functions
Example

The following statement returns 4, the number of prepared statements being maintained:

SELECT connection_property( 'PrepStmt' )FROM iq_dummy

Related Information

PROPERTY Function [System] [page 459]


PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]
Properties Available for the Server [page 213]
Properties Available for Each Database [page 236]
Connection Properties [page 212]
sp_iqshowpsexe Procedure [page 758]
sp_iqcontext Procedure [page 624]

6.11.30 CONVERT Function [Data Type Conversion]

Returns an expression converted to a supplied data type.

 Syntax

CONVERT ( <data-type>, <expression> [ , <format-style> ] )

Parameters

data-type

The data type to convert the expression into. Set the data type explicitly, or specify the %TYPE attribute to
set the data type to the data type of a column in a table or view, or to the data type of a variable.
expression

The expression to be converted.


format-style

For converting strings to date or time data types and vice versa, format-style is a style code number that
describes the date format string to be used.

If no <format-style> argument is provided, the database option settings are used.

SAP IQ SQL Reference


SQL Functions INTERNAL 303
Returns

The data type specified.

Remarks

The result data type of a CONVERT function is a LONG VARCHAR. If you use CONVERT in a SELECT INTO
statement, you must have an Unstructured Data Analytics Option license or use CAST and set CONVERT to the
correct data type and size.

The CONVERT format style code output is as follows:

With Century
Without Century (yy) (yyyy) Output

– 0 or 100 mmm dd yyyy hh:nnAM (or PM)

1 101 mm/dd/yy[yy]

2 102 [yy]yy.mm.dd

3 103 dd/mm/yy[yy]

4 104 dd.mm.yy[yy]

5 105 dd-mm-yy[yy]

6 106 dd mmm yy[yy]

7 107 mmm dd, yy[yy]

8 108 hh:nn:ss

– 9 or 109 mmm dd yyyy hh:nn:ss:sssAM (or PM)

10 110 mm-dd-yy[yy]

11 111 [yy]yy/mm/dd

12 112 [yy]yymmdd

– 13 or 113 dd mmm yyyy hh:nn:ss:sss (24 hour clock, Europe default + millisec­
onds, 4-digit year)

14 114 hh:nn:ss (24 hour clock)

– 20 or 120 yyyy-mm-dd hh:nn:ss (24-hour clock, ODBC canonical, 4-digit year)

– 21 or 121 yyyy-mm-dd hh:nn:ss.sss (24 hour clock, ODBC canonical with millisec­
onds, 4-digit year)

36 136 hh:nn:ss.ssssssAM (or PM)

37 137 hh:nn:ss.ssssss

38 138 mmm dd yy[yy] hh:nn:ss.ssssssAM (or PM)

39 139 mmm dd yy[yy] hh:nn:ss.ssssss

40 140 [yy]yy-mm-dd hh:nn:ss.ssssss

SAP IQ SQL Reference


304 INTERNAL SQL Functions
With Century
Without Century (yy) (yyyy) Output

– 365 yyyyjjj (as a string or integer, where jjj is the Julian day number from 1 to
366 within the year)

Abbreviations and values for date parts in the CONVERT format style table:

Abbreviation Date Part Values

hh hour 0 – 23

nn minute 0 – 59

ss second 0 – 59

sss millisecond 0 – 999

ssssss microsecond 0 – 999999

mmm month Jan to Dec

dd day 1 – 31

yyyy year 0001 – 9999

mm month 1 – 12

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise and SAP SQL Anywhere, except
for format style 365, which is an SAP IQ-only extension.

Example

The following statements illustrate the use of format styles:

SELECT CONVERT( CHAR( 20 ), order_date, 104 )


FROM sales_order

order_date

16.03.1993

20.03.1993

23.03.1993

25.03.1993

...

SELECT CONVERT( CHAR( 20 ), order_date, 7 )


FROM sales_order

SAP IQ SQL Reference


SQL Functions INTERNAL 305
order_date

mar 16, 93

mar 20, 93

mar 23, 93

mar 25, 93

...

SELECT order_datetime, CONVERT(CHAR(30), order_datetime, 40)


order_datetime40,
CONVERT(CHAR(30), order_datetime, 140) order_datetime140
FROM sales_order;

order_datetime order_datetime40 order_datetime140

03/05/2009 01:03.05.123456 09-03-05 01:03:05.123456 2009-03-05 01:03:05.123456

03/05/2009 13:05.07.654321 09-03-05 13:05:07.654321 2009-03-05 13:05:07.654321

SELECT CONVERT(CHAR(50), DATETIME('2009-11-03 11:10:42.033189'), 136) FROM iq_dummy


returns 11:10:42.033189AM.

SELECT CONVERT(CHAR(50), NOW(), 137) FROM iq_dummy returns 14:54:48.794122.

The following statements illustrate the use of the format style 365, which converts data of type DATE and
DATETIME to and from either string or integer type data:

CREATE TABLE tab


(date_col DATE, int_col INT, char7_col CHAR(7));
INSERT INTO tab (date_col, int_col, char7_col)
VALUES ('Dec 17, 2004', 2004352, '2004352');

● SELECT CONVERT(VARCHAR(8), tab.date_col, 365) FROM tab; returns '2004352'.


● SELECT CONVERT(INT, tab.date_col, 365) from tab; returns 2004352.
● SELECT CONVERT(DATE, tab.int_col, 365) FROM TAB; returns 2004-12-17.
● SELECT CONVERT(DATE, tab.char7_col, 365) FROM tab; returns 2004-12-17.

The following statement illustrates conversion to an integer, and returns the value 5:

SELECT CONVERT( integer, 5.2 ) FROM iq_dummy

Related Information

%TYPE and %ROWTYPE attributes [page 93]


CAST Function [Data Type Conversion] [page 288]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]

SAP IQ SQL Reference


306 INTERNAL SQL Functions
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]

6.11.31 CORR Function [Aggregate]

Returns the correlation coefficient of a set of number pairs.

 Syntax

Syntax 1

CORR ( <dependent-expression>, <independent-expression> )

Syntax 2

CORR ( <dependent-expression>, <independent-expression> )


OVER ( <window-spec> )

Parameters

dependent-expression

The variable that is affected by the <independent-expression>.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

The CORR function converts its arguments to DOUBLE, performs the computation in double-precision floating-
point, and returns a DOUBLE as the result. If applied to an empty set, then CORR 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

SAP IQ SQL Reference


SQL Functions INTERNAL 307
either <dependent-expression> or <independent-expression> is NULL. The following computation is
made, where <x> represents the <dependent-expression> and <y> represents the <independent-
expression>:

COVAR_POP (y, x) / (STDDEV_POP (x) * STDDEV_POP (y))

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL foundation feature outside of core SQL.
● SAP database products – compatible with SAP SQL Anywhere

Example

The following example performs a correlation to discover whether age is associated with income level. This
function returns the value 0.440227:

SELECT CORR( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) ) FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.32 COS Function [Numeric]

Returns the cosine of a number, expressed in radians.

 Syntax

COS ( <numeric-expression> )

SAP IQ SQL Reference


308 INTERNAL SQL Functions
Parameters

numeric-expression

The angle, in radians.

Returns

This function converts its argument to DOUBLE, performs the computation in double-precision floating point,
and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 0.86781:

SELECT COS( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

SAP IQ SQL Reference


SQL Functions INTERNAL 309
6.11.33 COT Function [Numeric]

Returns the cotangent of a number, expressed in radians.

 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,
and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 1.74653:

SELECT COT( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]

SAP IQ SQL Reference


310 INTERNAL SQL Functions
COS Function [Numeric] [page 308]
SIN Function [Numeric] [page 508]
TAN Function [Numeric] [page 544]

6.11.34 COVAR_POP Function [Aggregate]

Returns the population covariance of a set of number pairs.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then COVAR_POP 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, where <x> represents <dependent-expression> and <y> represents <independent-
expression>:

(SUM(x*y) - SUM(x) * SUM(y) / n) / n

SAP IQ SQL Reference


SQL Functions INTERNAL 311
 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant SQL foundation feature outside of core SQL.
● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following example measures the strength of association between employee age and salary. This function
returns the value 73785.840059:

SELECT COVAR_POP( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) ) FROM


Employees;

6.11.35 COVAR_SAMP Function [Aggregate]

Returns the sample covariance of a set of number pairs.

 Syntax

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.


independent-expression

SAP IQ SQL Reference


312 INTERNAL SQL Functions
The variable that influences the outcome.
window-spec

Specified when using this function as a window function.

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then COVAR_SAMP 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, where <x> represents the
<dependent-expression> and <y> represents the <independent-expression>:

(SUM(x*y) - SUM(x) * SUM(y) / n) / (n-1)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant SQL foundation feature outside of core SQL.
● SAP database products – compatible with SAP SQL Anywhere

Example

The following example measures the strength of association between employee age and salary. This function
returns the value 74782.946005:

SELECT COVAR_SAMP( Salary, ( 2008 - YEAR( BirthDate ) ) ) FROM Employees;

SAP IQ SQL Reference


SQL Functions INTERNAL 313
6.11.36 COUNT Function [Aggregate]

Counts the number of rows in a group, depending on the specified parameters.

 Syntax

COUNT ( * | <expression> | DISTINCT <column-name> )

Parameters

Returns the number of rows in each group.

 Note

When the query results are displayed, the * is not displayed in the column header, and appears as:

Count()

expression

Returns the number of rows in each group where expression is not the NULL value.
DISTINCT column-name

Returns the number of different values in column-name. Rows where the value is the NULL value are not
included in the count.

Returns

UNSIGNED BIGINT

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

Returns each unique city, and the number of rows with that city value:

SELECT city , Count(*)

SAP IQ SQL Reference


314 INTERNAL SQL Functions
FROM Employees
GROUP BY city

Related Information

Windowing Aggregate Function Usage [page 197]


AVG Function [Aggregate] [page 277]
SUM Function [Aggregate] [page 540]

6.11.37 CUME_DIST Function [Analytical]

The CUME_DIST function is a rank analytical function that calculates the relative position of one value among a
group of rows. It returns a decimal value between 0 and 1.

 Syntax

CUME_DIST () OVER (<window-spec>)

Parameters

window-spec

Specified when using this function as a window function.

Returns

A DOUBLE value between 0 and 1.

Remarks

SAP IQ calculates the cumulative distribution of a value of x in a set S of size N using CUME_DIST(x) = number
of values in S coming before and including x in the specified order / N

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.

The <window-spec> parameter represents usage as a window function in a SELECT statement. As such, you
can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW clause in the

SAP IQ SQL Reference


SQL Functions INTERNAL 315
SELECT statement. The <window-spec> must contain the ORDER BY clause, and cannot contain a ROWS or
RANGE clause.

 Note

DISTINCT is not supported.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL feature T612.


● SAP database products – compatible with SAP SQL Anywhere.

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');

The returned result set is:

DepartmentID Surname Salary Rank

200 Savarino 72,300.000 0.333333

200 Clark 45,000.000 0.666667

200 Overbey 39,300.000 1.000000

6.11.38 DATALENGTH Function [System]

Returns the length of the expression in bytes.

 Syntax

DATALENGTH ( <expression> )

Parameters

expression

SAP IQ SQL Reference


316 INTERNAL SQL Functions
The expression is usually a column name. If the expression is a string constant, it must be enclosed in
quotes.

Returns

UNSIGNED INT

Remarks

Data Type DATALENGTH

SMALLINT 2

INTEGER 4

DOUBLE 8

CHAR Length of the data

BINARY Length of the data

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Example

Returns the value 35, the longest string in the company_name column:

SELECT MAX( DATALENGTH( company_name ) )


FROM Customers

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
LEN Function [String] [page 405]

SAP IQ SQL Reference


SQL Functions INTERNAL 317
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.39 DATE Function [Date and Time]

Converts the expression into a date, and removes any hours, minutes, or seconds.

DATE ( <expression> )

Parameters

expression

The value to be converted to date format. The expression is usually a string.

Returns

DATE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 1988-11-26 as a date:

SELECT DATE( '1988-11-26 21:20:53' ) FROM iq_dummy

SAP IQ SQL Reference


318 INTERNAL SQL Functions
6.11.40 DATEADD Function [Date and Time]

Returns the date produced by adding the specified number of the specified date parts to a date.

 Syntax

DATEADD ( <date-part>, <numeric-expression>, <date-expression> )

Parameters

date-part

The date part to be added to the date.


numeric-expression

The number of date parts to be added to the date. <numeric-expression> can be any numeric type; the
value is truncated to an integer. The maximum microsecond in <numeric-expression> is 2147483647,
that is, 35:47.483647 (35 minutes 47 seconds 483647 microseconds).
date-expression

The date to be modified.

Returns

TIMESTAMP

Remarks

DATEADD is a Transact-SQL compatible data manipulation function.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 319
Examples

● The following statement returns the value 1995-11-02 00:00:00.000:

SELECT DATEADD( MONTH, 102, '1987/05/02' ) FROM iq_dummy

● The following statement returns the value 2009-11-10 14:57:52.722016:

SELECT DATEADD(MICROSECOND, 15, '2009-11-10


14:57:52.722001') FROM iq_dummy

● The following statement returns the value 1985-05-02 00:00:00.123456:

SELECT DATEADD(MICROSECOND, 123456, '1985/05/02')


FROM iq_dummy

● The following statement returns the value 1985-05-01 23:59:59.876544:

SELECT DATEADD(MICROSECOND, -123456, '1985/05/02')


FROM iq_dummy

● The following statement returns the value 2009-11-03 11:10:42.033192:

SELECT DATEADD(MCS, 2, '2009-11-03 11:10:42.033190')


FROM iq_dummy

Related Information

DATECEILING Function [Date and Time] [page 320]


DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.41 DATECEILING Function [Date and Time]

Calculates a new date, time, or datetime value by increasing the provided value up to the nearest larger value of
the specified granularity.

 Syntax

DATECEILING ( <date-part>, <datetime-expression> [, <multiple-expression>] )

SAP IQ SQL Reference


320 INTERNAL SQL Functions
Parameters

date-part

The date part to be added to the date.


datetime-expression

The date, time, or date-time expression containing the value you are evaluating.
multiple-expression

(Optional) A nonzero positive integer value expression specifying how many multiples of the units specified
by the date-part parameter to use within the calculation. For example, you can use multiple-expression to
specify that you want to regularize your data to 200-microsecond intervals or 10-minute intervals.

If multiple-expression evaluates to zero, evaluates to a negative number, is an explicit NULL constant, or is


not a valid value for the specified date-part, SAP IQ generates an error. If multiple-expression evaluates to a
NULL, then the function result is NULL.

Remarks

This function calculates a new date, time, or datetime value by increasing the provided value up to the nearest
larger value with the specified granularity. If you include the optional <multiple-expression> parameter,
then the function increases the date and time up to the nearest specified multiple of the specified granularity.

The data type of the calculated date and time matches the data type of the <multiple-expression>
parameter.

The following date parts are not compatible with DATECEILING:

● DayofYear
● WeekDay
● CalYearofWeek
● CalWeekofYear
● CalDayofWeek

If you specify a <multiple-expression> for the microsecond, millisecond, second, minute, or hour date
parts, SAP IQ assumes that the multiple applies from the start of the next larger unit of granularity:

● Multiples of microsecond start from the current second


● Multiples of millisecond start from the current second
● Multiples of second start from the current minute
● Multiples of minute start from the current hour
● Multiples of hour start from the current day

For example, if you specify a multiple of two minutes, SAP IQ applies two-minute intervals starting at the
current hour.

For the microsecond, millisecond, second, minute, and hour date parts, specify a <multiple-expression>
value that divides evenly into the range of the specified date part:

● For hours – the valid <multiple-expression> values are: 1, 2, 3, 4, 6, 8, 12, 24

SAP IQ SQL Reference


SQL Functions INTERNAL 321
● For seconds and minutes – the valid <multiple-expression> values are: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30,
60
● For milliseconds – the valid <multiple-expression> values are: 1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125,
200, 250, 500, 1000
● For microseconds – the valid <multiple-expression> values are:

1 40 400 4000 40000


2 50 500 5000 50000
4 64 625 6250 62500
5 80 800 8000 100000
8 100 1000 10000 125000
10 125 1250 12500 200000
16 160 1600 15625 250000
20 200 2000 20000 500000
25 250 2500 25000 1000000
32 320 3125 31250

If you specify a <multiple-expression> for the day, week, month, quarter, or year date parts, SAP IQ
assumes the intervals started at the smallest date value (0001-01-01), smallest time value
(00:00:00.000000), or smallest date-time value (0001-01-01.00:00:00.000000). For example, if you specify
a multiple of 10 days, SAP IQ calculates 10-day intervals starting at 0001-01-01.

For the day, week, month, quarter, or year date parts, you don't need to specify a multiple that divides evenly
into the next larger unit of time granularity.

If SAP IQ rounds to a multiple of the week date part, the date value is always Sunday.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Examples

● This statement returns the value August 13, 2009 10:40.00.000AM:

SELECT DATECEILING( MI, 'August 13, 2009, 10:32.00.132AM', 10)


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32.35.456800 AM:

SELECT DATECEILING( US, 'August 13, 2009, 10:32.35.456789AM', 200 )


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32.35.600000 AM:

SELECT DATECEILING( US, 'August 13, 2009, 10:32.35.456789AM', 200000 )


FROM iq_dummy

SAP IQ SQL Reference


322 INTERNAL SQL Functions
● This statement returns the value August 13, 2009 10:32.35.456789 AM:

SELECT DATECEILING( US, 'August 13, 2009, 10:32.35.456789AM')


FROM iq_dummy

Related Information

DATEADD Function [Date and Time] [page 319]


DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.42 DATEDIFF Function [Date and Time]

Returns the interval between two dates.

 Syntax

DATEDIFF ( <date-part>, <date-expression1>, <date-expression2> )

Parameters

date-part

The date part in which the interval is to be measured.


date-expression1

The starting date for the interval. This value is subtracted from <date-expression2> to return the
number of date parts between the two arguments.
date-expression2

The ending date for the interval. <date-expression1> is subtracted from this value to return the number
of date parts between the two arguments.

Returns

INT

SAP IQ SQL Reference


SQL Functions INTERNAL 323
Remarks

This function calculates the number of date parts between two specified dates. The result is a signed integer
value equal to (date2 - date1), in date parts.

DATEDIFF results are truncated, not rounded, when the result is not an even multiple of the date part.

When you use day as the date part, DATEDIFF returns the number of midnights between the two times
specified, including the second date, but not the first. For example, the following statement returns the value 5.
Midnight of the first day 2003/08/03 is not included in the result. Midnight of the second day is included, even
though the time specified is before midnight:

SELECT DATEDIFF( DAY, '2003/08/03 14:00', '2003/08/08 14:00' ) FROM iq_dummy

When you use month as the date part, DATEDIFF returns the number of first-of-the-months between two
dates, including the second date but not the first. For example, both of the following statements return the
value 9:

SELECT DATEDIFF( MONTH, '2003/02/01', '2003/11/15' ) FROM iq_dummy;


SELECT DATEDIFF( MONTH, '2003/02/01', '2003/11/01' ) FROM iq_dummy;

The first date 2003/02/01 is a first-of-month, but is not included in the result of either query. The second date
2003/11/01 in the second query is also a first-of-month and is included in the result.

When you use week as the date part, DATEDIFF returns the number of Sundays between the two dates,
including the second date but not the first. For example, in the month 2003/08, the dates of the Sundays are
03, 10, 17, 24, and 31. The following query returns the value 4:

SELECT DATEDIFF( week, '2003/08/03', '2003/08/31' ) FROM iq_dummy;

The first Sunday (2003/08/03) is not included in the result.

IQ Main Store Tables Versus Catalog Store Tables


DATEDIFF semantics differ between IQ main store tables, and IQ catalog store tables (system tables). The
DATEDIFF results for time parts HOUR, MINUTE, SECOND, MILLISECOND, and MICROSECOND are calculated
differently in certain situations.

Assume you have two time values three seconds apart: 11:14:59 and 11:15:02. Notice how the time range
includes a minute boundary point (11:15:00).If you are requesting a difference unit type of MINUTE:

● IQ main store table – SAP IQ sees that the difference between the two time values is less than the MINUTE
unit type, and calculates a DATEDIFF of 0.
● IQ catalog store table – the system sees that the difference between the two time values is less than the
MINUTE unit type, but notes that the difference includes the minute boundary point (11:15:00), and
calculates a DATEDIFF of 1.

If you require IQ catalog store DATEDIFF behavior in an expression that can be executed against either IQ main
store or IQ catalog store tables, then execute the DATEDIFF over a CAST over a DATEFORMAT with an
appropriate format string (that doesn't include components smaller than the requested difference unit)
wrapped over each input:

DATEDIFF(MINUTE,
CAST(DATEFORMAT(t.col1, 'YYYY-MM-DD HH:NN’) AS TIMESTAMP),
CAST(DATEFORMAT(t.col2, 'YYYY-MM-DD HH:NN’) AS TIMESTAMP))

SAP IQ SQL Reference


324 INTERNAL SQL Functions
Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns 1:

SELECT DATEDIFF( HOUR, '4:00AM', '5:50AM' )


FROM iq_dummy

● The following statement returns 102:

SELECT DATEDIFF( MONTH, '1987/05/02', '1995/11/15' )


FROM iq_dummy

● The following statement returns 0:

SELECT DATEDIFF( DAY, '00:00', '23:59' )


FROM iq_dummy

● The following statement returns 4:

SELECT DATEDIFF( DAY, '1999/07/19 00:00', '1999/07/23


23:59' ) FROM iq_dummy

● The following statement returns 0:

SELECT DATEDIFF( MONTH, '1999/07/19', '1999/07/23' )


FROM iq_dummy

● The following statement returns 1:

SELECT DATEDIFF( MONTH, '1999/07/19', '1999/08/23' )


FROM iq_dummy

● The following statement returns 4:

SELECT DATEDIFF(MCS, '2009-11-03 11:10:42.033185',


'2009-11-03 11:10:42.033189')
FROM iq_dummy

● The following statement returns 15:

SELECT DATEDIFF(MICROSECOND, '2009-11-10


14:57:52.722001', '2009-11-10 14:57:52.722016')
FROM iq_dummy

● The following statement returns 1,500,000:

SELECT DATEDIFF(MCS, '2000/07/07/07 07:07:06.277777',


'2000/07/07/07 07:07:07.777777') FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 325
Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.43 DATEFLOOR Function [Date and Time]

Calculates a new date, time, or datetime value by reducing the provided value down to the nearest lower value
of the specified multiple with the specified granularity.

 Syntax

DATEFLOOR ( <date-part>, <datetime-expression> [, <multiple-expression> ] )

Parameters

date-part

The date part to be added to the date.


datetime-expression

The date, time, or date-time expression containing the value you are evaluating.
multiple-expression

(Optional) A nonzero positive integer value expression specifying how many multiples of the units specified
by date-part to use within the calculation. For example, you can use multiple-expression to specify that you
want to regularize your data to 200-microsecond intervals or 10-minute intervals

If multiple-expression evaluates to zero, evaluates to a negative number, is an explicit NULL constant, or is


not a valid value for the specified date-part, SAP IQ generates an error. If multiple-expression evaluates to a
NULL, then the function result is NULL.

Remarks

This function calculates a new date, time, or datetime value by reducing the provided value down to the nearest
lower value with the specified granularity. If you include the optional <multiple-expression> parameter,
then the function reduces the date and time down to the nearest specified multiple of the specified granularity.

SAP IQ SQL Reference


326 INTERNAL SQL Functions
The data type of the calculated date and time matches the data type of the <multiple-expression>
parameter.

The following date parts are not compatible with DATEFLOOR:

● DayofYear
● WeekDay
● CalYearofWeek
● CalWeekofYear
● CalDayofWeek

If you specify a <multiple-expression> for the microsecond, millisecond, second, minute, or hour date
parts, SAP IQ assumes that the multiple applies from the start of the next larger unit of granularity:

● Multiples of microsecond start from the current second


● Multiples of millisecond start from the current second
● Multiples of second start from the current minute
● Multiples of minute start from the current hour
● Multiples of hour start from the current day

For example, if you specify a multiple of two minutes, SAP IQ applies two minute intervals starting at the
current hour.

For the microsecond, millisecond, second, minute, and hour date parts, specify a <multiple-expression>
value that divides evenly into the range of the specified date part:

● For hours – the valid <multiple-expression> values are: 1, 2, 3, 4, 6, 8, 12, 24


● For seconds and minutes – the valid <multiple-expression> values are: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30,
60
● For milliseconds – the valid <multiple-expression> values are: 1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125,
200, 250, 500, 1000
● For microseconds – the valid <multiple-expression> values are:

1 40 400 4000 40000


2 50 500 5000 50000
4 64 625 6250 62500
5 80 800 8000 100000
8 100 1000 10000 125000
10 125 1250 12500 200000
16 160 1600 15625 250000
20 200 2000 20000 500000
25 250 2500 25000 1000000
32 320 3125 31250

If you specify a <multiple-expression> for the day, week, month, quarter, or year date parts, SAP IQ
assumes the intervals started at the smallest date value (0001-01-01), smallest time value
(00:00:00.000000), or smallest date-time value (0001-01-01.00:00:00.000000). For example, if you specify
a multiple of 10 days, then SAP IQ calculates 10-day intervals starting at 0001-01-01.

For the day, week, month, quarter, or year date parts, you don't need to specify a multiple that divides evenly
into the next larger unit of time granularity.

If SAP IQ rounds to a multiple of the week date part, the date value is always Sunday.

SAP IQ SQL Reference


SQL Functions INTERNAL 327
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Examples

● This statement returns the value August 13, 2009 10:35:00.000AM:

SELECT DATEFLOOR( MINUTE, 'August 13, 2009 10:35:22.123AM')


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.456600 AM:

SELECT DATEFLOOR( US, 'August 13, 2009, 10:32:35.456789AM', 200 )


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.400000 AM:

SELECT DATEFLOOR( US, 'August 13, 2009, 10:32:35.456789AM', 200000 )


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.456789 AM:

SELECT DATEFLOOR( US, 'August 13, 2009, 10:32:35.456789AM')


FROM iq_dummy

Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.44 DATEFORMAT Function [Date and Time]

Returns a string representing a date expression in the specified format.

 Syntax

DATEFORMAT ( <datetime-expression>, <string-expression> )

SAP IQ SQL Reference


328 INTERNAL SQL Functions
Parameters

datetime-expression

The date and time to be converted, in the form of a date, time, timestamp, or character string.
string-expression

The format of the converted date.

Returns

VARCHAR

Remarks

The <datetime-expression> to convert must be a date, time, or timestamp data type, but can also be a
CHAR or VARCHAR character string. If the date is a character string, SAP IQ implicitly converts the character
string to date, time, or timestamp data type, so an explicit cast, as in the example above, is unnecessary.

Any allowable date format can be used for <string-expression>. Date format strings cannot contain any
multibyte characters. Only single-byte characters are allowed in a date/time/datetime format string, even
when the collation order of the database is a multibyte collation order like 932JPN.

If '<?>' represents a multibyte character, then the following query fails:

SELECT DATEFORMAT ( start_date, 'yy?') FROM Employees;

Instead, move the multibyte character outside of the date format string using the concatenation operator:

SELECT DATEFORMAT (start_date, 'yy') + '?' FROM Employees;

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Examples

● The following statement returns string values like “Jan 01, 1989”:

SELECT DATEFORMAT( start_date, 'Mmm dd, yyyy' ) from Employees;

SAP IQ SQL Reference


SQL Functions INTERNAL 329
● The following statement returns the string “Feb 19, 1987”:

SELECT DATEFORMAT( CAST ( '1987/02/19' AS DATE ), 'Mmm Dd, yyyy' ) FROM


iq_dummy

6.11.45 DATENAME Function [Date and Time]

Returns the name of the specified part (such as the month “June”) of a date/time value, as a character string.

 Syntax

DATEMNAME ( <date-part>, <date-expression> )

Parameters

date-part

The date part to be named.


date-expression

The date for which the date part name is to be returned. The date must contain the requested date-part.

Returns

VARCHAR

Remarks

DATENAME returns a character string, even if the result is numeric, such as 23, for the day.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


330 INTERNAL SQL Functions
Examples

● The following statement returns the value May:

SELECT DATENAME( MONTH , '1987/05/02' )


FROM iq_dummy

● The following statement returns the value 722,001:

SELECT DATENAME(MICROSECOND, '2009-11-10


14:57:52.722001') FROM iq_dummy

● The following statement returns the value 777,777:

SELECT DATENAME(MICROSECOND, '2000/07/07


07:07:07.777777') FROM iq_dummy

● The following statement returns the value 33,189:

SELECT DATENAME(MCS, '2009-11-03 11:10:42.033189')


FROM iq_dummy

Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATEPART Function [Date and Time] [page 331]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.46 DATEPART Function [Date and Time]

Returns an integer value for the specified part of a date/time value.

 Syntax

DATEPART ( <date-part>, <date-expression> )

Parameters

date-part

The date part to be returned.

SAP IQ SQL Reference


SQL Functions INTERNAL 331
date-expression

The date for which the part is to be returned. The date must contain the date-part field.

Returns

INT

Remarks

The DATE, TIME, and DTTM indexes do not support some date parts (Calyearofweek, Calweekofyear,
Caldayofweek, Dayofyear, Millisecond, Microsecond).

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 5:

SELECT DATEPART( MONTH, '1987/05/02' )


FROM iq_dummy

● The following statement returns the value 722,001:

SELECT DATEPART(MICROSECOND, '2009-11-10


14:57:52.722001') FROM iq_dummy

● The following statement returns the value 777,777:

SELECT DATEPART(MICROSECOND, '2000/07/07


07:07:07.777777') FROM iq_dummy

● The following statement returns the value 33,189:

SELECT DATEPART(MCS, '2009-11-03 11:10:42.033189')


FROM iq_dummy

SAP IQ SQL Reference


332 INTERNAL SQL Functions
Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEROUND Function [Date and Time] [page 333]
Date Parts [page 205]

6.11.47 DATEROUND Function [Date and Time]

Calculates a new date, time, or datetime value by rounding the provided value up or down to the nearest
multiple of the specified value with the specified granularity.

 Syntax

DATEROUND ( <date-part>, <datetime-expression> [, <multiple-expression> ] )

Parameters

date-part

The date part to be returned.


datetime-expression

The date, time, or date-time expression containing the value you are evaluating.
multiple-expression

(Optional).= A nonzero positive integer value expression specifying how many multiples of the units
specified by date-part to use within the calculation. For example, you can use multiple-expression to
specify that you want to regularize your data to 200-microsecond intervals or 10-minute intervals.

If <multiple-expression> evaluates to zero, evaluates to a negative number, is an explicit NULL


constant, or is not a valid value for the specified <date-part>, then SAP IQ generates an error. If
<multiple-expression> evaluates to a NULL, then the function result is NULL.

Remarks

This function calculates a new date, time, or datetime value by rounding the provided value up or down to the
nearest value with the specified granularity. If you include the optional <multiple-expression> parameter,
then the function rounds the date and time to the nearest specified multiple of the specified granularity.

SAP IQ SQL Reference


SQL Functions INTERNAL 333
The data type of the calculated date and time matches the data type of the <multiple-expression>
parameter.

The following date parts are not compatible with DATEROUND:

● DayofYear
● WeekDay
● CalYearofWeek
● CalWeekofYear
● CalDayofWeek

If you specify a <multiple-expression> for the microsecond, millisecond, second, minute, or hour date
parts, SAP IQ assumes that the multiple applies from the start of the next larger unit of granularity:

● Multiples of microsecond start from the current second


● Multiples of millisecond start from the current second
● Multiples of second start from the current minute
● Multiples of minute start from the current hour
● Multiples of hour start from the current day

For example, if you specify a multiple of two minutes, SAP IQ applies two minute intervals starting at the
current hour.

For the microsecond, millisecond, second, minute, and hour date parts, specify a <multiple-expression>
value that divides evenly into the range of the specified date part:

● For hours – the valid <multiple-expression> values are: 1, 2, 3, 4, 6, 8, 12, 24


● For seconds and minutes – the valid <multiple-expression> values are: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30,
60
● For milliseconds – the valid <multiple-expression> values are: 1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125,
200, 250, 500, 1000
● For microseconds – the valid <multiple-expression> values are:

1 40 400 4000 40000


2 50 500 5000 50000
4 64 625 6250 62500
5 80 800 8000 100000
8 100 1000 10000 125000
10 125 1250 12500 200000
16 160 1600 15625 250000
20 200 2000 20000 500000
25 250 2500 25000 1000000
32 320 3125 31250

If you specify a <multiple-expression> for the day, week, month, quarter, or year date parts, SAP IQ
assumes the intervals started at the smallest date value (0001-01-01), smallest time value
(00:00:00.000000), or smallest date-time value (0001-01-01.00:00:00.000000). For example, if you specify
a multiple of 10 days, then SAP IQ calculates 10-day intervals starting at 0001-01-01.

For the day, week, month, quarter, or year date parts, you don't need to specify a multiple that divides evenly
into the next larger unit of time granularity.

If SAP IQ rounds to a multiple of the week date part, then the date value is always Sunday.

SAP IQ SQL Reference


334 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Examples

● This statement returns the value August 13, 2009, 10:30.000AM:

SELECT DATEROUND( MI, 'August 13, 2009 10:33.123AM', 10)


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.456600 AM:

SELECT DATEROUND( US, 'August 13, 2009, 10:32:35.456500AM', 200 )


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.456789 AM:

SELECT DATEROUND( US, 'August 13, 2009, 10:32:35.456789AM')


FROM iq_dummy

● This statement returns the value August 13, 2009 10:32:35.456400 AM:

SELECT DATEROUND( US, 'August 13, 2009, 10:32:35.456499AM', 200 )


FROM iq_dummy

Related Information

DATEADD Function [Date and Time] [page 319]


DATECEILING Function [Date and Time] [page 320]
DATEDIFF Function [Date and Time] [page 323]
DATEFLOOR Function [Date and Time] [page 326]
DATENAME Function [Date and Time] [page 330]
DATEPART Function [Date and Time] [page 331]
Date Parts [page 205]

6.11.48 DATETIME Function [Date and Time]

Converts an expression into a timestamp.

 Syntax

DATETIME ( <expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 335
Parameters

expression

The expression to be converted. The expression is usually a string. Conversion errors may be reported.

Returns

TIMESTAMP

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

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' ) FROM iq_dummy

6.11.49 DAY Function [Date and Time]

Returns an integer from 1 to 31 corresponding to the day of the month of the date specified.

 Syntax

DAY ( <date-expression> )

Parameters

date-expression

The date.

SAP IQ SQL Reference


336 INTERNAL SQL Functions
Returns

SMALLINT

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 12:

SELECT DAY( '2001-09-12' ) FROM iq_dummy

6.11.50 DAYNAME Function [Date and Time]

Returns the name of the day of the week from the specified date.

 Syntax

DAYNAME ( <date-expression> )

Parameters

date-expression

The date.

Returns

VARCHAR

SAP IQ SQL Reference


SQL Functions INTERNAL 337
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value Saturday:

SELECT DAYNAME ( '1987/05/02' ) FROM iq_dummy

6.11.51 DAYS Function [Date and Time]

Returns the number of days since an arbitrary starting date, returns the number of days between two specified
dates, or adds the specified <integer-expression> number of days to a given date.

 Syntax

DAYS ( <datetime-expression> )
| ( <datetime-expression>, <datetime-expression> )
| ( <datetime-expression>, <integer-expression> )

Parameters

datetime-expression

A date and time.


integer-expression

The number of days to be added to the <datetime-expression>. If the <integer-expression> is


negative, the appropriate number of days are subtracted from the date and time. If you supply an integer
expression, the <datetime-expression> must be explicitly cast as a date.

Returns

INT when you specify two datetime expressions.

TIMESTAMP when the second argument you specify is an integer.

SAP IQ SQL Reference


338 INTERNAL SQL Functions
Remarks

DAYS ignores hours, minutes, and seconds.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the integer value 729948:

SELECT DAYS( '1998-07-13 06:07:12' ) FROM iq_dummy

● The following statement returns the integer value -366, which is the difference between the two dates:

SELECT DAYS( '1998-07-13 06:07:12',


'1997-07-12 10:07:12' ) FROM iq_dummy

● The following statement returns the value 1999-07-14:

SELECT DAYS( CAST('1998-07-13' AS DATE ), 366 )


FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]

6.11.52 DB_ID Function [System]

Returns the database ID number.

 Syntax

DB_ID ( [ <database-name> ] )

SAP IQ SQL Reference


SQL Functions INTERNAL 339
Parameters

database-name

A string expression containing the database name. If database-name is a string constant, it must be
enclosed in quotes. If no database-name is supplied, the ID number of the current database is returned.

Returns

INT

Remarks

 Note

CIS functional compensation performance considerations apply.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Examples

● Returns the value 0, if iqdemo is the only running database:

SELECT DB_ID( 'iqdemo' ) FROM iq_dummy

● Returns the value 0, if executed against the only running database:

SELECT DB_ID() FROM iq_dummy

Related Information

COL_NAME Function [System] [page 300]


DB_NAME Function [System] [page 341]
DB_PROPERTY Function [System] [page 342]

SAP IQ SQL Reference


340 INTERNAL SQL Functions
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]

6.11.53 DB_NAME Function [System]

Returns the database name.

 Syntax

DB_NAME ( [ <database-id> ] )

Parameters

database-id

The ID of the database, in the form of a numeric expression.

Returns

VARCHAR

Remarks

 Note

CIS functional compensation performance considerations apply.

If no <database-id> is supplied, the name of the current database is returned.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

SAP IQ SQL Reference


SQL Functions INTERNAL 341
Example

Returns the database name iqdemo, when executed against the iq_dummy database:

SELECT DB_NAME( 0 ) FROM iq_dummy

Related Information

COL_NAME Function [System] [page 300]


DB_ID Function [System] [page 339]
DB_PROPERTY Function [System] [page 342]
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]

6.11.54 DB_PROPERTY Function [System]

Returns the value of the given property.

 Syntax

DB_PROPERTY ( { <property-id> | <property-name> }


[ , { <database-id> | <database-name> } ] )

Parameters

property-id

The database property ID.


property-name

The database property name.


database-id

The database ID number, as returned by DB_ID. Typically, the database name is used.
database-name

The name of the database, as returned by DB_NAME.

SAP IQ SQL Reference


342 INTERNAL SQL Functions
Returns

VARCHAR

Remarks

 Note

CIS functional compensation performance considerations apply.

Returns a string. The current database is used if the second argument is omitted.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the page size of the current database, in bytes:

SELECT DB_PROPERTY( 'PAGESIZE' ) FROM iq_dummy

Related Information

COL_NAME Function [System] [page 300]


DB_ID Function [System] [page 339]
DB_NAME Function [System] [page 341]
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]

SAP IQ SQL Reference


SQL Functions INTERNAL 343
6.11.55 DEGREES Function [Numeric]

Converts a number from radians to degrees.

 Syntax

DEGREES ( <numeric-expression> )

Parameters

numeric-expression

An angle in radians.

Returns

Returns the degrees of the angle given by <numeric-expression>.

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 29.793805:

SELECT DEGREES( 0.52 ) FROM iq_dummy

6.11.56 DENSE_RANK Function [Analytical]

Ranks items in a group.

 Syntax

DENSE_RANK () OVER ( ORDER BY <expression> [ ASC | DESC ] )

SAP IQ SQL Reference


344 INTERNAL SQL Functions
Parameters

expression

A sort specification that can be any valid expression involving a column reference, aggregates, or
expressions invoking these items.

Returns

INTEGER

Remarks

DENSE_RANK is a rank analytical function. The dense rank of row R is defined as the number of rows preceding
and including R that are distinct within the groups specified in the OVER clause or distinct over the entire result
set. The difference between DENSE_RANK and RANK is that DENSE_RANK leaves no gap in the ranking sequence
when there is a tie. RANK leaves a gap when there is a tie.

DENSE_RANK requires an OVER (ORDER BY) clause. The ORDER BY clause specifies the parameter on which
ranking is performed and the order in which the rows are sorted in each group. This ORDER BY clause is used
only within the OVER clause and is not an ORDER BY for the SELECT. No aggregation functions in the rank
query are allowed to specify DISTINCT.

The OVER clause indicates that the function operates on a query result set. The result set is the rows that are
returned after the FROM, WHERE, GROUP BY, and HAVING clauses have all been evaluated. The OVER clause
defines the data set of the rows to include in the computation of the rank analytical function.

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is the
default.

DENSE_RANK is allowed only in the select list of a SELECT or INSERT statement or in the ORDER BY clause of
the SELECT statement. DENSE_RANK can be in a view or a union. The DENSE_RANK function cannot be used in
a subquery, a HAVING clause, or in the select list of an UPDATE or DELETE statement. Only one rank analytical
function is allowed per query.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

SAP IQ SQL Reference


SQL Functions INTERNAL 345
Example

The following statement illustrates the use of the DENSE_RANK function:

SELECT s_suppkey, DENSE_RANK()


OVER ( ORDER BY ( SUM(s_acctBal) DESC )
AS rank_dense FROM supplier GROUP BY s_suppkey;
s_suppkey sum_acctBal rank_dense
supplier#011 200,000 1
supplier#002 200,000 1
supplier#013 123,000 2
supplier#004 110,000 3
supplier#035 110,000 3
supplier#006 50,000 4
supplier#021 10,000 5

Related Information

RANK Function [Analytical] [page 469]

6.11.57 DIFFERENCE Function [String]

Compares two strings, evaluates the similarity between them, and returns a value from 0 to 4.

 Syntax

DIFFERENCE ( <string-expression1>, <string-expression2> )

Parameters

string-expression1

The first string to compare.


string-expression2

The second string to compare.

Returns

SMALLINT

SAP IQ SQL Reference


346 INTERNAL SQL Functions
Remarks

The best match is 4.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 4:

SELECT DIFFERENCE( 'Smith', 'Smith' ) FROM iq_dummy

● The following statement returns the value 4:

SELECT DIFFERENCE( 'Smith', 'Smyth' ) FROM iq_dummy

● The following statement returns the value 3:

SELECT DIFFERENCE( 'Smith', 'Sweeney' ) FROM iq_dummy

● The following statement returns the value 2:

SELECT DIFFERENCE( 'Smith', 'Jones' ) FROM iq_dummy

● The following statement returns the value 1:

SELECT DIFFERENCE( 'Smith', 'Rubin' ) FROM iq_dummy

● The following statement returns the value 0:

SELECT DIFFERENCE( 'Smith', 'Wilkins' ) FROM iq_dummy

Related Information

SOUNDEX Function [String] [page 514]

SAP IQ SQL Reference


SQL Functions INTERNAL 347
6.11.58 DOW Function [Date and Time]

Returns a number from 1 to 7 representing the day of the week of the specified date, with Sunday=1,
Monday=2, and so on.

 Syntax

DOW ( <date-expression> )

Parameters

date-expression

The date.

Returns

SMALLINT

Remarks

Use the DATE_FIRST_DAY_OF_WEEK option if you need Monday (or another day) to be the first day of the
week.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 5:

SELECT DOW( '1998-07-09' ) FROM iq_dummy

SAP IQ SQL Reference


348 INTERNAL SQL Functions
Related Information

DATE_FIRST_DAY_OF_WEEK Option [page 1803]

6.11.59 ENCRYPT function [String]

Encrypts the specified value using the supplied encryption key and returns a LONG BINARY value.

 Syntax

ENCRYPT( <string-expression>, <key>[, <algorithm-format> [, initialization-


vector ] ] )

<algorithm-format> :
<algorithm> [ ( <format-clause> ) ]

<algorithm> :
AES
| AES256
| AES_FIPS
| AES256_FIPS
| RSA
| RSA_FIPS

<format-clause> :
FORMAT={ RAW[; <padding-clause> ] | INTERNAL }

<padding-clause> :
PADDING={ PKCS5
| ZEROES
| OAEP
| PKCS1
| ALL
| NONE }

Parameters

string-expression

The string to be decrypted. Binary values are supported. This parameter is case sensitive, even in case-
insensitive databases.
key

The encryption key (string) that is required to decrypt the <string-expression>. For AES, this value
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.

Specify keys in PEM format for RSA.

SAP IQ SQL Reference


SQL Functions INTERNAL 349
 Caution

For strongly encrypted databases, 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-format

This optional string parameter specifies the type of algorithm, format, and padding to use when encrypting
the <string-expression>.

algorithm

This optional string parameter specifies the type of algorithm used to encrypt the <string-
expression>. Specify one of the following formats:

AES

The data is encrypted using the AES algorithm.

If <algorithm-format> is not specified, then AES is used by default.

For the AES algorithm, <padding> can be PKCS5, ZEROES, or NONE. The default padding is
PKCS5.
AES256 The data is encrypted using the AES 256-bit algorithm. For AES256, <padding> can be
PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES_FIPS

The data is encrypted using the FIPS-certified version of the AES algorithm.

If the database server was started using the -fips server option, AES_FIPS is used as the default.
For AES_FIPS, <padding> can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES256_FIPS The data is encrypted using the FIPS-certified version of the AES 256-bit algorithm.
For AES256_FIPS, <padding> can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
RSA

For the RSA algorithm, when encrypting with a public key, <padding> can be PKCS1, OAEP, or
NONE. When encrypting with a private key, <padding> must be PKCS1. The default padding is
PKCS1.

If the RSA algorithm is specified, then the <initialization-vector> parameter is ignored and
FORMAT=RAW is ignored.

If a public key encrypts the message, then a private key must decrypt it. Using the same key for
encryption and decryption fails unless PADDING=NONE. However, if PADDING=NONE is set and
the incorrect key is supplied, then the function succeeds but returns meaningless data.

 Note

The maximum message length for RSA encryption is equal to the key size minus 11 bytes for
PKCS1 padding and the key size minus 42 bytes for OAEP padding. If you specify
PADDING=NONE, then the message must be equal to the key size. Unlike AES, the length of
the output is not the same as the length of the input when using RSA encryption.

RSA_FIPS The same as RSA except that the data is encrypted using the FIPS-certified version of
the RSA algorithm.

SAP IQ SQL Reference


350 INTERNAL SQL Functions
FORMAT clause

Use the optional FORMAT clause to specify the storage format for the data. If the data was stored in
the proprietary storage format, then specify INTERNAL . If the encrypted data was stored as-is (that is,
it can be decrypted by any software that can decrypt the specified algorithm), then specify RAW. For
data stored as RAW, specify the <initialization-vector> parameter.
PADDING clause

Use the optional PADDING clause to specify the padding type for AES and RSA encryption. For AES
encryption, you must also specify FORMAT=RAW.

The padding type for decryption must match that used for encryption unless PADDING=ALL is used.

PKCS5

The data is padded by using the PKCS#5 algorithm. The encrypted data is 1-16 bytes longer than
the decrypted data. This option is only available for AES encryption.This is the default padding for
AES encryption.
ZEROES

The data is padded with zeros (0) before encryption. The encrypted data is 0-15 bytes longer than
the decrypted data. When the encrypted data is decrypted, the result is also padded with zeros.
OAEP The data is padded using Optimal Asymmetric Encryption Padding. This option is only
available for RSA encryption (RSA or RSA_FIPS).
PKCS1 The data is padded using the PKCS#1 algorithm. This option is only available for RSA
encryption (RSA or RSA_FIPS). This option is the default for RSA encryption (RSA or RSA_FIPS).
NONE

The data is not padded. The input data must be a multiple of the cipher block length (16-bytes) for
AES, or exactly equal to the key size for RSA.
initialization-vector

Specify <initialization-vector> when <format> is set to RAW. The string cannot be longer than 16
bytes. Any value less than 16 bytes is padded with 0 bytes. This string cannot be set to NULL.
<initialization-vector> is ignored when <format> is set to INTERNAL

Returns

LONG BINARY

Remarks

The LONG BINARY value returned by this function is up to 31 bytes longer than the input <string-
expression>. The value returned by this function is not human-readable. Use the DECRYPT function to
decrypt a <string-expression> that was encrypted with the ENCRYPT function. For AES, to successfully
decrypt a <string-expression>, use the same encryption key and algorithm that were used to encrypt the
data. If you specify an incorrect encryption key, then an error is generated. A lost key results in inaccessible
data, from which there is no recovery.

SAP IQ SQL Reference


SQL Functions INTERNAL 351
If you are storing encrypted values in a table, then the column should be BINARY or LONG BINARY so that
character set conversion is not performed on the data.

When FORMAT=RAW is specified, the data is encrypted using raw encryption. Specify the encryption key,
initialization vector, and, optionally, the padding format. These same values must be specified when decrypting
the data. The decryption can be performed outside of the database server or by using the DECRYPT function.

Do not use raw encryption when the data is to be encrypted and decrypted only within the database server
because you must specify the initialization vector and the padding, and the encryption key cannot be verified
during decryption.

 Note

For the ISENCRYPTED function to return meaningful results, data must be encrypted using the ENCRYPT
function with AES/AES256 and must not use FORMAT=RAW.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following trigger encrypts the user_pwd column of the user_info table. This column contains users'
passwords, and the trigger fires whenever a password value is changed.

CREATE TRIGGER encrypt_updated_pwd


BEFORE UPDATE OF user_pwd
ON user_info
REFERENCING NEW AS new_pwd
FOR EACH ROW
BEGIN
SET new_pwd.user_pwd=ENCRYPT( new_pwd.user_pwd, '8U3dkA' );
END;

The following example updates the secret column with an encrypted version of the password column.
The data is encrypted using encryption key 'TheEncryptionKey', raw-format AES encryption, PKCS#5
padding (the default), and the initialization vector 'ThisIsTheIV'.

CREATE OR REPLACE TABLE SensitiveData


(
username char(30), password char(30), secret binary(48)
);
INSERT INTO SensitiveData (username, password)
VALUES
('Martin', 'topXsecret1'),
('Jasmine', 'my_big_secret'),
('Aidan', 'Shortcutsmakelongdelays');
UPDATE SensitiveData
SET secret = ENCRYPT( password, 'TheEncryptionKey',
'AES(FORMAT=RAW;PADDING=PKCS5)', 'ThisIsTheIV' );
SELECT *, LENGTH(secret) FROM SensitiveData;

SAP IQ SQL Reference


352 INTERNAL SQL Functions
6.11.60 ERRORMSG Function [Miscellaneous]

Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.

 Syntax

ERRORMSG ( [ <sqlstate> | <sqlcode> ] )

Parameters

sqlstate

String representing the SQLSTATE for which the error message is to be returned.
sqlcode

Integer representing the SQLCODE for which the error message is to be returned.

Returns

A string containing the error message.

VARCHAR

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 ('???').

The ERRORMSG function returns SAP SQL Anywhere and SAP IQ error messages.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 353
Example

The following statement returns the error message for SQLCODE -813:

select errormsg( -813 )

6.11.61 EVENT_CONDITION Function [System]

Specifies when an event handler is triggered.

 Syntax

EVENT_CONDITION ( <condition-name> )

Parameters

condition-name

The condition triggering the event. The possible values are preset in the database, and are case-insensitive.
Each condition is valid only for certain event types.

Condition Name Units Valid for Comment

DBFreePercent N/A DBDiskSpace DBDiskSpace shows free space in the sys­


tem database file (.db file), not the IQ store.

DBFreeSpace Megabytes DBDiskSpace

DBSize Megabytes GrowDB

ErrorNumber N/A RAISERROR

IdleTime Seconds ServerIdle

Interval Seconds All Time since handler last executed.

LogFreePercent N/A LogDiskSpace

LogFreeSpace Megabytes LogDiskSpace

LogSize Megabytes GrowLog

RemainingValues Integer GlobalAutoincrement The number of remaining values.

TempFreePercent N/A TempDiskSpace TempDiskSpace shows free space in the sys­


tem temporary file (pointed to by TEMP or
IQTMP16 environment variable), not the IQ
temporary store.

TempFreeSpace Megabytes TempDiskSpace

TempSize Megabytes GrowTemp

SAP IQ SQL Reference


354 INTERNAL SQL Functions
Returns

INT

Remarks

To define an event and its associated handler, use the CREATE EVENT statement.

 Note

CIS functional compensation performance considerations apply.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following event definition uses the EVENT_CONDITION function:

create event LogNotifier


type LogDiskSpace
where event_condition( 'LogFreePercent' ) < 50
handler
begin
message 'LogNotifier message'
end

Related Information

CREATE EVENT Statement [page 1262]


EVENT_CONDITION_NAME Function [System] [page 356]
EVENT_PARAMETER Function [System] [page 357]

SAP IQ SQL Reference


SQL Functions INTERNAL 355
6.11.62 EVENT_CONDITION_NAME Function [System]

Can be used to list the possible parameters for EVENT_CONDITION.

 Syntax

EVENT_CONDITION_NAME ( <integer> )

Parameters

integer

An integer that is greater than or equal to zero.

Returns

VARCHAR

Remarks

You can use EVENT_CONDITION_NAME to obtain a list of all EVENT_CONDITION arguments by looping over
integers until the function returns NULL.

To define an event and its associated handler, use the CREATE EVENT statement.

 Note

CIS functional compensation performance considerations apply.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Related Information

CREATE EVENT Statement [page 1262]

SAP IQ SQL Reference


356 INTERNAL SQL Functions
EVENT_CONDITION Function [System] [page 354]
EVENT_PARAMETER Function [System] [page 357]

6.11.63 EVENT_PARAMETER Function [System]

Provides context information for event handlers.

 Syntax

EVENT_PARAMETER ( <context-name> )

Parameters

context-name

One of the preset strings. The strings are case-insensitive, and carry the following information:

● ConnectionId – the connection ID, as returned by connection_property( 'id' )


● User – the user ID for the user that caused the event to be triggered.
● EventName – the name of the event that has been triggered.
● Executions – the number of times the event handler has been executed.
● IQDBMainSpaceName
● 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.
● TableName – the name of the table, for use with RemainingValues.
● <condition-name> – you can also access any of the valid <condition-name> arguments to the
EVENT_CONDITION function from the EVENT_PARAMETER function.

Returns

VARCHAR

Remarks

To define an event and its associated handler, use the CREATE EVENT statement.

 Note

CIS functional compensation performance considerations apply.

SAP IQ SQL Reference


SQL Functions INTERNAL 357
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Related Information

CREATE EVENT Statement [page 1262]


EVENT_CONDITION Function [System] [page 354]
EVENT_CONDITION_NAME Function [System] [page 356]

6.11.64 EXP Function [Numeric]

Returns the exponential function, e to the power of a number.

 Syntax

EXP ( <numeric-expression> )

Parameters

numeric-expression

The exponent.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


358 INTERNAL SQL Functions
Example

The following statement returns the value 3269017.3724721107:

SELECT EXP( 15 ) FROM iq_dummy

6.11.65 EXP_WEIGHTED_AVG Function [Aggregate]

Calculates an exponential weighted moving average. Weightings determine the relative importance of each
quantity that makes up the average.

 Syntax

EXP_WEIGHTED_AVG (<expression>, <period-expression>)


OVER (<window-spec>)

Parameters

expression

A numeric expression for which a weighted value is being computed.


period-expression

A numeric expression specifying the period for which the average is to be computed.
window-spec

Specified when using this function as a window function.

Remarks

Similar to the WEIGHTED_AVG function, the weights in EXP_WEIGHTED_AVG decrease over time. However,
weights in WEIGHTED_AVG decrease arithmetically, whereas weights in EXP_WEIGHTED_AVG decrease
exponentially. Exponential weighting applies more weight to the most recent values, and decreases the weight
for older values while still applying some weight.

SAP IQ calculates the exponential moving average using:

S*C+(1-S)*PEMA

In the calculation above, SAP IQ applies the smoothing factor by multiplying the current closing price (C) by the
smoothing constant (S) added to the product of the previous day’s exponential moving average value (PEMA)
and 1 minus the smoothing factor.

SAP IQ calculates the exponential moving average over the entire period specified by the OVER clause.
<period-expression> specifies the moving range of the exponential moving average.

SAP IQ SQL Reference


SQL Functions INTERNAL 359
The <window-spec> parameter represents usage as a window function in a SELECT statement. As such, you
can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement. The <window-spec> must contain an ORDER BY statement and cannot contain a frame
specification.

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause. DISTINCT is not supported.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

Example

The following example returns an exponential weighted average of salaries for employees in Florida with the
salary of recently hired employees contributing the most weight to the average. There are three rows used in
the weighting:

SELECT DepartmentID, Surname, Salary, EXP_WEIGHTED_AVG(Salary, 3)


OVER (ORDER BY YEAR(StartDate) DESC) as "W_AVG"FROM Employees
WHERE State IN ('FL') ORDER BY StartDate DESC

The returned result set is:

DepartmentID Surname Salary W_AVG

400 Evans 68,940.000 34,470.000000

300 Litton 58,930.000 46,700.000000

200 Sterling 64,900.000 55,800.000000

200 Kelly 87,500.000 71,650.000000

400 Charlton 28,300.000 49,975.000000

100 Lull 87,900.000 68,937.500000

100 Gowda 59,840.000 60,621.875000

400 Francis 53,870.000 61,403.750000

Related Information

Windowing Aggregate Function Usage [page 197]


WEIGHTED_AVG Function [Aggregate] [page 563]

SAP IQ SQL Reference


360 INTERNAL SQL Functions
6.11.66 FIRST_VALUE Function [Aggregate]

Returns the first value from a set of values.

 Syntax

FIRST_VALUE ( <expression> [ IGNORE NULLS | RESPECT NULLS ] )


OVER ( <window-spec> )

Parameters

expression

The expression on which to determine the first value in an ordered set.


window-spec

Specified when using this function as a window function.

Returns

Data type of the argument.

Remarks

FIRST_VALUE returns the first value in a set of values, which is usually an ordered set. If the first value in the
set is null, then the function returns NULL unless you specify IGNORE NULLS. If you specify IGNORE NULLS,
then FIRST_VALUE returns the first non-null value in the set, or NULL if all values are null.

The data type of the returned value is the same as that of the input value.

You cannot use FIRST_VALUE or any other analytic function for <expression>. That is, you cannot nest
analytic functions, but you can use other built-in function expressions for <expression>.

The <window-spec> parameter represents usage as a window function in a SELECT statement. As such, you
can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement.

If the <window-spec> does not contain an ORDER BY expression, or if the ORDER BY expression is not precise
enough to guarantee a unique ordering, then the result is arbitrary. If there is no <window-spec>, then the
result is arbitrary.

 Note

DISTINCT is not supported.

SAP IQ SQL Reference


SQL Functions INTERNAL 361
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere.

Example

The following example returns the relationship, expressed 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 Year(StartDate) DESC ) )
AS percentage
FROM Employees order by DepartmentID DESC;

The returned result set is:

DepartmentID EmployeeID Percentage

500 1,658 100.000000000000000000000

500 1,570 138.842709713689113761394

500 1,615 110.428462434244870095972

500 1,013 109.585190539292454724330

500 750 137.734409508894510701521

500 921 167.449704854836766654619

500 868 113.239368750752921334778

500 703 222.867927558928643135365

500 191 119.664297474199895594908

400 1,684 100.000000000000000000000

400 1,740 76.128652163477274215016

400 1,751 76.353400685155687446813

400 1,607 133.758100765890593292456

400 1,507 77.996465120338650199655

400 1,576 150.428767810774836893669

In this example, employee 1658 is the first row for department 500, indicating that employee 1658 is the most
recent hire in that department, and therefore receives a percentage of 100%. Percentages for the remaining
employees in department 500 are calculated relative to that of employee 1658. For example, employee 1570
earns approximately 139% of what employee 1658 earns.

SAP IQ SQL Reference


362 INTERNAL SQL Functions
Related Information

Windowing Aggregate Function Usage [page 197]

6.11.67 FLOOR Function [Numeric]

Returns the floor of (largest integer not greater than) a number.

 Syntax

FLOOR ( <numeric-expression> )

Parameters

numeric-expression

The number, usually a float.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 123.00:

SELECT FLOOR ( 123 ) FROM iq_dummy

● The following statement returns the value 123:

SELECT FLOOR ( 123.45 ) FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 363
● The following statement returns the value -124.00:

SELECT FLOOR ( -123.45 ) FROM iq_dummy

Related Information

CEIL Function [Numeric] [page 290]


CEILING Function [Numeric] [page 291]

6.11.68 GETDATE Function [Date and Time]

Returns the current date and time.

 Syntax

GETDATE ()

Returns

TIMESTAMP

Remarks

GETDATE is a Transact-SQL compatible data manipulation function.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the system date and time:

SELECT GETDATE( ) FROM iq_dummy

SAP IQ SQL Reference


364 INTERNAL SQL Functions
6.11.69 GRAPHICAL_PLAN Function [String]

Returns the graphical query plan to Interactive SQL in an XML format string.

 Syntax

GRAPHICAL_PLAN ( <string-expression>
[, <statistics-level>
[, <cursor-type>
[, <update-status> ]]])

Parameters

string-expression

SQL statement for which the plan is to be generated. string-expression is generally a SELECT statement,
but it can also be an UPDATE or DELETE, INSERT SELECT, or SELECT INTO statement.
statistics-level

An integer. Statistics-level can be:

● 0 – Optimizer estimates only (default).


● 2 – Detailed statistics including node statistics.
● 3 – Detailed statistics.
cursor-type

A cursor type, expressed as a string. Possible values are: asensitive, insensitive, sensitive, or keyset-driven.
If cursor-type is not specified, asensitive is used by default.
update-status

A string parameter accepting one of the following values indicating how the optimizer should treat the
given cursor:

● READ-ONLY – The cursor is read-only.


● READ-WRITE (default) – The cursor can be read or written to.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use GRAPHICAL_PLAN in a SELECT INTO statement, you
must have an Unstructured Data Analytics Option license or use CAST and set GRAPHICAL_PLAN to the
correct data type and size.

SAP IQ SQL Reference


SQL Functions INTERNAL 365
Remarks

 Note

CIS functional compensation performance considerations apply.

If you do not provide an argument to the GRAPHICAL_PLAN function, the query plan is returned to you from the
cache. If there is no query plan in the cache, then this message appears:

plan not available

The behavior of GRAPHICAL_PLAN function is controlled by database options QUERY_PLAN_TEXT_ACCESS and


QUERY_PLAN_TEXT_CACHING. If QUERY_PLAN_TEXT_ACCESS is OFF (the default), then this message appears:

Plan not available. The database option QUERY_PLAN_TEXT_ACCESS is OFF

If a user needs access to the plan, a user with the SET ANY SYSTEM OPTION system privilege must set option
QUERY_PLAN_TEXT_ACCESS ON for that user.

If QUERY_PLAN_TEXT_ACCESS is ON, and the query plan for the string expression is available in the cache
maintained on the server, the query plan from the cache is returned to you.

If the query plan is not available in the cache and you are authorized to view plans on the client, then a query
plan with optimizer estimates (query plan with NOEXEC option ON) is generated and appears on the Interactive
SQL client plan window.

When a user requests a query plan that has not yet been executed, the query plan is not available in the cache.
Instead, a query plan with optimizer estimates is returned without QUERY_PLAN_AFTER_RUN statistics.

You cannot access query plans for stored procedures using the GRAPHICAL_PLAN function.

Users can view the query plan for cursors opened for SAP IQ queries. A cursor is declared and opened using
DECLARE CURSOR and OPEN CURSOR. To obtain the query plan for the most recently opened cursor, use:

SELECT GRAPHICAL_PLAN ( );

With the QUERY_PLAN_AFTER_RUN option OFF, the plan appears after OPEN CURSOR or CLOSE CURSOR.
However, if QUERY_PLAN_AFTER_RUN is ON, CLOSE CURSOR must be executed before you request the plan.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


366 INTERNAL SQL Functions
Examples

● The following example passes a SELECT statement as a string parameter and returns the plan for
executing the query. It saves the plan in the file gplan.xml:

SELECT GRAPHICAL_PLAN ('SELECT * FROM Employees');OUTPUT to 'C:\gplan.xml'


HEXADECIMAL ASIS quote '';

 Note

If you use the OUTPUT statement’s HEXADECIMAL clause set to ASIS to get formatted plan output, the
values of characters are written without any escaping, even if the value contains control characters.
ASIS is useful for text that contains formatting characters such as tabs or carriage returns.

● The following example returns the query plan from the cache, if available:

SELECT GRAPHICAL_PLAN ( );

Related Information

CAST Function [Data Type Conversion] [page 288]


HTML_PLAN Function [String] [page 378]

6.11.70 GROUPING Function [Aggregate]

Identifies whether a column in a ROLLUP or CUBE operation result set is NULL because it is part of a subtotal
row, or NULL because of the underlying data.

 Syntax

GROUPING ( <group-by-expression> )

Parameters

group-by-expression

An expression appearing as a grouping column in the result set of a query that uses a GROUP BY clause
with the ROLLUP or CUBE keyword. The function identifies subtotal rows added to the result set by a
ROLLUP or CUBE operation.

SAP IQ SQL Reference


SQL Functions INTERNAL 367
Returns

● 1 – indicates that <group-by-expression> is NULL because it is part of a subtotal row. The column is
not a prefix column for that row.
● 0 – indicates that <group-by-expression> is a prefix column of a subtotal row.

Remarks

SAP IQ does not support the PERCENTILE_CONT or PERCENTILE_DISC functions with GROUP BY CUBE
operations.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.71 GROUP_MEMBER Function [System]

Identifies whether the user belongs to the specified group.

 Syntax

GROUP_MEMBER ( <group-name-string-expression>[ , <user-name-string-


expression >] )

Parameters

group-name-string-expression

Identifies the group to be considered.


user-name-string-expression

Identifies the user to be considered. If not supplied, then the current user name is assumed.

SAP IQ SQL Reference


368 INTERNAL SQL Functions
Returns

● 0 – returns 0 if the group does not exist, if the user does not exist, or if the user does not belong to the
specified group.
● 1 – returns an integer other than 0 if the user is a member of the specified group.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

6.11.72 HEXTOBIGINT Function [Data Type Conversion]

Returns the BIGINT equivalent of a hexadecimal string.

 Syntax

HEXTOBIGINT ( <hexadecimal-string> )

Parameters

hexadecimal-string

The hexadecimal value to be converted to a big integer (BIGINT). Input can be in the following forms, with
either a lowercase or uppercase “0x” in the prefix, or no prefix:

0x<hex-string>

0X<hex-string>

<hex-string>

Remarks

The HEXTOBIGINT function accepts hexadecimal integers and returns the BIGINT equivalent. Hexadecimal
integers can be provided as CHAR and VARCHAR value expressions, as well as BINARY and VARBINARY
expressions.

The HEXTOBIGINT function accepts a valid hexadecimal string, with or without a “0x” or “0X” prefix, enclosed
in single quotes.

SAP IQ SQL Reference


SQL Functions INTERNAL 369
Input of fewer than 16 digits is assumed to be left-padded with zeros.

For data type conversion failure on input, an error is returned unless the CONVERSION_ERROR option is set to
OFF. When CONVERSION_ERROR is OFF, invalid hexadecimal input returns NULL.

An error is returned if a BINARY or VARBINARY value exceeds 8 bytes and a CHAR or VARCHAR value exceeds 16
characters, with the exception of the value being appended with ‘0x.’

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statements return the value 4294967287:

SELECT HEXTOBIGINT ( '0xfffffff7' ) FROM iq_dummy

SELECT HEXTOBIGINT ( '0Xfffffff7' ) FROM iq_dummy

SELECT HEXTOBIGINT ( 'fffffff7' ) FROM iq_dummy

Related Information

BIGINTTOHEX Function [Data Type Conversion] [page 280]


HEXTOINT Function [Data Type Conversion] [page 370]
INTTOHEX Function [Data Type Conversion] [page 391]
CONVERSION_ERROR Option [TSQL] [page 1787]

6.11.73 HEXTOINT Function [Data Type Conversion]

Returns the unsigned BIGINT equivalent of a hexadecimal string.

 Syntax

HEXTOINT ( <hexadecimal-string> )

SAP IQ SQL Reference


370 INTERNAL SQL Functions
Parameters

hexadecimal-string

The string to be converted to an integer. Input can be in the following forms, with either a lowercase or
uppercase “x” in the prefix, or no prefix:

0x<hex-string>

0X<hex-string>

<hex-string>

Returns

The HEXTOINT function returns the platform-independent SQL INTEGER equivalent of the hexadecimal string.
The hexadecimal value represents a negative integer if the 8th digit from the right is one of the digits 8-9 and
the uppercase or lowercase letters A-F and the previous leading digits are all uppercase or lowercase letter F.
The following is not a valid use of HEXTOINT since the argument represents a positive integer value that cannot
be represented as a signed 32-bit integer:

SELECT HEXTOINT( '0x0080000001' );

INT

Remarks

For invalid hexadecimal input, SAP IQ returns an error unless the CONVERSION_ERROR option is OFF. When
CONVERSION_ERROR is OFF, invalid hexadecimal input returns NULL.

See CONVERSION_ERROR Option [TSQL] .

The database option ASE_FUNCTION_BEHAVIOR specifies that output of SAP IQ functions, including
INTTOHEX and HEXTOINT, is consistent with the output of SAP Adaptive Server Enterprise functions.

See ASE_FUNCTION_BEHAVIOR Option.

When the ASE_FUNCTION_BEHAVIOR option is ON:

● SAP IQ HEXTOINT assumes input is a hexadecimal string of 8 characters; if the length is less than 8
characters long, the string is left padded with zeros.
● SAP IQ HEXTOINT accepts a maximum of 16 characters prefixed with 0x (a total of 18 characters); use
caution, as a large input value can result in an integer value that overflows the 32-bit signed integer output
size.
● The data type of the output of the SAP IQ HEXTOINT function is assumed to be a 32-bit signed integer.
● SAP IQ HEXTOINT accepts a 32-bit hexadecimal integer as a signed representation.

SAP IQ SQL Reference


SQL Functions INTERNAL 371
● For more than 8 hexadecimal characters, SAP IQ HEXTOINT considers only relevant characters.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statements return the value 420:

SELECT HEXTOINT ( '0x1A4' ) FROM iq_dummy

SELECT HEXTOINT ( '0X1A4' ) FROM iq_dummy

SELECT HEXTOINT ( '1A4' ) FROM iq_dummy

Related Information

BIGINTTOHEX Function [Data Type Conversion] [page 280]


HEXTOBIGINT Function [Data Type Conversion] [page 369]
INTTOHEX Function [Data Type Conversion] [page 391]
CONVERSION_ERROR Option [TSQL] [page 1787]
ASE_FUNCTION_BEHAVIOR Option [page 1767]

6.11.74 HOUR Function [Date and Time]

Returns a number from 0 to 23 corresponding to the hour component of the specified date/time.

 Syntax

HOUR ( <datetime-expression> )

Parameters

datetime-expression

SAP IQ SQL Reference


372 INTERNAL SQL Functions
The date/time.

Returns

SMALLINT

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 21:

SELECT HOUR( '1998-07-09 21:12:13' ) FROM iq_dummy

6.11.75 HOURS Function [Date and Time]

Returns the number of hours since an arbitrary starting date and time, the number of whole hours between two
specified times, or adds the specified integer-expression number of hours to a time.

 Syntax

HOURS ( <datetime-expression>
| <datetime-expression>, <datetime-expression>
| <datetime-expression>, <integer-expression> )

Parameters

datetime-expression

A date and time.


integer-expression

The number of hours to be added to the <datetime-expression>. If <integer-expression> is


negative, the appropriate number of hours are subtracted from the date/time. If you supply an integer
expression, the <datetime-expression> must be explicitly cast as a datetime data type.

SAP IQ SQL Reference


SQL Functions INTERNAL 373
Returns

INT

Remarks

The second syntax returns the number of whole hours from the first date/time to the second date/time. The
number might be negative.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 17518758:

SELECT HOURS( '1998-07-13 06:07:12' ) FROM iq_dummy

● The following statement returns the value 4, to signify the difference between the two times:

SELECT HOURS( '1999-07-13 06:07:12',


'1999-07-13 10:07:12' ) FROM iq_dummy

● The following statement returns the datetime value 1999-05-13 02:05:07.000:

SELECT HOURS( CAST( '1999-05-12 21:05:07'


AS DATETIME ), 5 ) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]

SAP IQ SQL Reference


374 INTERNAL SQL Functions
YEARS Function [Date and Time] [page 568]

6.11.76 HTML_DECODE function [Miscellaneous]

Decodes special character entities that appear in HTML literal strings.

 Syntax

HTML_DECODE( <string> )

Parameters

string

Arbitrary literal string used in an HTML document.

Returns

LONG VARCHAR or LONG NVARCHAR.

 Note

The result data type is a LONG VARCHAR. If you use HTML_DECODE in a SELECT INTO statement, you
must have an Unstructured Data Analytics Option license or use CAST and set HTML_DECODE to the
correct data type and size.

Remarks

This function returns the string argument after making the appropriate substitutions. The following table
contains a sampling of the acceptable character entities.

Characters Substitution

&quot; "

&#39; '

&amp; &

&lt; <

&gt; >

SAP IQ SQL Reference


SQL Functions INTERNAL 375
Characters Substitution

&#x<hexadecimal-number>; Unicode codepoint, specified as a hexadecimal number. For


example, &#x27; returns a single apostrophe.

&#<decimal-number>; Unicode codepoint, specified as a decimal number. For ex­


ample, &#8482; returns the trademark symbol.

When a Unicode codepoint is specified, if the value can be converted to a character in the database character
set, it is converted to a character. Otherwise, it is returned uninterpreted.

SAP IQ supports all character entity references specified in the HTML 4.01 Specification.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement returns the string <p>The piano was made by 'Steinway & Sons'.</p>:

SELECT HTML_DECODE('&lt;p&gt;The piano was made ' ||


'by &lsquo;Steinway &amp; Sons&rsquo;.&lt;/p&gt;')

The following statement returns the string <p>It cost €85.000,000.</p>:

SELECT HTML_DECODE('&lt;p&gt;It cost &euro;85.000,000.&lt;/p&gt;')

6.11.77 HTML_ENCODE function [Miscellaneous]

Encodes special characters within strings to be inserted into HTML documents.

 Syntax

HTML_ENCODE( <string> )

Parameters

string

Arbitrary string to be used in an HTML document.

SAP IQ SQL Reference


376 INTERNAL SQL Functions
Returns

LONG VARCHAR or LONG NVARCHAR.

 Note

The result data type is a LONG VARCHAR. If you use HTML_ENCODE in a SELECT INTO statement, you
must have an Unstructured Data Analytics Option license or use CAST and set HTML_DECODE to the
correct data type and size.

Remarks

This function returns the string argument after making the following set of substitutions:

Characters Substitution

" &quot;

' &#39;

& &amp;

< &lt;

> &gt;

codes <nn> less than 0x20 &#x<nn>;

This function supports NCHAR inputs and/or outputs.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following example returns the string '&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML
4.01//EN&quot;&gt; '.

SELECT HTML_ENCODE('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">')

SAP IQ SQL Reference


SQL Functions INTERNAL 377
6.11.78 HTML_PLAN Function [String]

Returns query plans in an HTML format string.

 Syntax

HTML_PLAN ( <string-expression> )

Parameters

string-expression

SQL statement for which the plan is to be generated. It is primarily a SELECT statement but can be an
UPDATE or DELETE statement.

Remarks

 Note

CIS functional compensation performance considerations apply.

If you do not provide an argument to the HTML_PLAN function, the query plan is returned to you from the
cache. If there is no query plan in the cache, this message appears:

No plan available

The behavior of the HTML_PLAN function is controlled by database options QUERY_PLAN_TEXT_ACCESS and
QUERY_PLAN_TEXT_CACHING. If QUERY_PLAN_TEXT_ACCESS is OFF (the default), this message appears:

Plan not available. The database option QUERY_PLAN_TEXT_ACCESS is OFF

If QUERY_PLAN_TEXT_ACCESS is ON, and the query plan for the string expression is available in the cache
maintained on the server, the query plan from the cache is returned to you.

The HTML_PLAN function can be used to return query plans to Interactive SQL using SELECT, UPDATE, DELETE,
INSERT SELECT, and SELECT INTO.

Users can view the query plan for cursors opened for SAP IQ queries. To obtain the query plan for the most
recently opened cursor, use:

SELECT HTML_PLAN ( );

With QUERY_PLAN_AFTER_RUN option OFF, the plan appears after OPEN CURSOR or CLOSE CURSOR. However,
if QUERY_PLAN_AFTER_RUN is ON, CLOSE CURSOR must be executed before you request the plan.

SAP IQ SQL Reference


378 INTERNAL SQL Functions
When you request an HTML_PLAN for a SAP SQL Anywhere query or for an OMNI/CIS decomposed query, the
following message is returned:

No plan. HTML_PLAN function is not supported for this type of statement or


database.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example passes a SELECT statement as a string parameter and returns the HTML plan for
executing the query. It saves the plan in the file hplan.html:

SELECT HTML_PLAN ('SELECT * FROM Employees');


OUTPUT to 'C:\hplan.html' HEXADECIMAL ASIS QUOTE '';

The OUTPUT TO clause HEXADECIMAL ASIS is useful for text that contains formatting characters such as
tabs or carriage returns. When set to ASIS, values are written as is, without any escaping, even if the values
contain control characters.
● The following example returns the HTML query plan from the cache, if available:

SELECT HTML_PLAN ( );

Related Information

CAST Function [Data Type Conversion] [page 288]


GRAPHICAL_PLAN Function [String] [page 365]

6.11.79 HTTP_DECODE function [Web service]

Decodes HTTP encoded strings. This is also known as URL decoding.

 Syntax

HTTP_DECODE( <string> )

SAP IQ SQL Reference


SQL Functions INTERNAL 379
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.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement returns the string http://test.sap.com:

SELECT HTTP_DECODE('http%3A%2F%2Ftest.sap.com')

6.11.80 HTTP_ENCODE function [Web service]

Encodes strings for use with HTTP. This is also known as URL encoding.

 Syntax

HTTP_ENCODE( <string> )

SAP IQ SQL Reference


380 INTERNAL SQL Functions
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

| %7C

} %7D

character codes <nn> that are less than 0x20 and greater %<nn>
than 0x7f

This function supports NCHAR inputs and/or outputs.

SAP IQ SQL Reference


SQL Functions INTERNAL 381
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement returns the string /opt%26id=123%26text='oid:c%09d%20ef':

SELECT HTTP_ENCODE('/opt&id=123&text=''oid:c\x09d ef''')

6.11.81 HTTP_HEADER function [Web service]

Returns the value of an HTTP request header.

 Syntax

HTTP_HEADER( <header-field-name> [, <instance> ] )

Parameters

header-field-name

The name of an HTTP request header field.


instance

The instance of the header to retrieve. If more than one header has the same name, then the instance is
the number of the field instance. A value of 0 or NULL returns the most recent instance of the header. The
default is 0.

Returns

LONG VARCHAR.

 Note

The result data type is a LONG VARCHAR. If you use HTTP_HEADER in a SELECT INTO statement, you
must have an Unstructured Data Analytics Option license or use CAST and set HTTP_HEADER to the
correct data type and size.

SAP IQ SQL Reference


382 INTERNAL SQL Functions
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 (for example, http://documents.sample.com:80/index.html) that contained


the link to the requested URI.
Host

The Internet host name or IP address and port number of the resource being requested, as obtained from
the original URI given by the user or referring resource (for example, webserver.sample.com:8082).
User-Agent

The name of the client application (for example, Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0)
Gecko/20100101 Firefox/14.0).
Accept-Encoding

A list of encodings for the response that are acceptable to the client application (for example, gzip,
deflate).

More information about these headers is available at HTTP Header Field Definitions .

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

Standards

ANSI/ISO SQL Standard

Not in the standard.

SAP IQ SQL Reference


SQL Functions INTERNAL 383
 Example

The following statement retrieves the fifth instance of the Cookie header value when used within a stored
procedure that is called by an HTTP web service:

SET cookie_header = HTTP_HEADER( 'Cookie', 5 );

The following statement displays the name and values of the HTTP request headers in the database server
messages window when used within a stored procedure that is called by an HTTP web service:

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;

6.11.82 HTTP_RESPONSE_HEADER function [Web service]

Returns the value of an HTTP response header.

 Syntax

HTTP_RESPONSE_HEADER( <header-field-name> [, <instance> ] )

Parameters

header-field-name

The name of an HTTP response header field.


instance

The instance of the header to retrieve. If more than one header has the same name, then the instance is
the number of the field instance. A value of 0 or NULL returns the most recent instance of the header. The
default is 0.

SAP IQ SQL Reference


384 INTERNAL SQL Functions
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 SAP IQ 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. For 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 SAP IQ 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 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 SAP IQ HTTP
server response, the web server name together with the version number is returned.
WWW-Authenticate

The WWW-Authenticate field is included in 401 (Unauthorized) response messages.

More information about these headers is available at HTTP Header Field Definitions .

The following special header allows access to the status within the response of a server response.

@HttpStatus

Returns the status code of the processed request.

SAP IQ SQL Reference


SQL Functions INTERNAL 385
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement displays the name and values of the HTTP response headers in the database
server messages window when used within a stored procedure that is called by an HTTP web service:

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;

6.11.83 HTTP_VARIABLE function [Web service]

Returns the value of an HTTP variable.

 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 section.

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.

SAP IQ SQL Reference


386 INTERNAL SQL Functions
The attribute can also be one of the following modes:

'@BINARY'

Returns a x-www-form-urlencoded binary data value. This mode indicates that the returned value is %-
decoded and not character-set translated. UTF-8 %-encoding is not supported in this mode since %-
encoded data are simply decoded into their equivalent byte representation.
'@TRANSPORT'

Returns the raw HTTP transport form of the value, where %-encodings are preserved.

Returns

LONG VARCHAR.

 Note

The result data type is a LONG VARCHAR. If you use HTTP_VARIABLE in a SELECT INTO statement, you
must have an Unstructured Data Analytics Option license or use CAST and set HTTP_VARIABLE to the
correct data type and size.

Remarks

This function returns the value of the named HTTP variable. It is used when processing an HTTP request within
a web service.

If <var-name> does not exist, the return value is NULL.

When the web service request is a POST, and the variable data is posted as multipart/form-data, the HTTP
server receives HTTP headers for each individual variable. When the <attribute> parameter is specified, the
HTTP_VARIABLE function returns the associated multipart/form-data header value from the POST request for
the particular variable. For a variable representing a file, an attribute of Content-Disposition, Content-Type, and
@BINARY would return the filename, media-type, and file contents respectively.

Normally, all input data goes through character set translation between the client (for example, a browser)
character set, and the character set of the database. However, if @BINARY is specified for <attribute>, the
variable value is returned without going through character set translation or %-decoding. This may be useful
when receiving binary data, such as image data, from a client.

This function returns NULL when the specified instance does not exist or when the function is called from
outside of an execution of a web service.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SAP IQ SQL Reference


SQL Functions INTERNAL 387
 Example

The following statement retrieves the values of the HTTP variables indicated in the sample URL when used
within a stored procedure that is called by an HTTP web service:

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

The following statements request the Content-Disposition and Content-Type headers of the image variable
when used within a stored procedure that is called by an HTTP web service:

SET v_name = HTTP_VARIABLE( 'image', NULL, 'Content-Disposition' );


SET v_type = HTTP_VARIABLE( 'image', NULL, 'Content-Type' );

The following statement requests the value of the image variable in its current character set without going
through character set translation when used within a stored procedure that is called by an HTTP web
service:

SET v_image = HTTP_VARIABLE( 'image', NULL, '@BINARY' );

6.11.84 IFNULL Function [Miscellaneous]

Returns the first non-null expression, or NULL.

 Syntax

IFNULL ( <expression1>, <expression2> [ , <expression3> ] )

Parameters

expression1

The expression to be evaluated. Its value determines whether <expression2> or <expression3> is


returned.
expression2

The return value if <expression1> is NULL


expression3

(Optional) The return value if <expression1> is not NULL.

SAP IQ SQL Reference


388 INTERNAL SQL Functions
Returns

The data type returned depends on the data type of <expression2> and <expression3>.

Remarks

If the first expression is the NULL value, then the value of the second expression is returned. If the first
expression is not NULL, the value of the third expression is returned. If the first expression is not NULL and
there is no third expression, then the NULL value is returned.

Standards and compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value -66:

SELECT IFNULL( NULL, -66 ) FROM iq_dummy

● The following statement returns NULL, because the first expression is not NULL and there is no third
expression:

SELECT IFNULL( -66, -66 ) FROM iq_dummy

6.11.85 INDEX_COL Function [System]

Returns the name of the indexed column.

 Syntax

INDEX_COL ( <table-name>, <index-id>, <key_#> [ , <user-id> ] )

Parameters

table-name

SAP IQ SQL Reference


SQL Functions INTERNAL 389
A table name.
index-id

The index ID of an index of <table-name>.


key_#

A key in the index specified by <index-id>. This parameter specifies the column number in the index. For
a single column index, <key_#> is equal to 0. For a multicolumn index, <key_#> is equal to 0 for the first
column, 1 for the second column, and so on.
user-id

(Optional) The user ID of the owner of <table-name>. If <user-id> is not specified, this value defaults to
the caller’s user ID.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Related Information

OBJECT_ID Function [System] [page 445]

6.11.86 INSERTSTR Function [String]

Inserts a string into another string at a specified position.

 Syntax

INSERTSTR ( <numeric-expression>, <string-expression1>, <string-expression2> )

Parameters

numeric-expression

The position after which <string-expression2> is to be inserted. Use zero to insert a string at the
beginning.
string-expression1

The string into which <string-expression2> is to be inserted.


string-expression2

SAP IQ SQL Reference


390 INTERNAL SQL Functions
The string to be inserted.

Returns

LONG NVARCHAR or LONG VARCHAR, depending on the data type of the input expressions. This function
returns LONG NVARCHAR or LONG VARCHAR, even if the input expressions are BINARY.

 Note

The result data type is a LONG VARCHAR. If you use INSERTSTR in a SELECT INTO statement, you must
have an Unstructured Data Analytics Option license or use CAST and set INSERTSTR to the correct data
type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. The STUFF function is
equivalent and is supported in both SAP ASE and SAP IQ.

Example

The following statement returns the value "backoffice":

SELECT INSERTSTR( 0, 'office ', 'back' ) FROM iq_dummy

Related Information

REPLACE Function [String] [page 489]


STUFF Function [String] [page 535]

6.11.87 INTTOHEX Function [Data Type Conversion]

Returns the hexadecimal equivalent of a decimal integer.

 Syntax

INTTOHEX ( <integer-expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 391
Parameters

integer-expression

The integer to be converted to hexadecimal.

Returns

VARCHAR

Remarks

If data conversion of input to INTTOHEX conversion fails, SAP IQ returns an error, unless the
CONVERSION_ERROR option is OFF. In that case, the result is NULL.

The database option ASE_FUNCTION_BEHAVIOR specifies that output of SAP IQ functions, including
INTTOHEX and HEXTOINT, be consistent with the output of SAP Adaptive Server Enterprise functions. The
default value of ASE_FUNCTION_BEHAVIOR is OFF.

When the ASE_FUNCTION_BEHAVIOR option is disabled (the value is OFF):

● The output of INTTOHEX:


○ Is compatible with SAP SQL Anywhere.
○ Does not have a ‘0x’ or ‘0X’ prefix.
● Depending on the input, the output of INTTOHEX can be 8 digits or 16 digits and is left padded with zeros;
the return data type is VARCHAR.
● The input to INTTOHEX can be up to a 64-bit integer.

When the ASE_FUNCTION_BEHAVIOR option is enabled (the value is ON):

● The output of INTTOHEX


○ Is compatible with SAP ASE.
○ Is always 8 digits and is left-padded with zeros; the return data type is VARCHAR.
○ Does not have a ‘0x’ or ‘0X’ prefix.
● SAP IQ INTTOHEX assumes input is a 32-bit signed integer; a larger value can overflow and a conversion
error can result.
For example, the following statement returns the value 3B9ACA00:

SELECT INTTOHEX( 1000000000 ) FROM iq_dummy

The following statement, however, results in a conversion error:

SELECT INTTOHEX( 10000000000 ) FROM iq_dummy

SAP IQ SQL Reference


392 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 3B9ACA00:

SELECT INTTOHEX( 1000000000 ) FROM iq_dummy

● The following statement returns the value 00000002540BE400:

SELECT INTTOHEX ( 10000000000) FROM iq_dummy

Related Information

BIGINTTOHEX Function [Data Type Conversion] [page 280]


HEXTOBIGINT Function [Data Type Conversion] [page 369]
HEXTOINT Function [Data Type Conversion] [page 370]

6.11.88 ISDATE Function [Date and Time]

Tests whether a string argument can be converted to a date.

 Syntax

ISDATE ( <string> )

Parameters

string

The string to be analyzed to determine whether the string represents a valid date.

Returns

INT

SAP IQ SQL Reference


SQL Functions INTERNAL 393
Remarks

If a conversion is possible, the function returns 1; otherwise, it returns 0. If the argument is null, 0 is returned.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products:
○ SAP SQL Anywhere uses ISO 8601 date interchange formats
○ Supported by SAP Adaptive Server Enterprise 15.0.1 and later

Example

The following example tests whether the birth_date column holds valid dates, returning invalid dates as
NULL, and valid dates in date format:

select birth_date from MyData;


------------------------------
1990/32/89
0101/32/89
1990/12/09

select
case when isdate(birth_date)=0 then NULL
else cast(birth_date as date)
end
from MyData;
------------------------------------
(NULL)
(NULL)
1990-12-09

6.11.89 ISNULL Function [Miscellaneous]

Returns the value of the first non-NULL expression in the parameter list.

 Syntax

ISNULL ( <expression>, <expression> [ …, <expression> ] )

SAP IQ SQL Reference


394 INTERNAL SQL Functions
Parameters

expression

An expression to be tested against NULL.

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

At least two expressions must be passed to the function.

The ISNULL function is the same as the COALESCE function.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value -66:

SELECT ISNULL( NULL ,-66, 55, 45, NULL, 16 ) FROM iq_dummy

Related Information

COALESCE Function [Miscellaneous] [page 298]

SAP IQ SQL Reference


SQL Functions INTERNAL 395
6.11.90 ISNUMERIC Function [Miscellaneous]

Tests whether a string argument can be converted to a numeric.

 Syntax

ISNUMERIC ( <string> )

Parameters

string

The string to be analyzed to determine whether the string represents a valid numeric value.

Returns

INT

Remarks

If a conversion is possible, the function returns 1; otherwise, it returns 0. If the argument is null, 0 is returned.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise 15.0.1 and later.

Example

The following example tests whether the height_in_cms column holds valid numeric data, returning invalid
numeric data as NULL, and valid numeric data in int format:

data height_in_cms
------------------------
asde
asde
180
156

SAP IQ SQL Reference


396 INTERNAL SQL Functions
select case
when isnumeric(height_in_cms)=0
then NULL
else cast(height_in_cms as int)
end
from MyData

6.11.91 LAG Function [Analytical]

An interrow function that returns the value of an attribute in a previous row in the table or table partition.

 Syntax

LAG ( <value_expr>) [, <offset> [, <default> ] ] )


OVER ( [ PARTITION BY <window partition> ] ORDER BY <window ordering> )

Parameters

value_expr

Table column or expression defining the offset data to return from the table.
offset

The number of rows above the current row, expressed as a non-negative exact numeric literal, or as a SQL
variable with exact numeric data. The permitted range is 0 to 231.
default

The value to return if the <offset> value goes beyond the scope of the cardinality of the table or partition.
window partition

(Optional) One or more value expressions separated by commas indicating how you want to divide the set
of result rows.
window ordering

Defines the expressions for sorting rows within window partitions, if specified, or within the result set if you
did not specify a window partition.

Remarks

The LAG function requires an OVER (ORDER_BY) window specification. The window partitioning clause in the
OVER (ORDER_BY) clause is optional. The OVER (ORDER_BY) clause must not contain a window frame ROWS/
RANGE specification.

You cannot define an analytic expression in <value_expr>. That is, you cannot nest analytic functions, but
you can use other built-in function expressions for <value_expr>.

SAP IQ SQL Reference


SQL Functions INTERNAL 397
You must enter a non-negative numeric data type for <offset>. Entering 0 returns the current row. Entering a
negative number generates an error.

The default value of <default> is NULL. The data type of <default> must be implicitly convertible to the data
type of the <value_expr> value or else SAP IQ generates a conversion error.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

Example

The following example returns salary data from the Employees table, partitions the data by department ID, and
orders the data according to employee start date. The LAG function returns the salary from the previous row (a
physical offset of one row) and displays it under the LAG (Salary) column:

SELECT DepartmentID dID, StartDate, Salary, LAG(Salary, 1)


OVER (PARTITION BY dID ORDER BY StartDate) FROM Employees ORDER BY 1,2;

The returned result set is:

dID StartDate Salary Lag(Salary)


========= =========== ========== =============
100 1984-08-28 45,700.000 NULL
100 1985-01-01 62,000.000 45,700.000
100 1985-06-17 57,490.000 62,000.000
100 1986-06-07 72,995.000 57,490.000
100 1986-07-01 48,023.690 72,995.000
...
200 1985-02-03 38,500.000 NULL
200 1985-12-06 54,800.000 38,500.000
200 1987-02-19 39,300.000 54,800.000
200 1987-07-10 49,500.000 39,300.000
200 1988-10-04 54,600.000 49,500.000
200 1988-11-12 39,800.000 54,600.000
...

Related Information

LEAD Function [Analytical] [page 402]

SAP IQ SQL Reference


398 INTERNAL SQL Functions
6.11.92 LAST_VALUE Function [Aggregate]

Returns the last value from a set of values.

 Syntax

LAST_VALUE ( <expression> [ IGNORE NULLS | RESPECT NULLS ] )


OVER ( <window-spec> )

Parameters

expression

The expression on which to determine the last value in an ordered set


window-spec

Specified when using this function as a window function.

Returns

Data type of the argument.

Remarks

LAST_VALUE returns the last value in a set of values, which is usually an ordered set. If the last value in the set
is null, then the function returns NULL unless you specify IGNORE NULLS. If you specify IGNORE NULLS, then
LAST_VALUE returns the last non-null value in the set, or NULL if all values are null.

The data type of the returned value is the same as that of the input value.

You cannot use LAST_VALUE or any other analytic function for expression. That is, you cannot nest analytic
functions, but you can use other built-in function expressions for expression.
The <window-spec> parameter represents usage as a window function in a SELECT statement. As such, you
can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement.

If the <window-spec> does not contain an ORDER BY expression, or if the ORDER BY expression is not precise
enough to guarantee a unique ordering, then the result is arbitrary. If there is no <window-spec>, then the
result is arbitrary.

 Note

DISTINCT is not supported.

SAP IQ SQL Reference


SQL Functions INTERNAL 399
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the salary of each employee, plus the name of the employee with the highest
salary in their department:

SELECT GivenName + ' ' + Surname AS employee_name,


Salary, DepartmentID,
LAST_VALUE( employee_name ) OVER Salary_Window AS
highest_paid
FROM Employees
WINDOW Salary_Window AS ( PARTITION BY DepartmentID ORDER BY
Salary
RANGE BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING )
ORDER BY DepartmentID DESC;

The returned result set is:

employee_name Salary DepartmentID highest_paid

Michael Lynch 24,903.000 500 Jose Martinez

Joseph Barker 27,290.000 500 Jose Martinez

Sheila Romero 27,500.000 500 Jose Martinez

Felicia Kuo 28,200.000 500 Jose Martinez

Jeannette Bertrand 29,800.000 500 Jose Martinez

Jane Braun 34,300.000 500 Jose Martinez

Anthony Rebeiro 34,576.000 500 Jose Martinez

Charles Crowley 41,700.000 500 Jose Martinez

Jose Martinez 55,500.800 500 Jose Martinez

Doug Charlton 28,300.000 400 Scott Evans

Elizabeth Lambert 29,384.000 400 Scott Evans

Joyce Butterfield 34,011.000 400 Scott Evans

Robert Nielsen 34,889.000 400 Scott Evans

Alex Ahmed 34,992.000 400 Scott Evans

Ruth Wetherby 35,745.000 400 Scott Evans

... ... ... ...

SAP IQ SQL Reference


400 INTERNAL SQL Functions
Related Information

Windowing Aggregate Function Usage [page 197]

6.11.93 LCASE Function [String]

Converts all characters in a string to lowercase.

 Syntax

LCASE ( <string-expression> )

Parameters

string-expression

The string to be converted to lowercase.

Returns

● CHAR
● NCHAR
● LONG VARCHAR
● VARCHAR
● NVARCHAR

Remarks

The result data type is a LONG VARCHAR. If you use LCASE in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set LCASE to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise; you can use LOWER to get the
same functionality.

SAP IQ SQL Reference


SQL Functions INTERNAL 401
Example

The following statement returns the value "lower case":

SELECT LCASE( 'LOWER CasE' ) FROM iq_dummy

Related Information

LEFT Function [String] [page 404]


LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]

6.11.94 LEAD Function [Analytical]

An interrow function that returns the value of an attribute in a subsequent row in the table or table partition.

 Syntax

LEAD ( <value_expr> )[, <offset>[, <default> ] ] )


OVER ( [ PARTITION BY <window partition> ] ORDER BY <window ordering> )

Parameters

value_expr

Table column or expression defining the offset data to return from the table.
offset

The number of rows below the current row, expressed as a non-negative exact numeric literal, or as a SQL
variable with exact numeric data. The permitted range is 0 to 231.
default

The value to return if the <offset> value goes beyond the scope of the table or partition.
window partition

(Optional) One or more value expressions separated by commas indicating how you want to divide the set
of result rows.
window ordering

SAP IQ SQL Reference


402 INTERNAL SQL Functions
Defines the expressions for sorting rows within window partitions, if specified, or within the result set if you
did not specify a window partition.

Remarks

The LEAD function requires an OVER (ORDER_BY) window specification. The window partitioning clause in the
OVER (ORDER_BY) clause is optional. The OVER (ORDER_BY) clause must not contain a window frame ROWS/
RANGE specification.

You cannot define an analytic expression in <value_expr>. That is, you cannot nest analytic functions, but
you can use other built-in function expressions for <value_expr>.

You must enter a non-negative numeric data type for <offset>. Entering 0 returns the current row. Entering a
negative number generates an error.

The default value of <default> is NULL. The data type of <default> must be implicitly convertible to the data
type of the <value_expr> value or else SAP IQ generates a conversion error.

Standards and Compatibility

SQL – vendor extension to ISO/ANSI SQL grammar

Example

The following example returns salary data from the Employees table, partitions the data by department ID, and
orders the data according to employee start date. The LEAD function returns the salary from the next row (a
physical offset of one row) and displays it under the LEAD (Salary) column:

SELECT DepartmentID dID, StartDate, Salary, LEAD(Salary, 1)


OVER (PARTITION BY dID ORDER BY StartDate) FROM Employees ORDER BY 1,2;

The returned result set is:

dID StartDate Salary Lead(Salary)


========= =========== ========== =============
100 1984-08-28 45,700.000 62,000.000
100 1985-01-01 62,000.000 57,490.000
100 1985-06-17 57,490.000 72,995.000
100 1986-06-07 72,995.000 48,023.690
...
100 1990-08-19 54,900.000 NULL
200 1985-02-03 38,500.000 39,300.000
200 1987-02-19 39,300.000 49,500.000
200 1987-07-10 49,500.000 54,600.000
200 1988-11-28 46,200.000 34,892.000
200 1989-06-01 34,892.000 87,500.000
...
200 1993-08-12 47,653.000 NULL

SAP IQ SQL Reference


SQL Functions INTERNAL 403
Related Information

LAG Function [Analytical] [page 397]

6.11.95 LEFT Function [String]

Returns a specified number of characters from the beginning of a string.

 Syntax

LEFT ( <string-expression>, <numeric-expression> )

Parameters

string-expression

The string.
numeric-expression

The number of characters to return.

Returns

● LONG VARCHAR
● LONG NVARCHAR

Remarks

The result data type is a LONG VARCHAR. If you use LEFT in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set LEFT to the correct data type and size.

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.

 Note

The result data type of a LEFT function is a LONG VARCHAR. If you use LEFT in a SELECT INTO statement,
you must have an Unstructured Data Analytics option license or use CAST and set LEFT to the correct data
type and size.

SAP IQ SQL Reference


404 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value "choco":

SELECT LEFT( 'chocolate', 5 ) FROM iq_dummy

Related Information

LCASE Function [String] [page 401]


LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]

6.11.96 LEN Function [String]

Takes one argument as an input of type BINARY or STRING and returns the number of characters, as defined
by the database's collation sequence, of a specified string expression, excluding trailing blanks.

 Syntax

LEN ( <string_expr> )

Parameters

string_expr

The string expression to be evaluated.

SAP IQ SQL Reference


SQL Functions INTERNAL 405
Remarks

The result may differ from the string’s byte length for multi-byte character sets.

BINARY and VARBINARY are also allowed, in which case LEN() returns the number of bytes of the input.

LEN is an alias of LENGTH function

This function is the equivalent of CHAR_LENGTH (< string_expression >).

Standards and Compatibility

SQL – Transact-SQL extension to ISO/ANSI SQL grammar

Example

The following example returns the value 3152:

select len(Photo) from Productswhere ID = 500

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.97 LENGTH Function [String]

Returns the number of characters in the specified string.

 Syntax

LENGTH ( <string-expression> )

SAP IQ SQL Reference


406 INTERNAL SQL Functions
Parameters

string-expression

The string.

Returns

INT

Remarks

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 BINARY data type, the LENGTH function behaves as
BYTE_LENGTH.

The LENGTH function is the same as the CHAR_LENGTH function.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. Use the CHAR_LENGTH
function instead.

Example

The following statement returns the value 9:

SELECT LENGTH( 'chocolate' ) FROM iq_dummy

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]

SAP IQ SQL Reference


SQL Functions INTERNAL 407
LEN Function [String] [page 405]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]

6.11.98 LN Function [Numeric]

Returns the natural logarithm of the specified expression.

 Syntax

LN ( <numeric-expression> )

Parameters

numeric-expression

A column, variable, or expression with a data type that is either exact numeric, approximate numeric,
money, or any type that can be implicitly converted to one of these types. For other data types, the LN
function generates an error. The return value is of DOUBLE data type.

Remarks

LN takes one argument. For example, LN (<20>) returns 2.995732.

The LN function is an alias of the LOG function.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. Use the LOG function instead.

Related Information

LOG Function [Numeric] [page 412]


LOG10 Function [Numeric] [page 416]

SAP IQ SQL Reference


408 INTERNAL SQL Functions
6.11.99 LOCATE Function [String]

Returns the position of one string within another.

 Syntax

LOCATE ( <string-expression1>, <string-expression2>


[ , <numeric-expression> ] )

Parameters

string-expression1

The string to be searched.


string-expression2

The string for which you are searching. This string is limited to 255 bytes.
numeric-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.

The <numeric-expression> is a 32 bit signed integer for CHAR, VARCHAR, and BINARY columns.

If <numeric-expression> is specified, the search starts at that offset into the string being searched.

If <numeric-expression> is not specified, LOCATE returns only the position of the first instance of the
specified string.

Returns

INT

Remarks

The first string can be a long string (longer than 255 bytes), but the second is limited to 255 bytes. A second
string longer than 255 bytes causes an error.

If any of the arguments is NULL, the result is NULL.

Searching for a zero-length string returns 1.

If the string does not contain the specified string, the LOCATE function returns zero (0).

SAP IQ SQL Reference


SQL Functions INTERNAL 409
All the positions or offsets, returned or specified, in the LOCATE function are always character offsets and may
be different from the byte offset for multibyte data.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 8:

SELECT LOCATE( 'office party this week – rsvp as soon as possible', 'party',
2 ) FROM iq_dummy

● In the second example, the <numeric-expression> starting offset for the search is a negative number:

CREATE TABLE t1(name VARCHAR(20), dirname VARCHAR(60));


INSERT INTO t1 VALUES(‘m1000’,’c:\test\functions\locate.sql’);
INSERT INTO t1 VALUES(‘m1001’,’d:\test\functions\trim.sql’);
COMMIT;
SELECT LOCATE(dirname, ‘\’, -1), dirname FROM t1;

The result is:

18 c:\test\functions\locate.sql
18 d:\test\functions\trim.sql

In this section:

LOCATE Function [Unstructured Data Analytics] [page 411]


The LOCATE function returns a 64-bit signed integer containing the position of the specified string in
the large object column or variable parameter. For CHAR and VARCHAR columns, LOCATE returns a 32-
bit signed integer position.

Related Information

LIKE Conditions [page 70]


PATINDEX Function [String] [page 448]

SAP IQ SQL Reference


410 INTERNAL SQL Functions
6.11.99.1 LOCATE Function [Unstructured Data Analytics]

The LOCATE function returns a 64-bit signed integer containing the position of the specified string in the large
object column or variable parameter. For CHAR and VARCHAR columns, LOCATE returns a 32-bit signed integer
position.

 Syntax

LOCATE( <large-object-column>, <string-expression>


[, <numeric-expression> ] )

Parameters

large-object-column

The name of the LONG VARCHAR or LONG BINARY column or variable to search.
string-expression

The string of up to 255 bytes, for which you are searching.


numeric-expression

The character position or offset at which to begin the search in the string. The <numeric-expression> is
a 64-bit signed integer for LONG VARCHAR and LONG BINARY columns and is a 32-bit signed integer for
CHAR, VARCHAR, and BINARY columns. The first character is position 1. If the starting offset is negative,
LOCATE returns the last matching string offset, rather than the first. A negative offset indicates how much
of the end of the string to exclude from the search. The number of characters excluded is calculated as ( -1
* offset ) - 1.

Remarks

● All the positions or offsets, returned or specified, in the LOCATE function are always character offsets and
may be different from the byte offset for multibyte data.
● If the large object cell being searched contains more than one instance of the string:
○ If <numeric-expression> is specified, LOCATE starts the search at that offset in the string.
○ If <numeric-expression> is not specified, LOCATE returns only the position of the first instance.
● If the column does not contain the string, LOCATE returns zero (0).
● Searching for a string longer than 255 bytes returns NULL.
● Searching for a zero-length string returns 1.
● If any of the arguments is NULL, the result is NULL.
● LOCATE supports searching LONG VARCHAR and LONG BINARY columns and LONG VARCHAR and LONG
BINARY variables of any size of data. Currently, a SQL variable can hold up to 2 GB - 1 in length.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

SAP IQ SQL Reference


SQL Functions INTERNAL 411
6.11.100 LOG Function [Numeric]

Returns the natural logarithm of a number.

 Syntax

LOG ( <numeric-expression> )

Parameters

numeric-expression

The number.

Returns

This function converts its argument to DOUBLE, performs the computation in double-precision floating point,
and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Remarks

LN is an alias of LOG.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 3.912023:

SELECT LOG( 50 ) FROM iq_dummy

SAP IQ SQL Reference


412 INTERNAL SQL Functions
Related Information

LN Function [Numeric] [page 408]


LOG10 Function [Numeric] [page 416]

6.11.101 LIST Function [Aggregate]

Returns a delimited list of values for every row in a group.

 Syntax

LIST
( [ ALL | DISTINCT ] <string-expresssion>
[, '<delimiter-string>' ]
[ ORDER BY <order-by-expression> [ ASC | DESC ], ... ] )

Parameters

string-expresssion

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.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use LIST in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set LIST to the correct data type and size.

SAP IQ SQL Reference


SQL Functions INTERNAL 413
Remarks

The LIST function returns the concatenation (with delimiters) of all the non-NULL values of X for each row in
the group. If there does not exist at least one row in the group with a definite X-value, then LIST( X ) returns the
empty string.

NULL values and empty strings are ignored by the LIST function.

A LIST function cannot be used as a window function, but it can be used as input to a window function.

This function supports NCHAR inputs and/or outputs.

Order By
There is no comma <order-by-expression>, which makes it easy to use in the case where no delimiter-
string is supplied.

<order-by-expression> cannot be an integer literal. However, it can be a variable that contains an integer
literal.

When an ORDER BY clause contains constants, they are interpreted by the optimizer and then replaced by an
equivalent ORDER BY clause. For example, the optimizer interprets ORDER BY 'a' as ORDER BY expression.

A query block containing more than one aggregate function with valid ORDER BY clauses can be executed if the
ORDER BY clauses can be logically combined into a single ORDER BY clause. For example, the following
clauses:

ORDER BY expression1, 'a', expression2

ORDER BY expression1, 'b', expression2, 'c', expression3

Are subsumed by the clause:

ORDER BY expression1, expression2, expression3

Standards and Compatibility

SQL – vendor extension to ISO/ANSI SQL grammar

SAP IQ 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.

SAP IQ does not support optional SQL/2008 feature F442, "Mixed column references in set functions". SAP
IQdoes 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.

SAP IQ SQL Reference


414 INTERNAL SQL Functions
Examples

● This statement returns the value 487 Kennedy Court, 547 School Street:

SELECT LIST( Street ) FROM Employees


WHERE GivenName = 'Thomas';

● This 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,...

191,703,750,868,921,1013,1570,...

● This statement sorts the employee IDs by the last name of the employee:

SELECT LIST( EmployeeID ORDER BY Surname ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

Sorted IDs

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

● This statement returns semicolon-separated lists. Note the position of the ORDER BY clause and the list
separator:

SELECT LIST( EmployeeID, ';' ORDER BY Surname ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

Sorted IDs

1013;191;750;921;868;1658;703;...

1751;591;1062;1191;992;888;318;...

1336;879;586;390;757;148;1483;...

1039;129;1142;195;667;1162;902; ...

SAP IQ SQL Reference


SQL Functions INTERNAL 415
Sorted IDs

160;105;1250;247;266;249;445;...

Be sure to distinguish the previous statement from the following statement, which returns comma-
separated lists of employee IDs sorted by a compound sort-key of ( Surname, ';' ):

SELECT LIST( EmployeeID ORDER BY Surname, ';' ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

6.11.102 LOG10 Function [Numeric]

Returns the base 10 logarithm of a number.

 Syntax

LOG10 ( <numeric-expression> )

Parameters

numeric-expression

The number.

Returns

This function converts its argument to DOUBLE, and performs the computation in double-precision floating
point. If the parameter is NULL, the result is NULL.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


416 INTERNAL SQL Functions
Example

The following statement returns the value 1.698970:

SELECT LOG10( 50 ) FROM iq_dummy

Related Information

LN Function [Numeric] [page 408]


LOG Function [Numeric] [page 412]

6.11.103 LOWER Function [String]

Converts all characters in a string to lowercase.

 Syntax

LOWER ( <string-expression> )

Parameters

string-expression

The string to be converted.

Returns

● CHAR
● NCHAR
● LONG VARCHAR
● VARCHAR
● NVARCHAR

Remarks

The result data type is a LONG VARCHAR. If you use LOWER in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set LOWER to the correct data type and size.

SAP IQ SQL Reference


SQL Functions INTERNAL 417
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value "lower case":

SELECT LOWER( 'LOWER CasE' ) FROM iq_dummy

Related Information

LCASE Function [String] [page 401]


LEFT Function [String] [page 404]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]

6.11.104 LPAD Function [String]

Left-pads a string with spaces, or a specified pattern, to make a string of a specified number of characters in
length.

 Syntax

LPAD ( <str>, <n> [, <pattern> ] )

Syntax Elements

str

The string to be padded.


n

The length to which to pad <str>. <n> must be an integer.


pattern

SAP IQ SQL Reference


418 INTERNAL SQL Functions
A string of characters to use for padding instead of spaces.

Description

Left-pads the end of <str> with spaces to make a string of <n> characters. If <pattern> is specified, then
<str> is padded using sequences of the given characters until the required length is met.

If the length of <str> is greater than <n>, then no padding is performed and the resulting value is truncated
from the right side to the length specified in <n>.

LPAD returns an empty string value if <n> is less than 1.

Examples

● The following example left-pads the start of string end with the pattern 12345 to make a string of 15
characters in length, and returns the value 1234512345hello:

SELECT LPAD ('hello', 15, '12345') "left pad" FROM DUMMY;

● In the following example, <str> is longer than <n>, so no padding is performed and the result is <str>
truncated to the length of <n> (that is, he):

SELECT LPAD ('hello', 2, '12345') "left pad" FROM DUMMY;

● By not specifying <pattern>, this example left-pads the start of string hello with a single blank
character (that is, " hello"):

SELECT LPAD ('hello', 6) "left pad" FROM DUMMY;

6.11.105 LTRIM Function [String]

Returns a string, trimmed of all the leading characters present in the trim character set.

 Syntax

LTRIM ( <string-expression>, [ <trim_character_set> ] )

Parameters

string-expression

The string to be trimmed.

SAP IQ SQL Reference


SQL Functions INTERNAL 419
trim_character_set The set of characters to use for trim.

Returns

Trimmed string.

Remarks

If trim character set is not specified, all leading spaces in the string expression are trimmed.

Standards and Compatibility

● STANDARD function

Example

The following statement removes all leading a and b characters from the given string and returns the value
Aabend.

SELECT LTRIM ('babababAabend','ab') "ltrim" FROM iq_dummy

Related Information

RTRIM Function [String] [page 502]


TRIM Function [String] [page 546]

6.11.106 MAX Function [Aggregate]

Returns the maximum <expression> value found in each group of rows.

 Syntax

MAX ( <expression>
| DISTINCT <column-name> )

SAP IQ SQL Reference


420 INTERNAL SQL Functions
Parameters

expression

The expression for which the maximum value is to be calculated. This is commonly a column name.
DISTINCT column-name

Returns the same as MAX ( <expression> ), and is included for completeness.

Returns

The same data type as the argument.

Remarks

Rows where <expression> is NULL are ignored. Returns NULL for a group containing no rows.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 138948.000, representing the maximum salary in the Employees
table:

SELECT MAX ( Salary )


FROM Employees

Related Information

Windowing Aggregate Function Usage [page 197]


MIN Function [Aggregate] [page 423]

SAP IQ SQL Reference


SQL Functions INTERNAL 421
6.11.107 MEDIAN Function [Aggregate]

Returns the median of an expression.

 Syntax

Syntax 1

MEDIAN ( [ ALL | DISTINCT ] <expression> )

Syntax 2

MEDIAN ( [ ALL | DISTINCT ] <expression> )


OVER ( <window-spec> )

Parameters

expression

A numeric expression for which a median value is to be computed.


window-spec

Specified when using this function as a window function.

Remarks

The median is the number separating the higher half of a sample, a population, or a probability distribution,
from the lower half.

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. You can use the optional keyword DISTINCT to eliminate duplicate values before the
aggregate function is applied. ALL, which performs the operation on all rows, is the default.

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

 Note

The <window-spec> cannot contain a ROW, RANGE or ORDER BY specification; <window-spec> can only
specify a PARTITION clause. DISTINCT is not supported if a WINDOW clause is used.

SAP IQ SQL Reference


422 INTERNAL SQL Functions
Standards and Compatibility

SQL – Transact-SQL extension to ISO/ANSI SQL grammar

Example

The following query returns the median salary for each department in Florida:

SELECT DepartmentID, Surname, Salary,


MEDIAN(Salary) OVER (PARTITION BY DepartmentID) "Median"
FROM Employees
WHERE State IN ('FL')

The returned result is:

DepartmentID Surname Salary Median

100 Lull 87,900.000 73,870.000

100 Gowda 59,840.000 73,870.000

200 Sterling 64,900.000 76,200.000

200 Kelly 87,500.000 76,200.000

300 Litton 58,930.000 58,930.000

400 Francis 53,870.000 38,70.000

400 Charlton 28,300.000 53,870.000

400 Evans 68,940.000 53,870.000

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.108 MIN Function [Aggregate]

Returns the minimum expression value found in each group of rows.

 Syntax

MIN ( <expression>
| DISTINCT <column-name> )

SAP IQ SQL Reference


SQL Functions INTERNAL 423
Parameters

expression

The expression for which the minimum value is to be calculated. This is commonly a column name.
DISTINCT column-name

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.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 24903.000, representing the minimum salary in the Employees
table:

SELECT MIN ( Salary )


FROM Employees

Related Information

Windowing Aggregate Function Usage [page 197]


MAX Function [Aggregate] [page 420]

SAP IQ SQL Reference


424 INTERNAL SQL Functions
6.11.109 MINUTE Function [Date and Time]

Returns a number from 0 to 59 corresponding to the minute component of the specified date/time value.

 Syntax

MINUTE ( <datetime-expression> )

Parameters

datetime-expression

The date/time value.

Returns

SMALLINT

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 22:

SELECT MINUTE( '1998-07-13 12:22:34' ) FROM iq_dummy

6.11.110 MINUTES Function [Date and Time]

Returns the number of minutes since an arbitrary date and time, the number of whole minutes between two
specified times, or adds the specified integer-expression number of minutes to a time.

 Syntax

MINUTES ( <datetime-expression>

SAP IQ SQL Reference


SQL Functions INTERNAL 425
| <datetime-expression>, <datetime-expression>
| <datetime-expression>, <integer-expression> )

Parameters

datetime-expression

A date and time.


integer-expression

The number of minutes to be added to the <datetime-expression>. If <integer-expression> is


negative, the appropriate number of minutes are subtracted from the date/time. If you supply an integer
expression, the <datetime-expression> must be explicitly cast as a datetime data type

Returns

● INT
● TIMESTAMP

Remarks

The second syntax returns the number of whole minutes from the first date/time to the second date/time. The
number might be negative.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● Returns the value 1051125487:

SELECT MINUTES( '1998-07-13 06:07:12' ) FROM iq_dummy

● Returns the value 240, to signify the difference between the two times:

SELECT MINUTES( '1999-07-13 06:07:12',


'1999-07-13 10:07:12' ) FROM iq_dummy

SAP IQ SQL Reference


426 INTERNAL SQL Functions
● Returns the datetime value 1999-05-12 21:10:07.000:

SELECT MINUTES( CAST( '1999-05-12 21:05:07'


AS DATETIME ), 5) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]

6.11.111 MOD Function [Numeric]

Returns the remainder when one whole number is divided by another.

 Syntax

MOD ( <dividend>, <divisor> )

Parameters

dividend

The dividend, or numerator, of the division.


divisor

The divisor, or denominator, of the division.

Returns

● SMALLINT
● INT
● NUMERIC

SAP IQ SQL Reference


SQL Functions INTERNAL 427
Remarks

Division involving a negative <dividend> gives a negative or zero result. The sign of the <divisor> has no
effect.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. The % operator is used as a
modulo operator in SAP ASE.

Example

The following statement returns the value 2:

SELECT MOD( 5, 3 ) FROM iq_dummy

Related Information

REMAINDER Function [Numeric] [page 487]

6.11.112 MONTH Function [Date and Time]

Returns a number from 1 to 12 corresponding to the month of the given date.

 Syntax

MONTH ( <date-expression> )

Parameters

date-expression

A date/time value.

SAP IQ SQL Reference


428 INTERNAL SQL Functions
Returns

SMALLINT

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 7:

SELECT MONTH( '1998-07-13' ) FROM iq_dummy

6.11.113 MONTHNAME Function [Date and Time]

Returns the name of the month from the specified date expression.

 Syntax

MONTHNAME ( <date-expression> )

Parameters

date-expression

The datetime value.

Returns

VARCHAR

SAP IQ SQL Reference


SQL Functions INTERNAL 429
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value September, when the DATE_ORDER option is set to the default value
of <ymd>:

SELECT MONTHNAME( '1998-09-05' ) FROM iq_dummy

6.11.114 MONTHS Function [Date and Time]

Returns the number of months since an arbitrary starting date/time or the number of months between two
specified date/times, or adds the specified integer-expression number of months to a date/time.

 Syntax

MONTHS ( <date-expression>
| <date-expression, datetime-expression>
| <date-expression, integer-expression> )

Parameters

date-expression

A date and time.


integer-expression

The number of months to be added to the <date-expression>. If <integer-expression> is negative,


the appropriate number of months are subtracted from the date/time value. If you supply an integer
expression, the <date-expression> must be explicitly cast as a datetime data type.

Returns

● INT
● TIMSTAMP

SAP IQ SQL Reference


430 INTERNAL SQL Functions
Remarks

The first syntax returns the number of months since an arbitrary starting date. This number is often useful for
determining whether two date/time expressions are in the same month in the same year.

MONTHS( invoice_sent ) = MONTHS( payment_received )

Comparing the MONTH function would incorrectly include a payment made 12 months after the invoice was
sent.

The second syntax returns the number of months from the first date to the second date. The number might be
negative. It is calculated from the number of the first days of the month between the two dates. Hours, minutes
and seconds are ignored.

The third syntax adds <integer-expression> months to the given date. If the new date is past the end of
the month — such as MONTHS ('1992-01-31', 1) — the result is set to the last day of the month. If
<integer-expression> is negative, the appropriate number of months are subtracted from the date. Hours,
minutes and seconds are ignored.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 23982:

SELECT MONTHS( '1998-07-13 06:07:12' ) FROM iq_dummy

● The following statement returns the value 2, to signify the difference between the two dates:

SELECT MONTHS( '1999-07-13 06:07:12',


'1999-09-13 10:07:12' ) FROM iq_dummy

● The following statement returns the datetime value 1999-10-12 21:05:07.000:

SELECT MONTHS( CAST( '1999-05-12 21:05:07'


AS DATETIME ), 5) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]

SAP IQ SQL Reference


SQL Functions INTERNAL 431
MINUTES Function [Date and Time] [page 425]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]

6.11.115 NEWID Function [Miscellaneous]

Generates a UUID (Universally Unique Identifier) value.

 Syntax

NEWID ( )

Parameters

There are no parameters associated with NEWID().

Returns

UNIQUEIDENTIFIER

Remarks

The returned UUID value is a binary. A UUID is the same as a GUID (Globally Unique Identifier).

The NEWID() function generates a unique identifier value.

UUIDs can be used to uniquely identify objects in a database. The values are generated such that a value
produced on one computer does not match that produced on another, hence they can also be used as keys in
replication and synchronization environments.

The NEWID function is supported only in the following positions:

● SELECT list of a top level query block


● SET clause of an UPDATE statement
● VALUES clause of INSERT...VALUES

You can use a value generated by the NEWID function as a column default value in a table.

SAP IQ SQL Reference


432 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement creates the table t1 and then updates the table, setting the value of the column
uid_col to a unique identifier generated by the NEWID function, if the current value of the column is NULL:

CREATE TABLE t1 (uid_col int);


UPDATE t1
SET uid_col = NEWID()
WHERE uid_col IS NULL

If you execute the following statement, the unique identifier is returned as a BINARY(16):

SELECT NEWID()

For example, the value might be 0xd3749fe09cf446e399913bc6434f1f08. You can convert this string into a
readable format using the UUIDTOSTR() function.

Related Information

Binary Data Types [page 123]


STRTOUUID Function [String] [page 533]
UUIDTOSTR Function [String] [page 553]
Character Data Types [page 115]
Binary Data Type Compatibility [page 159]

6.11.116 NEXT_CONNECTION Function [System]

Returns the next connection number, or the first connection if the parameter is NULL.

 Syntax

NEXT_CONNECTION ( { <connection-id> }, { <database-id> } )

SAP IQ SQL Reference


SQL Functions INTERNAL 433
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.

Returns

INT

Remarks

 Note

CIS functional compensation performance considerations apply.

You can use NEXT_CONNECTION to enumerate the connections to a database. To get the first connection, pass
NULL; to get each subsequent connection, pass the previous return value. The function returns NULL when
there are no more connections.

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.

Standards and Compatibility

SQL – Transact-SQL extension to ISO/ANSI SQL grammar

SAP IQ SQL Reference


434 INTERNAL SQL Functions
Examples

● The following statement returns an identifier for the first connection on the current database. The identifier
is an integer value like 10:

SELECT NEXT_CONNECTION( NULL );

● The following statement returns a value like 5:

SELECT NEXT_CONNECTION( 10 );

● The following call returns the next connection ID in reverse order from the specified <connection-id> on
the current database:

SELECT NEXT_CONNECTION( connection-id );

● The following call returns the next connection ID in reverse order from the specified <connection-id
>(regardless of database):

SELECT NEXT_CONNECTION( connection-id, NULL );

● The following call returns the next connection ID in reverse order from the specified <connection-id> on
the specified database:

SELECT NEXT_CONNECTION( connection-id, database-id );

● The following call returns the first (earliest) connection (regardless of database):

SELECT NEXT_CONNECTION( NULL, NULL );

● The following call returns the first (earliest) connection on the specified database:

SELECT NEXT_CONNECTION( NULL, database-id );

6.11.117 NEXT_DATABASE Function [System]

Returns the next database ID number, or the first database if the parameter is NULL.

 Syntax

NEXT_DATABASE ( { NULL | <database-id> } )

Parameters

database-id

An integer that specifies the ID number of the database.

SAP IQ SQL Reference


SQL Functions INTERNAL 435
Returns

INT

Remarks

 Note

CIS functional compensation performance considerations apply.

You can use NEXT_DATABASE to enumerate the databases running on a database server. To get the first
database, pass NULL; to get each subsequent database, pass the previous return value. The function returns
NULL when there are no more databases.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 0, the first database value:

SELECT NEXT_DATABASE( NULL ) FROM iq_dummy

● The following statement returns NULL, indicating that there are no more databases on the server:

SELECT NEXT_DATABASE( 0 ) FROM iq_dummy

Related Information

COL_NAME Function [System] [page 300]


DB_ID Function [System] [page 339]
DB_NAME Function [System] [page 341]
DB_PROPERTY Function [System] [page 342]
OBJECT_ID Function [System] [page 445]
OBJECT_NAME Function [System] [page 446]

SAP IQ SQL Reference


436 INTERNAL SQL Functions
6.11.118 NEXT_HTTP_HEADER function [Web service]

Returns the next HTTP header name.

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

 Note

The result data type is a LONG VARCHAR. If you use NEXT_HTTP_HEADER in a SELECT INTO statement,
you must have an Unstructured Data Analytics Option license or use CAST and set HTML_DECODE to the
correct data type and size.

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.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SAP IQ SQL Reference


SQL Functions INTERNAL 437
 Example

The following statement displays the name and values of the HTTP request headers in the database server
messages window when used within a stored procedure that is called by an HTTP web service:

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;

6.11.119 NEXT_HTTP_VARIABLE function [Web service]

Returns the next HTTP variable name.

 Syntax

NEXT_HTTP_VARIABLE( <var-name>)

Parameters

var-name

The name of the previous variable. If <var-name> is NULL, this function returns the name of the first HTTP
variable.

Returns

LONG VARCHAR.

 Note

The result data type is a LONG VARCHAR. If you use NEXT_HTTP_VARIABLE in a SELECT INTO statement,
you must have an Unstructured Data Analytics Option license or use CAST and set NEXT_HTTP_HEADER
to the correct data type and size.

SAP IQ SQL Reference


438 INTERNAL SQL Functions
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.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement returns the name of the first HTTP variable when used within a stored procedure
that is called by an HTTP web service:

BEGIN
DECLARE variable_name LONG VARCHAR;
DECLARE variable_value LONG VARCHAR;
SET variable_name = NULL;
SET variable_name = NEXT_HTTP_VARIABLE( variable_name );
SET variable_value = HTTP_VARIABLE( variable_name );
END;

6.11.120 NOW Function [Date and Time]

Returns the current date and time. This is the historical syntax for CURRENT TIMESTAMP.

 Syntax

NOW ( * )

Returns

TIMESTAMP

SAP IQ SQL Reference


SQL Functions INTERNAL 439
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the current date and time:

SELECT NOW(*) FROM iq_dummy

6.11.121 NTILE Function [Analytical]

Distributes query results into a specified number of buckets and assigns the bucket number to each row in the
bucket.

 Syntax

NTILE ( <expression1> )
OVER ( ORDER BY <expression2> [ ASC | DESC ] )

Parameters

expression1

A constant integer from 1 to 32767, which specifies the number of buckets.


expression2

A sort specification that can be any valid expression involving a column reference, aggregates, or
expressions invoking these items.
ASC | DESC

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is
the default.

Remarks

NTILE is a rank analytical function that distributes query results into a specified number of buckets and
assigns the bucket number to each row in the bucket. You can divide a result set into one-hundredths
(percentiles), tenths (deciles), fourths (quartiles), or other numbers of groupings.

SAP IQ SQL Reference


440 INTERNAL SQL Functions
NTILE requires an OVER (ORDER BY) clause. The ORDER BY clause specifies the parameter on which
ranking is performed and the order in which the rows are sorted in each group. This ORDER BY clause is used
only within the OVER clause and is not an ORDER BY for the SELECT. No aggregation functions in the rank
query are allowed to specify DISTINCT.

The OVER clause indicates that the function operates on a query result set. The result set is the rows that are
returned after the FROM, WHERE, GROUP BY, and HAVING clauses have all been evaluated. The OVER clause
defines the data set of the rows to include in the computation of the rank analytical function.

NTILE is allowed only in the select list of a SELECT or INSERT statement or in the ORDER BY clause of the
SELECT statement. NTILE can be in a view or a union. The NTILE function cannot be used in a subquery, a
HAVING clause, or in the select list of an UPDATE or DELETE statement. Only one NTILE function is allowed per
query.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Example

The following example uses the NTILE function to determine the sale status of car dealers. The dealers are
divided into four groups based on the number of cars each dealer sold. The dealers with ntile = 1 are in the
top 25% for car sales:

SELECT dealer_name, sales,


NTILE(4) OVER ( ORDER BY sales DESC )
FROM carSales;
dealer_name sales ntile
Boston 1000 1
Worcester 950 1
Providence 950 1
SF 940 1
Lowell 900 2
Seattle 900 2
Natick 870 2
New Haven 850 2
Portland 800 3
Houston 780 3
Hartford 780 3
Dublin 750 3
Austin 650 4
Dallas 640 4
Dover 600 4

To find the top 10% of car dealers by sales, you specify NTILE(10) in the example SELECT statement.
Similarly, to find the top 50% of car dealers by sales, specify NTILE(2).

SAP IQ SQL Reference


SQL Functions INTERNAL 441
Related Information

PERCENTILE_CONT Function [Analytical] [page 453]


PERCENTILE_DISC Function [Analytical] [page 455]
YEAR Function [Date and Time] [page 566]

6.11.122 NULLIF Function [Miscellaneous]

Provides an abbreviated CASE expression by comparing expressions.

 Syntax

NULLIF ( <expression1>, <expression2> )

Parameters

expression1

An expression to be compared.
expression2

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. NULLIF is equivalent to:

CASE WHEN <expression1> = <expression2> THEN NULL


ELSE <expression1> END

SAP IQ SQL Reference


442 INTERNAL SQL Functions
Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns a:

SELECT NULLIF( 'a', 'b' ) FROM iq_dummy

● The following statement returns NULL:

SELECT NULLIF( 'a', 'a' ) FROM iq_dummy

Related Information

CASE Expressions [page 52]


NULLIF Function for Abbreviated CASE Expressions [page 53]

6.11.123 NUMBER Function [Miscellaneous]

Generates numbers starting at 1 for each successive row in the results of the query.

 Syntax

NUMBER ( * )

Returns

INT

SAP IQ SQL Reference


SQL Functions INTERNAL 443
Remarks

Use the NUMBER function only in a select list or a SET clause of an UPDATE statement. For example, the
following statement updates each row of the seq_id column with a number 1 greater than the previous row.
The number is applied in the order specified by the ORDER BY clause:

update empl
set seq_id = number(*)
order by empl_id

In an UPDATE statement, if the NUMBER (*) function is used in the SET clause and the FROM clause specifies a
one-to-many join, NUMBER (*) generates unique numbers that increase, but may not increment sequentially
due to row elimination.

NUMBER can also be used to generate primary keys when using the INSERT from SELECT statement, although
using IDENTITY/AUTOINCREMENT is a preferred mechanism for generating sequential primary keys.

 Note

A syntax error is generated if you use NUMBER in a DELETE statement, WHERE clause, HAVING clause,
ORDER BY clause, subquery, query involving aggregation, any constraint, GROUP BY, DISTINCT, a query
containing UNION ALL, or a derived table.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

This statement returns the following numbered list:

SELECT NUMBER( * )
FROM Departments
WHERE DepartmentID > 10

number(*)

SAP IQ SQL Reference


444 INTERNAL SQL Functions
number(*)

6.11.124 OBJECT_ID Function [System]

Returns the object ID.

 Syntax

OBJECT_ID ( <object-name> )

Parameters

object-name

The name of the object.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Example

The following statement returns the object ID 100209 of the <Customers> table:

SELECT OBJECT_ID ('CUSTOMERS') FROM iq_dummy

Related Information

COL_NAME Function [System] [page 300]


DB_ID Function [System] [page 339]
DB_NAME Function [System] [page 341]
DB_PROPERTY Function [System] [page 342]
NEXT_DATABASE Function [System] [page 435]

SAP IQ SQL Reference


SQL Functions INTERNAL 445
OBJECT_NAME Function [System] [page 446]
INDEX_COL Function [System] [page 389]

6.11.125 OBJECT_NAME Function [System]

Returns the object name.

 Syntax

OBJECT_NAME ( <object-id> [ , <database-id> ] )

Parameters

object-id

The object ID.


database-id

The database ID.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Example

The following statement returns the name "customer":

SELECT OBJECT_NAME ( 100209 ) FROM iq_dummy

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]

SAP IQ SQL Reference


446 INTERNAL SQL Functions
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OCTET_LENGTH Function [String] [page 447]
STR_REPLACE Function [String] [page 530]
COL_NAME Function [System] [page 300]
DB_ID Function [System] [page 339]
DB_NAME Function [System] [page 341]
DB_PROPERTY Function [System] [page 342]
NEXT_DATABASE Function [System] [page 435]
OBJECT_ID Function [System] [page 445]

6.11.126 OCTET_LENGTH Function [String]

Returns an unsigned 64-bit value containing the byte length of the column parameter.

 Syntax

OCTET_LENGTH( <column-name> )

Parameters

column-name

The name of a column.

Remarks

The return value of a NULL argument is NULL.

The OCTET_LENGTH function supports all SAP IQ data types.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data. The OCTET_LENGTH function supports all SAP IQ data types and LONG VARCHAR and LONG
BINARY variables of any size of data. Currently, a SQL variable can hold up to 2 GB - 1 in length.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

SAP IQ SQL Reference


SQL Functions INTERNAL 447
Standards and Compatibility

SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
STR_REPLACE Function [String] [page 530]

6.11.127 PATINDEX Function [String]

Returns the starting position of the first occurrence of a specified pattern.

 Syntax

PATINDEX ( '%<pattern>%', <string-expression> )

Parameters

pattern

The pattern for which you are searching. This string is limited to 126 bytes for patterns with wildcards. If
the leading percent wildcard is omitted, PATINDEX returns one (1) if the pattern occurs at the beginning of
the string, and zero if not. If <pattern> starts with a percent wildcard, then the two leading percent
wildcards are treated as one.

Patterns without wildcards (percent % or underscore _) can be up to 255 bytes in length.


string-expression

The string to be searched for the pattern.

SAP IQ SQL Reference


448 INTERNAL SQL Functions
Returns

INT

Remarks

PATINDEX returns the starting position of the first occurrence of the pattern. If the string being searched
contains more than one instance of the string pattern, PATINDEX returns only the position of the first instance.

The pattern uses the same wildcards as the LIKE comparison. This table lists the pattern wildcards:

Wildcard Matches

_ (underscore) Any one character

% (percent) Any string of zero or more characters

[] Any single character in the specified range or set

[^] Any single character not in the specified range or set

If the pattern is not found, PATINDEX returns zero (0).

Searching for a pattern longer than 126 bytes returns NULL.

Searching for a zero-length string returns 1.

If any of the arguments is NULL, the result is zero (0).

All the positions or offsets, returned or specified, in the PATINDEX function are always character offsets and
may be different from the byte offset for multibyte data.

PATINDEX returns a 32-bit unsigned integer position for CHAR and VARCHAR columns.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 2:

SELECT PATINDEX( '%hoco%', 'chocolate' ) FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 449
● The following statement returns the value 11:

SELECT PATINDEX ('%4_5_', '0a1A 2a3A 4a5A') FROM iq_dummy

In this section:

PATINDEX Function [Unstructured Data Analytics] [page 450]


The PATINDEX function returns a 64-bit unsigned integer containing the position of the first
occurrence of the specified pattern in a LONG VARCHAR column or variable. For CHAR and VARCHAR
columns, PATINDEX returns a 32-bit unsigned integer position.

Related Information

LIKE Conditions [page 70]


LOCATE Function [String] [page 409]

6.11.127.1 PATINDEX Function [Unstructured Data Analytics]

The PATINDEX function returns a 64-bit unsigned integer containing the position of the first occurrence of the
specified pattern in a LONG VARCHAR column or variable. For CHAR and VARCHAR columns, PATINDEX returns a
32-bit unsigned integer position.

 Syntax

PATINDEX( '<%pattern%>', <long-varchar-column> )

Parameters

%pattern%

The pattern for which you are searching. This string is limited to 126 bytes for patterns with wildcards. If
you omit the leading percent wildcard, PATINDEX returns one (1) if the pattern occurs at the beginning of
the column value, and zero (0) if the pattern does not occur at the beginning of the column value. Similarly,
if you omit the trailing percent wildcard, the pattern should occur at the end of the column value. The
pattern uses the same wildcards as the LIKE comparison.

Patterns without wildcards — percent (%) and underscore (_) — can be up to 255 bytes in length.
long-varchar-column

The name of the LONG VARCHAR column or variable.

SAP IQ SQL Reference


450 INTERNAL SQL Functions
Remarks

● All the positions or offsets, returned or specified, in the PATINDEX function are always character offsets
and may be different from the byte offset for multibyte data.
● If the LONG VARCHAR cell being searched contains more than one instance of the string pattern, PATINDEX
returns only the position of the first instance.
● If the column does not contain the pattern, PATINDEX returns zero (0).
● Searching for a pattern longer than 126 bytes returns NULL.
● Searching for a zero-length pattern returns 1.
● If any of the arguments is NULL, the result is zero (0).
● PATINDEX supports LONG VARCHAR variables of any size of data. Currently, a SQL variable can hold up to
2GB - 1 in length. PATINDEX does not support LONG BINARY variables or searching LONG BINARY
columns.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.128 PERCENT_RANK Function [Analytical]

Computes the (fractional) position of one row returned from a query with respect to the other rows returned by
the query, as defined by the ORDER BY clause.

 Syntax

PERCENT_RANK () OVER ( ORDER BY <expression> [ ASC | DESC ] )

Parameters

OVER (ORDER BY)

The ORDER BY clause specifies the parameter on which ranking is performed and the order in which the
rows are sorted in each group.
expression

A sort specification that can be any valid expression involving a column reference, aggregates, or
expressions invoking these items.
ASC | DESC

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is
the default.

Returns

The PERCENT_RANK function returns a DOUBLE value between 0 and 1.

SAP IQ SQL Reference


SQL Functions INTERNAL 451
Returns a decimal value between 0 and 1.

Remarks

PERCENT_RANK is a rank analytical function. The percent rank of a row R is defined as the rank of a row in the
groups specified in the OVER clause minus one divided by the number of total rows in the groups specified in
the OVER clause minus one. PERCENT_RANK returns a value between 0 and 1. The first row has a percent rank
of zero.

The PERCENT_RANK of a row is calculated as follows, where <Rx> is the rank position of a row in the group and
<NtotalRow> is the total number of rows in the group specified by the OVER clause:

(Rx - 1) / (NtotalRow - 1)

PERCENT_RANK requires an OVER (ORDER BY) clause. The ORDER BY clause specifies the parameter on
which ranking is performed and the order in which the rows are sorted in each group. This ORDER BY clause is
used only within the OVER clause and is not an ORDER BY for the SELECT. No aggregation functions in the rank
query are allowed to specify DISTINCT.

The OVER clause indicates that the function operates on a query result set. The result set is the rows that are
returned after the FROM, WHERE, GROUP BY, and HAVING clauses have all been evaluated. The OVER clause
defines the data set of the rows to include in the computation of the rank analytical function.

PERCENT_RANK is allowed only in the select list of a SELECT or INSERT statement or in the ORDER BY clause of
the SELECT statement. PERCENT_RANK can be in a view or a union. The PERCENT_RANK function cannot be
used in a subquery, a HAVING clause, or in the select list of an UPDATE or DELETE statement. Only one rank
analytical function is allowed per query.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Example

The following statement illustrates the use of the PERCENT_RANK function:

SELECT s_suppkey, SUM(s_acctBal) AS sum_acctBal,


PERCENT_RANK() OVER ( ORDER BY SUM(s_acctBal) DESC )
AS percent_rank_all FROM supplier GROUP BY s_suppkey;
s_suppkey sum_acctBal percent_rank_all
supplier#011 200000 0
supplier#002 200000 0
supplier#013 123000 0.3333
supplier#004 110000 0.5
supplier#035 110000 0.5

SAP IQ SQL Reference


452 INTERNAL SQL Functions
supplier#006 50000 0.8333
supplier#021 10000 1

6.11.129 PERCENTILE_CONT Function [Analytical]

Given a percentile, returns the value that corresponds to that percentile. Assumes a continuous distribution
data model.

 Note

If you are simply trying to compute a percentile, use the NTILE function instead, with a value of 100.

 Syntax

PERCENTILE_CONT ( <expression1> )
WITHIN GROUP ( ORDER BY <expression2> [ ASC | DESC ] )

Parameters

expression1

A constant of numeric data type and range from 0 to 1 (inclusive). If the argument is NULL, a “wrong
argument for percentile” error is returned. If the argument value is less than 0 or greater than 1, a “data
value out of range” error is returned
expression2

A sort specification that must be a single expression involving a column reference. Multiple expressions are
not allowed and no rank analytical functions, set functions, or subqueries are allowed in this sort
expression.

Remarks

The inverse distribution analytical functions return a k-th percentile value, which can be used to help establish a
threshold acceptance value for a set of data. The function PERCENTILE_CONT takes a percentile value as the
function argument, and operates on a group of data specified in the WITHIN GROUP clause, or operates on the
entire data set. The function returns one value per group. If the GROUP BY column from the query is not
present, the result is a single row. The data type of the results is the same as the data type of its ORDER BY
item specified in the WITHIN GROUP clause. The data type of the ORDER BY expression for PERCENTILE_CONT
must be numeric.

PERCENTILE_CONT requires a WITHIN GROUP (ORDER BY) clause.

The ORDER BY clause, which must be present, specifies the expression on which the percentile function is
performed and the order in which the rows are sorted in each group. For the PERCENTILE_CONT function, the

SAP IQ SQL Reference


SQL Functions INTERNAL 453
data type of this expression must be numeric. This ORDER BY clause is used only within the WITHIN GROUP
clause and is not an ORDER BY for the SELECT.

The WITHIN GROUP clause distributes the query result into an ordered data set from which the function
calculates a result. The WITHIN GROUP clause must contain a single sort item. If the WITHIN GROUP clause
contains more or less than one sort item, an error is reported.

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is the
default.

The PERCENTILE_CONT function is allowed in a subquery, a HAVING clause, a view, or a union.


PERCENTILE_CONT can be used anywhere the simple non-analytical aggregate functions are used. The
PERCENTILE_CONT function ignores the NULL value in the data set.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Example

The following example uses the PERCENTILE_CONT function to determine the 10th percentile value for car
sales in a region.

The example uses the following data set:

sales region dealer_name


900 Northeast Boston
800 Northeast Worcester
800 Northeast Providence
700 Northeast Lowell
540 Northeast Natick
500 Northeast New Haven
450 Northeast Hartford
800 Northwest SF
600 Northwest Seattle
500 Northwest Portland
400 Northwest Dublin
500 South Houston
400 South Austin
300 South Dallas
200 South Dover

The following SELECT statement contains the PERCENTILE_CONT function:

SELECT region, PERCENTILE_CONT(0.1)


WITHIN GROUP ( ORDER BY sales DESC )
FROM carSales GROUP BY region;

The result of the SELECT statement lists the 10th percentile value for car sales in a region:

region percentile_cont

SAP IQ SQL Reference


454 INTERNAL SQL Functions
Northeast 840
Northwest 740
South 470

Related Information

NTILE Function [Analytical] [page 440]


PERCENTILE_DISC Function [Analytical] [page 455]

6.11.130 PERCENTILE_DISC Function [Analytical]

Given a percentile, returns the value that corresponds to that percentile. Assumes a discrete distribution data
model.

 Note

If you are simply trying to compute a percentile, use the NTILE function instead, with a value of 100.

 Syntax

PERCENTILE_DISC ( <expression1> )
WITHIN GROUP ( ORDER BY <expression2> [ ASC | DESC ] )

Parameters

expression1

A constant of numeric data type and range from 0 to 1 (inclusive). If the argument is NULL, then a “wrong
argument for percentile” error is returned. If the argument value is less than 0 or greater than 1, then a
“data value out of range” error is returned.
expression2

A sort specification that must be a single expression involving a column reference. Multiple expressions are
not allowed and no rank analytical functions, set functions, or subqueries are allowed in this sort
expression.

Remarks

The inverse distribution analytical functions return a k-th percentile value, which can be used to help establish a
threshold acceptance value for a set of data. The function PERCENTILE_DISC takes a percentile value as the
function argument and operates on a group of data specified in the WITHIN GROUP clause or operates on the

SAP IQ SQL Reference


SQL Functions INTERNAL 455
entire data set. The function returns one value per group. If the GROUP BY column from the query is not
present, the result is a single row. The data type of the results is the same as the data type of its ORDER BY
item specified in the WITHIN GROUP clause. PERCENTILE_DISC supports all data types that can be sorted in
SAP IQ.

PERCENTILE_DISC requires a WITHIN GROUP (ORDER BY) clause.

The ORDER BY clause, which must be present, specifies the expression on which the percentile function is
performed and the order in which the rows are sorted in each group. This ORDER BY clause is used only within
the WITHIN GROUP clause and is not an ORDER BY for the SELECT.

The WITHIN GROUP clause distributes the query result into an ordered data set from which the function
calculates a result. The WITHIN GROUP clause must contain a single sort item. If the WITHIN GROUP clause
contains more or less than one sort item, an error is reported.

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is the
default.

The PERCENTILE_DISC function is allowed in a subquery, a HAVING clause, a view, or a union.


PERCENTILE_DISC can be used anywhere the simple nonanalytical aggregate functions are used. The
PERCENTILE_DISC function ignores the NULL value in the data set.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Example

The following example uses the PERCENTILE_DISC function to determine the 10th percentile value for car
sales in a region.

The example uses the following data set:

sales region dealer_name


900 Northeast Boston
800 Northeast Worcester
800 Northeast Providence
700 Northeast Lowell
540 Northeast Natick
500 Northeast New Haven
450 Northeast Hartford
800 Northwest SF
600 Northwest Seattle
500 Northwest Portland
400 Northwest Dublin
500 South Houston
400 South Austin
300 South Dallas
200 South Dover

SAP IQ SQL Reference


456 INTERNAL SQL Functions
The following SELECT statement contains the PERCENTILE_DISC function:

SELECT region, PERCENTILE_DISC(0.1)


WITHIN GROUP ( ORDER BY sales DESC )
FROM carSales GROUP BY region;

The result of the SELECT statement lists the 10th percentile value for car sales in a region:

region percentile_cont
Northeast 900
Northwest 800
South 500

Related Information

NTILE Function [Analytical] [page 440]


PERCENTILE_CONT Function [Analytical] [page 453]

6.11.131 PI Function [Numeric]

Returns the numeric value pi.

 Syntax

PI ( * )

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise supports PI(), but not PI(*).

SAP IQ SQL Reference


SQL Functions INTERNAL 457
Example

The following statement returns the value 3.141592653…:

SELECT PI( * ) FROM iq_dummy

6.11.132 POWER Function [Numeric]

Calculates one number raised to the power of another.

 Syntax

POWER ( <numeric-expression1>, <numeric-expression2> )

Parameters

numeric-expression1

The base.
numeric-expression2

The exponent.

Returns

DOUBLE

Remarks

Raises <numeric-expression1> to the power <numeric-expresson2>.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


458 INTERNAL SQL Functions
Example

The following statement returns the value 64:

SELECT Power( 2, 6 ) FROM iq_dummy

6.11.133 PROPERTY Function [System]

Returns the value of the specified server-level property as a string.

 Syntax

PROPERTY ( { <property-id> | <property-name> } )

Parameters

property-id

An integer that is the property-number of the server-level property. This number can be determined from
the PROPERTY_NUMBER function. The <property-id> is commonly used when looping through a set of
properties.
property-name

A string giving the name of the property.

Returns

VARCHAR

Remarks

 Note

CIS functional compensation performance considerations apply.

Each property has both a number and a name, but the number is subject to change between versions, and
should not be used as a reliable identifier for a given property.

SAP IQ SQL Reference


SQL Functions INTERNAL 459
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the name of the current database server:

SELECT PROPERTY( 'Name' ) FROM iq_dummy

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


PROPERTY_NAME Function [System] [page 462]
PROPERTY_NUMBER Function [System] [page 463]
Properties Available for the Server [page 213]
Properties Available for Each Database [page 236]
Connection Properties [page 212]

6.11.134 PROPERTY_DESCRIPTION Function [System]

Returns a description of a property.

 Syntax

PROPERTY_DESCRIPTION ( { <property-id> | <property-name> } )

Parameters

property-id

An integer that is the property number of the property. This number can be determined from the
PROPERTY_NUMBER function. The <property-id> is commonly used when looping through a set of
properties.
property-name

A string giving the name of the property.

SAP IQ SQL Reference


460 INTERNAL SQL Functions
Returns

VARCHAR

Remarks

 Note

CIS functional compensation performance considerations apply.

Each property has both a number and a name, but the number is subject to change between releases, and
should not be used as a reliable identifier for a given property.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the description "Number of index insertions":

SELECT PROPERTY_DESCRIPTION( 'IndAdd' ) FROM iq_dummy

6.11.135 PROPERTY_IS_TRACKABLE function [System]

Returns whether or not you can maintain historical data for the specified database server property by storing
its tracked values.

 Syntax

PROPERTY_IS_TRACKABLE( <property-ID> )

Parameters

property-ID

SAP IQ SQL Reference


SQL Functions INTERNAL 461
The PropNum of the database server property. You can find the PropNum of the database server property
by running the sa_eng_properties system procedure or by calling the PROPERTY_NUMBER function.

Returns

1 if the database server property can be tracked; otherwise, returns 0.

Remarks

Only database properties that return a numeric value can be tracked.

 Example

The following example returns all database server properties that are trackable:

SELECT PropName FROM sa_eng_properties( ) WHERE


PROPERTY_IS_TRACKABLE( PropNum ) = 1;

6.11.136 PROPERTY_NAME Function [System]

Returns the name of the property with the supplied property number.

 Syntax

PROPERTY_NAME ( <property-id> )

Parameters

property-id

The property number of the property.

Returns

VARCHAR

SAP IQ SQL Reference


462 INTERNAL SQL Functions
Remarks

 Note

CIS functional compensation performance considerations apply.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the property associated with property number 126:

SELECT PROPERTY_NAME( 126 ) FROM iq_dummy

The actual property to which this refers changes from version to version.

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


PROPERTY Function [System] [page 459]
PROPERTY_NUMBER Function [System] [page 463]
Properties Available for the Server [page 213]
Properties Available for Each Database [page 236]
Connection Properties [page 212]

6.11.137 PROPERTY_NUMBER Function [System]

Returns the property number of the property with the supplied property name.

 Syntax

PROPERTY_NUMBER ( <property-name> )

SAP IQ SQL Reference


SQL Functions INTERNAL 463
Parameters

property-name

A property name.

Returns

INT

Remarks

 Note

CIS functional compensation performance considerations apply.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns an integer value:

SELECT PROPERTY_NUMBER( 'PAGESIZE' ) FROM iq_dummy

The actual value changes from version to version.

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


PROPERTY Function [System] [page 459]
PROPERTY_NAME Function [System] [page 462]
Properties Available for the Server [page 213]
Properties Available for Each Database [page 236]
Connection Properties [page 212]

SAP IQ SQL Reference


464 INTERNAL SQL Functions
Viewing all trackable database server property values [page 214]

6.11.138 QUARTER Function [Date and Time]

Returns a number indicating the quarter of the year from the supplied date expression.

 Syntax

QUARTER( <date-expression> )

Parameters

date-expression

A date.

Returns

INT

Remarks

This table lists the dates in the quarters of the year. Function assumes as starting quarter of 1 (January). For a
user-defined starting quarter, use QUARTERSTR.

Quarter Period (Inclusive)

1 January 1 to March 31

2 April 1 to June 30

3 July 1 to September 30

4 October 1 to December 31

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

SAP IQ SQL Reference


SQL Functions INTERNAL 465
● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

With the DATE_ORDER option set to the default of <ymd>, the following statement returns the value 2:

SELECT QUARTER ( '1987/05/02' ) FROM iq_dummy

Related Information

QUARTERSTR Function [Date and Time] [page 466]

6.11.139 QUARTERSTR Function [Date and Time]

Returns a number indicating the quarter of the year from the supplied date expression and quarter start
month.

 Syntax

QUARTERSTR( <date-expression>,[ <quarter_start_month> ] )

Parameters

date-expression

A date.
quarter_start_month Any integer 1 to 12. If not specified, default value is 1 (January).

Returns

A string in the format YYYY-QN where YYYY is year and N is quarter number.

SAP IQ SQL Reference


466 INTERNAL SQL Functions
Standards and Compatibility

● Nonstandard function.

Example

With the DATE_ORDER option set to the default of <ymd>, the following statement returns the value 1998-Q4:

SELECT QUARTERSTR ( '1999/01/28', 2 ) FROM iq_dummy

6.11.140 RADIANS Function [Numeric]

Converts a number from degrees to radians.

 Syntax

RADIANS ( <numeric-expression> )

Parameters

numeric-expression

A number, in degrees. This angle is converted to radians

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 467
Example

The following statement returns a value of approximately 0.5236:

SELECT RADIANS( 30 ) FROM iq_dummy

6.11.141 RAND Function [Numeric]

Returns a DOUBLE precision, random number x, where 0 <= x <1, with an optional seed.

 Syntax

RAND ( [ <integer-expression> ] )

Parameters

integer-expression

The optional seed used to create a random number. This argument allows you to create repeatable random
number sequences.

Returns

DOUBLE

Remarks

If RAND is called with a FROM clause and an argument in a query containing only tables in IQ stores, the function
returns an arbitrary but repeatable value.

When no argument is called, RAND is a non-deterministic function. Successive calls to RAND might return
different values. The query optimizer does not cache the results of the RAND function

 Note

The values returned by RAND vary depending on whether you use a FROM clause or not and whether the
referenced table was created in SYSTEM or in an IQ store.

SAP IQ SQL Reference


468 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns a 5% sampling of a table:

SELECT AVG(table1.number_of_cars),
AVG(table1.number_of_tvs)FROM table1 WHERE
RAND(ROWID(table1)) < .05 and table1.income < 50000;

● The following statement returns a value of approximately 941392926249216914:

SELECT RAND( 4 ) FROM iq_dummy

6.11.142 RANK Function [Analytical]

Ranks items in a group.

 Syntax

RANK () OVER ( [ PARTITION BY ] ORDER BY <expression> [ ASC | DESC ] )

Parameters

expression

A sort specification that can be any valid expression involving a column reference, aggregates, or
expressions invoking these items.

Returns

INTEGER

SAP IQ SQL Reference


SQL Functions INTERNAL 469
Remarks

RANK is a rank analytical function. The rank of row R is defined as the number of rows that precede R and are
not peers of R. If two or more rows are not distinct within the groups specified in the OVER clause or distinct
over the entire result set, then there are one or more gaps in the sequential rank numbering. The difference
between RANK and DENSE_RANK is that DENSE_RANK leaves no gap in the ranking sequence when there is a tie.
RANK leaves a gap when there is a tie.

RANK requires an OVER (ORDER BY) clause. The ORDER BY clause specifies the parameter on which ranking
is performed and the order in which the rows are sorted in each group. This ORDER BY clause is used only
within the OVER clause and is not an ORDER BY for the SELECT. No aggregation functions in the rank query are
allowed to specify DISTINCT.

The PARTITION BY window partitioning clause in the OVER (ORDER BY) clause is optional.

The ASC or DESC parameter specifies the ordering sequence ascending or descending. Ascending order is the
default.

The OVER clause indicates that the function operates on a query result set. The result set is the rows that are
returned after the FROM, WHERE, GROUP BY, and HAVING clauses have all been evaluated. The OVER clause
defines the data set of the rows to include in the computation of the rank analytical function.

RANK is allowed only in the select list of a SELECT or INSERT statement or in the ORDER BY clause of the
SELECT statement. RANK can be in a view or a union. The RANK function cannot be used in a subquery, a
HAVING clause, or in the select list of an UPDATE or DELETE statement. Only one rank analytical function is
allowed per query.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise or SAP SQL Anywhere

Example

This statement illustrates the use of the RANK function:

SELECT Surname, Sex, Salary, RANK() OVER (PARTITION BY Sex


ORDER BY Salary DESC) AS RANK FROM Employees
WHERE State IN ('CA', 'AZ') AND DepartmentID IN (200, 300)
ORDER BY Sex, Salary DESC;

The results from the above query:

Surname Sex Salary RANK


------- --- ------ ----
Savarino F 72300.000 1
Jordan F 51432.000 2
Clark F 45000.000 3
Coleman M 42300.000 1

SAP IQ SQL Reference


470 INTERNAL SQL Functions
Overbey M 39300.000 2

Related Information

DENSE_RANK Function [Analytical] [page 344]

6.11.143 READ_SERVER_FILE function [String]

Reads data from the specified file on the server and returns the full or partial contents of the file as a LONG
BINARY value.

 Syntax

READ_SERVER_FILE( <filename> ) [, <start> [ , <length>] ]

Parameters

filename

LONG VARCHAR value indicating the path and name of the file on the server.
start

The start position of the file to read, in bytes. The first byte in the file is at position 1. A negative starting
position specifies the number of bytes from the end of the file rather than from the beginning.

● If <start> is not specified, a value of 1 is used.


● If <start> is zero and <length> is non-negative, a value of 1 is used.
● If <start> is zero and <length> is negative, a value of -1 is used.
length

The length of the file to read, in bytes.

● If <length> is not specified, the function reads from the starting position to the end of the file.
● If <length> is positive, the function reads at most <length> bytes beginning at the starting position.
● If <length> is negative, the function returns at most <length> ending at the starting position.

Returns

LONG BINARY

SAP IQ SQL Reference


SQL Functions INTERNAL 471
Remarks

This function returns the full or partial (if <start> and/or <length> are specified) contents of the named file
as a LONG BINARY value. If the file does not exist or cannot be read, NULL is returned.

<filename> is relative to the starting directory of the database server.

The READ_SERVER_FILE function supports reading files larger than 2GB. However, the returned content is
limited to 2GB. If the returned content exceeds this limit, a SQL error is returned.

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 the character set conversion requirements you may have when using
the READ_SERVER_FILE server function.

If disk sandboxing is enabled, the file referenced in <filename> must be in an accessible location.

Privileges

When reading from a file on a client computer:

● You must have the READ FILE system privilege.


● You must have read permissions on the directory being read from.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement reads 20 bytes in a file, starting from byte 100 of the file.

SELECT READ_SERVER_FILE( 'c:\\data.txt', 100, 20 )

6.11.144 REGR_AVGX Function [Aggregate]

Computes the average of the independent variable of the regression line.

 Syntax

Syntax 1

REGR_AVGX ( <dependent-expression>, <independent-expression> )

SAP IQ SQL Reference


472 INTERNAL SQL Functions
Syntax 2

REGR_AVGX ( <dependent-expression>, <independent-expression> )


OVER ( <window-spec> )

Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_AVGX 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)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

SAP IQ SQL Reference


SQL Functions INTERNAL 473
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example calculates the average of the dependent variable, employee age:

SELECT REGR_AVGX( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.145 REGR_AVGY Function [Aggregate]

Computes the average of the dependent variable of the regression line.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

SAP IQ SQL Reference


474 INTERNAL SQL Functions
Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_AVGY returns NULL.

The function is applied to the set of (<dependent-expression> and <dependent-expression>) pairs


after eliminating all pairs for which either <dependent-expression> or <dependent-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)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example calculates the average of the independent variable, employee salary:

SELECT REGR_AVGY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )FROM Employees;

This function returns the value 49988.6232.

SAP IQ SQL Reference


SQL Functions INTERNAL 475
6.11.146 REGR_COUNT Function [Aggregate]

Returns an integer that represents the number of non-NULL number pairs used to fit the regression line.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

INTEGER

Remarks

This function returns an UNSIGNED BIGINT as the result.

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

SAP IQ SQL Reference


476 INTERNAL SQL Functions
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns a value that indicates the number of non-NULL pairs that were used to fit the
regression line:

SELECT REGR_COUNT( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

This function returns the value 75.

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.147 REGR_INTERCEPT Function [Aggregate]

Computes the y-intercept of the linear regression line that best fits the dependent and independent variables.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

SAP IQ SQL Reference


SQL Functions INTERNAL 477
Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, REGR_INTERCEPT 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 made, where <y> represents the <dependent-expression> and <x>
represents the <independent-expression>:

AVG(y) - REGR_SLOPE(y, x) * AVG(x)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the value 1874.5805688517603:

SELECT REGR_INTERCEPT( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM


Employees;

SAP IQ SQL Reference


478 INTERNAL SQL Functions
Related Information

Windowing Aggregate Function Usage [page 197]

6.11.148 REGR_R2 Function [Aggregate]

Computes the coefficient of determination (also referred to as R-squared or the goodness-of-fit statistic) for
the regression line.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_R2 returns NULL.

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

SAP IQ SQL Reference


SQL Functions INTERNAL 479
SAP IQ then applies the following algorithm, where <y> represents the <dependent-expression> and <x>
represents the <independent-expression>:

● REGR_R2 calculates VAR_POP(x) and returns NULL if VAR_POP(x) = 0; otherwise, it calculates


VAR_POP(y) and returns the value 1 if VAR_POP(y) = 0.
● If neither VAR_POP(x) or VAR_POP(y) is zero, the return value is POWER(CORR(y,x),2).

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the value 0.19379959710325653:

SELECT REGR_R2( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.149 REGR_SLOPE Function [Aggregate]

Computes the slope of the linear regression line, fitted to non-NULL pairs.

 Syntax

Syntax 1

REGR_SLOPE( <dependent-expression>, <independent-expression> )

Syntax 2

REGR_SLOPE( <dependent-expression>, <independent-expression> )

SAP IQ SQL Reference


480 INTERNAL SQL Functions
OVER ( <window-spec> )

Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_SLOPE returns NULL.

REGR_SLOPE 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 made, where <y> represents the <dependent-expression> and <x>
represents the <independent-expression>:

COVAR_POP(x, y) / VAR_POP(y)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

SAP IQ SQL Reference


SQL Functions INTERNAL 481
Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the value 935.3429749445614:

SELECT REGR_SLOPE( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.150 REGR_SXX Function [Aggregate]

Computes the slope of the linear regression line, fitted to non-NULL pairs.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

SAP IQ SQL Reference


482 INTERNAL SQL Functions
Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_SXX 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 made, where <y> represents the <dependent-expression> and <x>
represents the <independent-expression>:

REGR_COUNT(y, x) * VAR_POP(x)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the value 5916.4800000000105:

SELECT REGR_SXX( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

SAP IQ SQL Reference


SQL Functions INTERNAL 483
6.11.151 REGR_SXY Function [Aggregate]

Returns the sum of products of the dependent and independent variables. Use REGR_SXY to evaluate the
statistical validity of a regression model.

 Syntax

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.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If 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 made, where y represents the dependent-expression and x represents the
<independent-expression>:

REGR_COUNT(x, y) * COVAR_POP(x, y)

SAP IQ SQL Reference


484 INTERNAL SQL Functions
 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP SQL Anywhere

Example

The following example returns the value 5533938.004400015:

SELECT REGR_SXY( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.152 REGR_SYY Function [Aggregate]

Returns values that can evaluate the statistical validity of a regression model.

 Syntax

Syntax 1

REGR_SYY(<dependent-expression>, <independent-expression>)

Syntax 2

REGR_SYY(<dependent-expression>, <independent-expression>)
OVER (<window-spec>)

SAP IQ SQL Reference


SQL Functions INTERNAL 485
Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.


window-spec

Specified when using this function as a window function.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, performs the computation in double-precision floating-point,
and returns a DOUBLE as the result. If applied to an empty set, then REGR_SYY 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(x, y) * VAR_POP(y)

 Note

ROLLUP and CUBE are not supported in the GROUP BY clause with Syntax 1. DISTINCT is not supported.

Syntax 2 – The <window-spec> parameter represents usage as a window function in a SELECT statement. As
such, you can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW
clause in the SELECT statement.

Standards and Compatibility

● SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T612.


● SAP database products – compatible with SAP Adaptive Server Enterprise

SAP IQ SQL Reference


486 INTERNAL SQL Functions
Example

The following example returns the value 26, 708, 672,843.3002:

SELECT REGR_SYY( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )FROM Employees;

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.153 REMAINDER Function [Numeric]

Returns the remainder when one whole number is divided by another.

 Syntax

REMAINDER ( <dividend>, <divisor> )

Parameters

dividend

The dividend, or numerator of the division.


divisor

The divisor, or denominator of the division.

Returns

● INTEGER
● NUMERIC

Remarks

REMAINDER is the same as the MOD function.

SAP IQ SQL Reference


SQL Functions INTERNAL 487
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. The % (modulo) operator and
the division operator can be used to produce a remainder.

Example

The following statement returns the value 2:

SELECT REMAINDER( 5, 3 ) FROM iq_dummy

Related Information

MOD Function [Numeric] [page 427]

6.11.154 REPEAT Function [String]

Concatenates a string a specified number of times.

 Syntax

REPEAT ( <string-expression>, <integer-expression> )

Parameters

string-expression

The string to be repeated.


integer-expression

The number of times the string is to be repeated. If <integer-expression> is negative, an empty string
is returned.

SAP IQ SQL Reference


488 INTERNAL SQL Functions
Returns

● LONG VARCHAR
● LONG NVARCHAR

Remarks

 Note

The result data type is a LONG VARCHAR. If you use REPEAT in a SELECT INTO statement, you must have
an Unstructured Data Analytics Option license or use CAST and set REPEAT to the correct data type and
size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise, but REPLICATE provides the
same capabilities.

Example

The following statement returns the value "repeatrepeatrepeat":

SELECT REPEAT( 'repeat', 3 ) FROM iq_dummy

Related Information

REPLACE Function [String] [page 489]


REPLICATE Function [String] [page 492]

6.11.155 REPLACE Function [String]

Replaces all occurrences of a substring with another substring.

 Syntax

REPLACE ( <original-string>, <search-string>, <replace-string> )

SAP IQ SQL Reference


SQL Functions INTERNAL 489
Parameters

If any argument is NULL, the function returns NULL.

original-string

The string to be searched. This string can be any length.


search-string

The string to be searched for and replaced with <replace-string>. This string is limited to 255 bytes. If
<search-string> is an empty string, the original string is returned unchanged.
replace-string

The replacement string, which replaces <search-string>. This can be any length. If <replace-
string> is an empty string, all occurrences of <search-string> are deleted.

Returns

● LONG VARCHAR
● LONG NVARCHAR

 Note

The result data type is a LONG VARCHAR. If you use REPLACE in a SELECT INTO statement, you must have
an Unstructured Data Analytics Option license or use CAST and set REPLACE to the correct data type and
size.

Remarks

The result data type of a REPLACE function is a LONG VARCHAR. If you use REPLACE in a SELECT INTO
statement, you must have an Unstructured Data Analytics Option license, or use CAST and set REPLACE to the
correct data type and size.

There are two ways to work around this issue:

● Declare a local temporary table, then perform an INSERT:

DECLARE local temporary table #mytable


(name_column char(10)) on commit preserve rows;
INSERT INTO #mytable SELECT REPLACE(name,'0','1') FROM dummy_table01;

● Use CAST:

SELECT CAST(replace(name, '0', '1') AS Char(10)) into #mytable from


dummy_table01;

SAP IQ SQL Reference


490 INTERNAL SQL Functions
If you need to control the width of the resulting column when <replace-string> is wider than <search-
string>, use the CAST function. For example:

CREATE TABLE aa(a CHAR(5));


INSERT INTO aa VALUES('CCCCC');
COMMIT;
SELECT a, CAST(REPLACE(a,'C','ZZ') AS CHAR(5)) FROM aa;

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns the value "xx.def.xx.ghi":

SELECT REPLACE( 'abc.def.abc.ghi', 'abc', 'xx' ) FROM iq_dummy

● The following statement generates a result set containing ALTER PROCEDURE statements, which when
executed, 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%'

● Use a separator other than the comma for the LIST function:

SELECT REPLACE( list( table_id ), ',', '--')


FROM SYS.ISYSTAB
WHERE table_id <= 5

Related Information

AES_ENCRYPT Function [String] [page 268]


AES_DECRYPT Function [String] [page 270]
CAST Function [Data Type Conversion] [page 288]
CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
SECOND Function [Date and Time] [page 503]

SAP IQ SQL Reference


SQL Functions INTERNAL 491
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]
INSERTSTR Function [String] [page 390]
STUFF Function [String] [page 535]
LCASE Function [String] [page 401]
LEFT Function [String] [page 404]
LOWER Function [String] [page 417]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]
AES_DECRYPT Function [String] [page 270]
AES_ENCRYPT Function [String] [page 268]
REPEAT Function [String] [page 488]
REPLICATE Function [String] [page 492]

6.11.156 REPLICATE Function [String]

Concatenates a string a specified number of times.

 Syntax

REPLICATE ( <string-expression>, <integer-expression> )

Parameters

string-expression

The string to be repeated.


integer-expression

The number of times the string is to be repeated.

Returns

● LONG VARCHAR
● LONG NVARCHAR

SAP IQ SQL Reference


492 INTERNAL SQL Functions
Remarks

REPLICATE is the same as the REPEAT function.

 Note

The result data type is a LONG VARCHAR. If you use REPLICATE in a SELECT INTO statement, you must
have an Unstructured Data Analytics Option license or use CAST and set REPLICATE to the correct data
type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value "repeatrepeatrepeat":

SELECT REPLICATE( 'repeat', 3 ) FROM iq_dummy

Related Information

REPEAT Function [String] [page 488]


REPLACE Function [String] [page 489]

6.11.157 REVERSE Function [String]

Takes one argument as an input of type BINARY or STRING and returns the specified string with characters
listed in reverse order.

 Syntax

REVERSE ( <expression> | <uchar_expr> )

SAP IQ SQL Reference


SQL Functions INTERNAL 493
Parameters

expression

A character or binary-type column name, variable, or constant expression of CHAR, VARCHAR, NCHAR,
NVARCHAR, BINARY, or VARBINARY type.

Returns

LONG VARCHAR

LONG NVARCHAR

 Note

The result data type is a LONG VARCHAR. If you use REVERSE in a SELECT INTO statement, you must have
an Unstructured Data Analytics Option license or use CAST and set REVERSE to the correct data type and
size.

Remarks

● REVERSE, a string function, returns the reverse of expression.


● If expression is NULL, reverse returns NULL.
● Surrogate pairs are treated as indivisible and are not reversed.

Standards and Compatibility

SQL – Transact-SQL extension to ISO/ANSI SQL grammar

Examples

● The following statement returns the value "dcba":

select reverse("abcd")

● The following statement returns the value "0x00503412":

select reverse(0x12345000)

SAP IQ SQL Reference


494 INTERNAL SQL Functions
Related Information

String Operators [page 46]


LCASE Function [String] [page 401]
LEFT Function [String] [page 404]
LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]

6.11.158 RIGHT Function [String]

Returns the rightmost characters of a string.

 Syntax

RIGHT ( <string-expression>, <numeric-expression> )

Parameters

string-expression

The string to be left-truncated.


numeric-expression

The number of characters at the end of the string to return.

Returns

● LONG VARCHAR
● LONG NVARCHAR

Remarks

If the string contains multibyte characters, and the proper collation is being used, the number of bytes
returned might be greater than the specified number of characters.

SAP IQ SQL Reference


SQL Functions INTERNAL 495
 Note

The result data type is a LONG VARCHAR. If you use RIGHT in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set RIGHT to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value "olate":

SELECT RIGHT( 'chocolate', 5 ) FROM iq_dummy

Related Information

LCASE Function [String] [page 401]


LEFT Function [String] [page 404]
LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
UCASE Function [String] [page 548]
UPPER Function [String] [page 549]

6.11.159 ROUND Function [Numeric]

Rounds the <numeric-expression> to the specified <integer-expression> number of places after the
decimal point.

 Syntax

ROUND ( <numeric-expression>, <integer-expression> )

SAP IQ SQL Reference


496 INTERNAL SQL Functions
Parameters

numeric-expression

The number, passed to 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

When ROUND_TO_EVEN database option is set ON, the ROUND function rounds data from an SAP IQ table half to
the nearest even number to the integer-expression, matching the behavior of SAP SQL Anywhere table data.
When the option is set to OFF, the ROUND function rounds SAP IQ data half away from zero.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

● The following statement returns the value 123.200:

SELECT ROUND( 123.234, 1 ) FROM iq_dummy

Additional results of the ROUND function are shown in the following table:

Value ROUND (Value)

123.4567 round (a.n,4)

123.4570 round (a.n,3)

123.4600 round (a.n,2)

123.5000 round (a.n,1)

123.0000 round (a.n, 0)

SAP IQ SQL Reference


SQL Functions INTERNAL 497
Value ROUND (Value)

120.0000 round (a.n,-1)

100.0000 round (a.n,-2)

0.0000 round(a.n,-3)

● In the following examples, the ROUND_TO_EVEN settings affects the value returned.

ROUND_TO_EVEN
ROUND (Value) ON ROUND_TO_EVEN OFF Note

ROUND (convert (double, 123.5 123.5 0.05001 is more than half of


123.45001), 1) 0.1

ROUND (convert (double, 123.4 123.5 0.0500 is half of 0.1


123.45000), 1)

Related Information

TRUNCNUM Function [Numeric] [page 547]

6.11.160 ROW_NUMBER Function [Analytical]

A ranking function that returns a unique row number for each row in a window partition, restarting the row
numbering at the start of every window partition.

 Syntax

ROW_NUMBER() OVER ( [ PARTITION BY <window partition> ] ORDER BY <window


ordering> )

Parameters

window partition

(Optional) One or more value expressions separated by commas indicating how you want to divide the set
of result rows.
window ordering

Defines the expressions for sorting rows within window partitions, if specified, or within the result set if you
did not specify a window partition.

SAP IQ SQL Reference


498 INTERNAL SQL Functions
Remarks

If no window partitions exist, the function numbers the rows in the result set from 1 to the cardinality of the
table.

The ROW_NUMBER function requires an OVER (ORDER_BY) window specification. The window partitioning clause
in the OVER (ORDER_BY) clause is optional. The OVER (ORDER_BY) clause must not contain a window frame
ROWS/RANGE specification.

Standards and Compatibility

SQL – ISO/ANSI SQL compliant. SQL/OLAP feature T611.

Example

The following example returns salary data from the Employees table, partitions the result set by department ID,
and orders the data according to employee start date. The ROW_NUMBER function assigns each row a row
number, and restarts the row numbering for each window partition:

SELECT DepartmentID dID, StartDate, Salary, ROW_NUMBER()OVER(PARTITION


BY dID ORDER BY StartDate) FROM Employees ORDER BY 1,2;

The returned result set is:

dID StartDate Salary Row_number()


========= =========== ========== =============
100 1986-10-14 42,998.000 1
100 1987-07-23 39,875.500 2
100 1988-03-23 37,400.000 3
100 1989-04-20 42,500.000 4
100 1990-01-15 42,100.000 5
200 1985-02-03 38,500.000 1
200 1987-02-19 39,300.000 2
200 1988-11-22 39,800.000 3
200 1989-06-01 34,892.000 4
200 1990-05-13 33,890.000 5
200 1990-07-11 37,803.000 6

6.11.161 ROWID Function [Miscellaneous]

Returns the internal row ID value for each row of the table.

 Syntax

ROWID ( <table-name> ) … FROM <table-name>

SAP IQ SQL Reference


SQL Functions INTERNAL 499
Parameters

table-name

The name of the table. Specify the name of the table within the parentheses with either no quotes or with
double quotes.

Returns

UNSIGNED BIGINT

Remarks

You can use the ROWID function with other clauses to manipulate specific rows of the table.

You must specify the FROM <table-name> clause.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the row ID values 1 through 10:

SELECT ROWID( "PRODUCTS" ) FROM PRODUCTS

rowid(Products)

SAP IQ SQL Reference


500 INTERNAL SQL Functions
rowid(Products)

10

● The following statement returns the product ID and row ID value of all rows with a product ID value less
than 400:

SELECT PRODUCTS.ID, ROWID ( PRODUCTS )


FROM PRODUCTS
WHERE PRODUCTS.ID < 400

ID rowid (Products)

300 1

301 2

302 3

● The following statement deletes all rows with row ID values greater than 50:

DELETE FROM PRODUCTS


WHERE ROWID ( PRODUCTS ) > 50

6.11.162 RPAD Function [String]

Right-pads a string with spaces or a specified pattern to make a string that is a specified number of characters
in length.

 Syntax

RPAD ( <str>, <n> [, <pattern> ] )

Syntax Elements

str

The string to be padded.


n

The length to pad <str>. <n> must be an integer.


pattern

A string of characters, rather than spaces, to use for padding.

SAP IQ SQL Reference


SQL Functions INTERNAL 501
Description

Right-pads the end of <str> with spaces or characters to make a string of <n> characters in length. If
<pattern> is specified, then <str> is padded using sequences of the given characters until the required
length is met.

If the length of <str> is greater than <n>, then no padding is performed and the resulting value is truncated
from the right side to the length specified in <n>.

RPAD returns an empty string value if <n> is less than 1.

Examples

● The following example right-pads the end of string hello with the pattern 12345 to make a string of 15
characters in length and returns the value "hello1234512345":

SELECT RPAD ('hello', 15, '12345') "right pad" FROM DUMMY;

● In this example, <str> is longer than <n>, so no padding is performed; the result is <str> truncated to the
length of <n> (that is, "he"):

SELECT RPAD ('hello', 2, '12345') "right pad" FROM DUMMY;

● By not specifying <pattern>, this example right-pads the end of string hello with a single blank
character (that is, "hello "):

SELECT RPAD ('hello', 6) "right pad" FROM DUMMY;

6.11.163 RTRIM Function [String]

Returns a string, trimmed of all the trailing characters present in the trim character set.

 Syntax

RTRIM ( <string-expression>, [ <trim_character_set> ] )

Parameters

string-expression

The string to be trimmed.


trim_character_set The set of characters to use for trim.

SAP IQ SQL Reference


502 INTERNAL SQL Functions
Returns

Trimmed string.

Remarks

If trim character set is not specified, all training spaces in the string expression are trimmed.

Standards and Compatibility

● STANDARD function

Example

The following statement removes all trailing a and b characters from the given string and returns the value
babababAabend.

SELECT RTRIM ('babababAabendbababab','ab') "rtrim" FROM iq_dummy

Related Information

LTRIM Function [String] [page 419]


TRIM Function [String] [page 546]

6.11.164 SECOND Function [Date and Time]

Returns a number from 0 to 59 corresponding to the second component of the given date/time value.

 Syntax

SECOND ( <datetime-expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 503
Parameters

datetime-expression

The date and time value.

Returns

SMALLINT

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 5:

SELECT SECOND( '1998-07-13 08:21:05' ) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]

SAP IQ SQL Reference


504 INTERNAL SQL Functions
6.11.165 SECONDS Function [Date and Time]

Returns the number of seconds since an arbitrary starting date and time, the number of seconds between two
times, or adds an integer amount of seconds to a time.

 Syntax

SECONDS ( <datetime-expression>
| <datetime-expression>, <datetime-expression>
| <datetime-expression>, <integer-expression> )

Parameters

datetime-expression

A date and time.


integer-expression

The number of seconds to be added to the <datetime-expression>. If <integer-expression> is


negative, the appropriate number of minutes are subtracted from the date/time value. If you supply an
integer expression, the <datetime-expression> must be explicitly cast as a datetime data type.

Returns

● INTEGER
● TIMESTAMP

Remarks

The second syntax returns the number of whole seconds from the first date/time to the second date/time. The
number might be negative.

Standards and compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 505
Examples

● The following statement returns the value 3600:

SELECT ( SECONDS( '1998-07-13 06:07:12' ) -


SECONDS( '1998-07-13 05:07:12' )) FROM iq_dummy

● The following statement returns the value 14400, to signify the difference between the two times:

SELECT SECONDS( '1999-07-13 06:07:12',


'1999-07-13 10:07:12' ) FROM iq_dummy

● The following statement returns the datetime value 1999-05-12 21:05:12.000:

SELECT SECONDS( CAST( '1999-05-12 21:05:07'


AS TIMESTAMP ), 5) FROM iq_dummy

6.11.166 SIGN Function [Numeric]

Returns the sign of a number.

 Syntax

SIGN ( <numeric-expression> )

Parameters

numeric-expression

The number for which the sign is to be returned.

Returns

SMALLINT

Remarks

SIGN returns the following:

● -1 – for negative numbers


● 0 – for zero
● 1 – for positie numbers

SAP IQ SQL Reference


506 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value -1:

SELECT SIGN( -550 ) FROM iq_dummy

6.11.167 SIMILAR Function [String]

Returns an integer between 0 and 100 representing the similarity between two strings.

 Syntax

SIMILAR ( <string-expression1>, <string-expression2> )

Parameters

string-expression1

The first string to be compared.


string-expression2

The second string to be compared.

Returns

SMALLINT

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.

SAP IQ SQL Reference


SQL Functions INTERNAL 507
This function can be used to correct a list of names (such as customers). Some customers might have been
added to the list more than once with slightly different names. Join the table to itself and produce a report of all
similarities greater than 90 percent but less than 100 percent.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 75:

SELECT SIMILAR( 'toast', 'coast' ) FROM iq_dummy

This signifies that the two values are 75% similar.

6.11.168 SIN Function [Numeric]

Returns the sine of a number, expressed in radians.

 Syntax

SIN ( <numeric-expression> )

Parameters

numeric-expression

The angle, in radians.

Returns

DOUBLE

SAP IQ SQL Reference


508 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 0.496880:

SELECT SIN( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
TAN Function [Numeric] [page 544]

6.11.169 SORTKEY Function [String]

Generates values that can be used to sort character strings based on alternate collation rules.

 Syntax

SORTKEY ( <string-expression> [, { <collation-id>


| <collation-name> [ ( <collation-tailoring-string> ) ] } ] )

Parameters

string-expression

The string expression must contain characters that are encoded in the character set of the database and
must be STRING data type.

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.

SAP IQ SQL Reference


SQL Functions INTERNAL 509
There is no limit on the length of the input string that the SORTKEY function can handle. The result of
SORTKEY is always limited to 1024 bytes and is VARBINARY data type. If the actual results exceed 1024
bytes, the result contains only the first 1024 bytes.
collation-id

A variable, integer constant, or string that specifies the ID number of the sort order to use. This parameter
applies only to SAP ASE collations, which can be referred to by their corresponding collation ID.
collation-name

A string or 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 sort-keys as used by the CHAR collation in use by
the database.

Similarly, you can specify the alias NCHAR_COLLATION to generate sort-keys as used by the NCHAR
collation in use by the database. However, SAP IQ does not support NCHAR_COLLATION for SAP IQ-
specific objects. NCHAR_COLLATION is supported for SAP SQL Anywhere objects on an SAP IQ server.
collation-tailoring-string

(Optional) Specify collation tailoring options (<collation-tailoring-string>) for additional control


over sorting and comparison of characters. These options take the form of keyword=value pairs assembled
in parentheses, following the collation name. For example:

'UCA(locale=es;case=LowerFirst;accent=respect)'

The syntax for specifying these options is identical to the COLLATION clause of the CREATE DATABASE
statement.

 Note

All of the collation tailoring options are supported for SAP SQL Anywhere databases, when specifying
the Unicode Collation Algorithm (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.

SAP IQ SQL Reference


510 INTERNAL SQL Functions
For example, you can store the values returned by the SORTKEY function in a column with the source character
string. The following SELECT statement retrieves data from table T1 in the sorted order of c1 according to the
Thai dictionary:

SELECT rid, c1 from T1 ORDER BY SORTKEY(c1)

You instead store the value returned by SORTKEY in a column with the source character string. To retrieve the
character data in the required order, the SELECT statement needs to include only an ORDER BY clause on the
column that contains the results of running the SORTKEY function:

UPDATE T1 SET shadowc1=SORTKEY(c1) FROM T1;


SELECT rid, c1 FROM T1 ORDER BY shadowc1

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 sort-keys for queries can be expensive. As an alternative for frequently requested sort-keys,
consider creating a computed column to hold the sort-key values, and then referencing that column in the
ORDER BY clause of the query.

If you do not specify a collation name or collation ID, the default is Default Unicode multilingual.

Valid collations are as follows:

● To see collations that are supported by SAP IQ, listed by label, execute iqinit -l.
● The SAP ASE collations are listed in the table below.

Description Collation Name Collation ID

Default Unicode multilingual default 0

CP 850 Alternative: no accent altnoacc 39

CP 850 Alternative: lowercase first altdict 45

CP 850 Western European: no case, preference altnocsp 46

CP 850 Scandinavian dictionary scandict 47

CP 850 Scandinavian: no case, preference scannocp 48

GB Pinyin gbpinyin n/a

Binary sort binary 50

Latin-1 English, French, German dictionary dict 51

Latin-1 English, French, German no case nocase 52

Latin-1 English, French, German no case, preference nocasep 53

Latin-1 English, French, German no accent noaccent 54

Latin-1 Spanish dictionary espdict 55

SAP IQ SQL Reference


SQL Functions INTERNAL 511
Description Collation Name Collation ID

Latin-1 Spanish no case espnocs 56

Latin-1 Spanish no accent espnoac 57

ISO 8859-5 Russian dictionary rusdict 58

ISO 8859-5 Russian no case rusnocs 59

ISO 8859-5 Cyrillic dictionary cyrdict 63

ISO 8859-5 Cyrillic no case cyrnocs 64

ISO 8859-7 Greek dictionary elldict 65

ISO 8859-2 Hungarian dictionary hundict 69

ISO 8859-2 Hungarian no accents hunnoac 70

ISO 8859-2 Hungarian no case hunnocs 71

ISO 8859-5 Turkish dictionary turdict 72

ISO 8859-5 Turkish no accents turnoac 73

ISO 8859-5 Turkish no case turnocs 74

CP 874 (TIS 620) Royal Thai dictionary thaidict 1

ISO 14651 ordering standard 14651 22

Shift-JIS binary order sjisbin 179

Unicode UTF-8 binary sort utf8bin 24

EUC JIS binary order eucjisbn 192

GB2312 binary order gb2312bn 137

CP932 MS binary order cp932bin 129

Big5 binary order big5bin 194

EUC KSC binary order euckscbn 161

With respect to collation tailoring, full sensitivity is generally the intent when creating sort-keys, so when you
specify a non-UCA collation, the default tailoring applied is equivalent to case=Respect. For example, the
following two statements are equivalent:

SELECT SORTKEY( 'abc', '1252LATIN1' );


SELECT SORTKEY( 'abc', '1252LATIN1(case=Respect)' );

SAP IQ SQL Reference


512 INTERNAL SQL Functions
When specifying a non-UCA collation, by default, collation tailorings are accent and case-sensitive. However,
for non-UCA collations, you can override only the case sensitivity using a collation tailoring. For example:

SELECT SORTKEY( 'abc', '1252LATIN1(case=LowerFirst)' );

If the database was created without specifying tailoring options, 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 )

Different sort orders may be generated, 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 created using a version of SAP IQ earlier than 15.0 do not contain the same values created
using version 15.0 and later. This may be a problem for your applications if your pre- 15.0 database has sort-
key values stored within it, especially if sort-key value comparison is required by your application.
Regenerate any sort-key values in your database that were generated using a version of SAP IQ earlier than
15.0.

Standards and Compatibility

SQL – vendor extension to ISO/ANSI SQL grammar

Example

The following statement queries the Employees table and returns the FirstName and Surname of all
employees, sorted by the sort-key values for the Surname column using the dict collation (Latin-1, English,
French, German dictionary):

SELECT Surname, GivenName FROM Employees ORDER BY SORTKEY( Surname, 'dict' );

SAP IQ SQL Reference


SQL Functions INTERNAL 513
6.11.170 SOUNDEX Function [String]

Returns a number representing the sound of a string.

 Syntax

SOUNDEX ( <string-expression> )

Parameters

string-expression

The string.

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. Doubled letters are counted as one letter. The following example is based on the letters A, P, L, and S:

SOUNDEX( 'apples' ) FROM iq_dummy

Multibyte characters are ignored by the SOUNDEX function.

Although it is not perfect, SOUNDEX normally returns the same number for words that sound similar and that
start with the same letter.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise, except that SAP ASE returns a
CHAR(4) result and SAP IQ returns an integer.

SAP IQ SQL Reference


514 INTERNAL SQL Functions
Example

The following statement returns two numbers, representing the sound of each name. The SOUNDEX value for
each argument is 3827:

SELECT SOUNDEX( 'Smith' ), SOUNDEX( 'Smythe' ) FROM iq_dummy

SOUNDEX ( 'Smith' ) is equal to SOUNDEX ( 'Smythe' ).

Related Information

DIFFERENCE Function [String] [page 346]

6.11.171 SP_HAS_ROLE Function [System]

Returns an integer value indicating whether the invoking user has been granted a specified system privilege or
user-defined role. When used for privilege checking within user-defined stored procedures, SP_HAS_ROLE
returns an error message when a user fails a privilege check.

 Syntax

SP_HAS_ROLE ( [ <rolename> ], [ <grant_type> ], [ <throw_error> ] )

Parameters

rolename

The name of a system privilege or user-defined role.


grant_type

Valid values are: ADMIN and NO ADMIN. If NULL or not specified, NO ADMIN is used by default.
throw_error

Valid values are:

● 1 – display error message specified if system privilege or user-defined role is not granted to invoking
user.
● 0 – (default) do not display error message if specified system privilege or user-defined role is not
granted to invoking user.

SAP IQ SQL Reference


SQL Functions INTERNAL 515
Returns

Value Description

1 System privilege or user-defined role is granted to invoking user.

0 or Permission denied: you System privilege or user-defined role is not granted to invoking user. The error
do not have permission to message replaces the value 0 when the throw_error argument is set to 1.
execute this command/
procedure.

-1 The system privilege or user-defined role specified does not exist. No error mes­
sage appears, even if the throw_error argument is set to 1.

Remarks

If the value of the grant_type argument is ADMIN, the function checks whether the invoking user has
administrative privileges for the system privilege. If the value of the grant_type argument is NO ADMIN, the
function checks whether the invoking user has privileged use of the system privilege or role.

If the grant_type argument is not specified, NO ADMIN is used by default and output indicates only whether
the invoking user has been granted, either directly or indirectly, the specified system privilege or user-defined
role.

If the rolename and grant_type arguments are both NULL and the throw_error argument is 1, you see an
error message. You may find this useful for those stored procedures where an error message appears after
certain values are read from the catalog tables rather than after the checking the presence of certain system
privileges for the invoking user.

 Note

A permission denied error message is returned if the arguments rolename and grant_type are set to
NULL and throw_error is set to 1, or if all three arguments are set to NULL.

Examples

The examples use the following scenario:

● u1 has been granted the CREATE ANY PROCEDURE system privilege with the WITH NO ADMIN OPTION
clause.
● u1 has not been granted the CREATE ANY TABLE system privilege.
● u1 has been granted the user-defined role Role_A with the WITH ADMIN ONLY OPTION clause.
● Role_B exists, but has not been granted to u1
● The role Role_C does not exist.

SAP IQ SQL Reference


516 INTERNAL SQL Functions
The sp_has_role examples are:

● The following example returns the value 1, which indicates u1 has been granted the CREATE ANY
PROCEDURE system privilege:

sp_has_role 'create any procedure'

● The following example returns the value 0, which indicates u1 has not been granted the CREATE ANY
TABLE system privilege:

sp_has_role 'create any table'

No error message is returned because the throw_error argument is not specified.


● The following example returns the Permission denied error message (throw_error=1):

sp_has_role 'create any procedure','admin',1

Even though u1 has been granted the CREATE ANY PROCEDURE system privilege, u1 has not been
granted administrative rights to the system privilege.
● The following example returns the value 1, which indicates u1 has been granted role Role_A:

sp_has_role 'Role_A'

● The following example returns the value 1, which indicates u1 has been granted role Role_A with
administrative rights:

sp_has_role 'Role_A','admin',1

● The following example returns the value 0, which indicates u1 has not been granted the role ROLE_B:

sp_has_role 'Role_B'

No error message is returned because the throw_error argument is not specified.


● The following example returns the value -1, which indicates the role ROLE_C does not exist:

sp_has_role 'Role_C'

● The following example returns the value -1, which indicates the role ROLE_C does not exist:

sp_has_role 'Role_C',NULL,1

6.11.172 SPACE Function [String]

Returns a specified number of spaces.

 Syntax

SPACE ( <integer-expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 517
Parameters

integer-expression

The number of spaces to return.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use SPACE in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license or use CAST and set SPACE to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns a string containing 10 spaces:

SELECT SPACE( 10 ) FROM iq_dummy

6.11.173 SQLFLAGGER Function [Miscellaneous]

Returns the conformity of a given SQL statement to a specified standard.

 Syntax

SQLFLAGGER ( <sql-standard-string>, <sql-statement-string> )

Parameters

sql-standard-string

SAP IQ SQL Reference


518 INTERNAL SQL Functions
The standard level against which to test compliance. Possible values are the same as for the
SQL_FLAGGER_ERROR_LEVEL database option:

● SQL:2003/Core – test for conformance to core SQL/2003 syntax.


● SQL:2003/Package – test for conformance to full SQL/2003 syntax.
● SQL:1999/Core – test for conformance to core SQL/1999 syntax.
● SQL:1999/Package – test for conformance to full SQL/1999 syntax.
● SQL:1992/Entry – test for conformance to entry-level SQL/1992 syntax.
● SQL:1992/Intermediate – test for conformance to intermediate-level SQL/1992 syntax.
● SQL:1992/Full – test for conformance to full-SQL/1992 syntax.
sql-statement-string

The SQL statement to check for conformance.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use SQLFLAGGER in a SELECT INTO statement, you must
have an Unstructured Data Analytics Option license or use CAST and set SQLFLAGGER to the correct data
type and size.

Remarks

You can also use the iqsqlpp SQL Preprocessor Utility to flag any Embedded SQL that is not part of a specified
set of SQL92. See iqsqlpp SQL Preprocessor Utility in the Utility Guide.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement shows an example of the message that is returned when a disallowed extension is
found:

SELECT SQLFLAGGER( 'SQL:2003/Package',

SAP IQ SQL Reference


SQL Functions INTERNAL 519
'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 contains no disallowed extensions:

SELECT SQLFLAGGER( 'SQL:2003/Package', 'SELECT dummy_col FROM sys.dummy' );

6.11.174 SQRT Function [Numeric]

Returns the square root of a number.

 Syntax

SQRT ( <numeric-expression> )

Parameters

numeric-expression

The number for which the square root is to be calculated.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 3:

SELECT SQRT( 9 ) FROM iq_dummy

SAP IQ SQL Reference


520 INTERNAL SQL Functions
6.11.175 SQUARE Function [Numeric]

Returns the square of the specified expression as a float.

 Syntax

SQUARE ( <numeric-expression> )

Parameters

numeric-expression

Is a column, variable, or expression with a data type that is either exact numeric, approximate numeric,
money, or any type that can be implicitly converted to one of these types. For other data types, the
SQUARE function generates an error. The return value is of DOUBLE data type.

Remarks

SQUARE function takes one argument. For example, SQUARE (<12.01>) returns 144.240100.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

6.11.176 STACK_TRACE function [Miscellaneous]

Returns information about the stack trace for the current statement.

 Syntax

sa_stack_trace(
[ stack_frames
[, detail_level
[, connection_id ] ] ]
)

SAP IQ SQL Reference


SQL Functions INTERNAL 521
Parameters

stack_frames

Controls whether to include procedures, outer-statements, or both.

'procedure'

Return procedures but not the outer-most statement. This is the default behavior.
'caller'

Return only the outer-most statement (the statement that arrived from the client).
'procedure+caller', 'caller+procedure'

Return all statements.


detail_level

Controls the level of detail to include in the returned data.

'stack'

Include procedure names and line numbers. This is the default behavior.
'stack+sql', 'sql+stack'

Include the procedure names and line numbers, as well as the SQL text of the statement being
executed at each level.
connection_id

Use the connection_id option to filter the results returned to the specified connection ID.

Returns

LONG VARCHAR representing the stack trace of the current statement.

Remarks

The result contains lines of text delimited by line feed (\n) characters. Each line of the returned value contains
the qualified procedure name or batch type, followed by the line number of the statement. The last line of the
returned value is not terminated by a line feed character. The first line of the stack trace represents the line
where the function was invoked. If a compound statement is not part of a procedure, function, trigger, or event,
then the type of batch (watcom_batch or tsql_batch) is returned instead of the procedure name.

This function returns line numbers as found in the proc_defn column of the SYSPROCEDURE system table for
the procedure. These line numbers might differ from those of the source definition used to create the
procedure.

This function returns the same information as the sa_stack_trace system procedure.

SAP IQ SQL Reference


522 INTERNAL SQL Functions
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following example illustrates a procedure call stack trace:

CREATE OR REPLACE PROCEDURE proc3()


BEGIN
DECLARE v INTEGER;
SET v = 1;
SELECT * FROM sa_split_list( STACK_TRACE('caller+procedure', 'stack+sql'),
'\n' );
END;
CREATE OR REPLACE PROCEDURE proc2()
BEGIN
CALL proc3();
END;
CREATE OR REPLACE PROCEDURE proc1()
BEGIN
CALL proc2();
END;
CALL proc1();

Results:

line_num row_value
------------------------------------------------------------------------------
--------------------------------------------------
1 "DBA"."proc3" : 5 : select
sa_split_list.line_num,sa_split_list.row_value from
sa_split_list(STACK_TRACE('caller+procedure','stack
+sql'),'\x0A')

2 "DBA"."proc2" : 3 : call
proc3()

3 "DBA"."proc1" : 3 : call
proc2()

4 call proc1(

Related Information

sa_stack_trace system procedure [page 901]


sa_stack_trace system procedure [page 901]

SAP IQ SQL Reference


SQL Functions INTERNAL 523
6.11.177 STDDEV Function [Aggregate]

Returns the standard deviation of a set of numbers.

 Syntax

STDDEV ( [ ALL ] <expression> )

Parameters

expression

Any numeric data type (FLOAT, REAL, or DOUBLE precision) expression.

Returns

DOUBLE

Remarks

The formula used to calculate STDDEV is:

STDDEV returns a result of data type DOUBLE precision floating-point. If applied to the empty set, the result is
NULL, which returns NULL for a one-element input set.

STDDEV does not support the keyword DISTINCT. A syntax error is returned if you use DISTINCT with STDDEV.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


524 INTERNAL SQL Functions
Example

● Given this data:

SELECT Salary FROM Employees WHERE DepartmentID = 300

Salary

51432.000

57090.000

42300.000

43700.00

36500.000

138948.000

31200.000

58930.00

75400.00

The following statement returns the value 32617.8446712838471:

SELECT STDDEV ( Salary ) FROM Employees


WHERE DepartmentID = 300

● Given this data:

SELECT UnitPrice FROM Products WHERE Name = 'Tee Shirt'

Name UnitPrice

Tee Shirt 9.00

Tee Shirt 14.00

Tee Shirt 14.00

The following statement returns the value 2.88675134594813049:

SELECT STDDEV ( UnitPrice ) FROM Products


WHERE Name = 'Tee Shirt'

SAP IQ SQL Reference


SQL Functions INTERNAL 525
Related Information

Windowing Aggregate Function Usage [page 197]


STDDEV_SAMP Function [Aggregate] [page 527]
VARIANCE Function [Aggregate] [page 558]

6.11.178 STDDEV_POP Function [Aggregate]

Computes the standard deviation of a population consisting of a numeric-expression, as a DOUBLE.

 Syntax

STDDEV_POP ( [ ALL ] <expression> )

Parameters

expression

The expression (commonly a column name) that has a population-based standard deviation that is
calculated over a set of rows.

Returns

DOUBLE

Remarks

Computes the population standard deviation of the provided <value expression> evaluated for each row of
the group or partition (if DISTINCT was specified, then each row that remains after duplicates have been
eliminated), defined as the square root of the population variance.

SAP IQ SQL Reference


526 INTERNAL SQL Functions
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement lists the average and variance in the number of items per order in different time
periods:

SELECT year( ship_date ) AS Year, quarter( ship_date )


AS Quarter, AVG( quantity ) AS Average,
STDDEV_POP ( quantity ) AS Variance
FROM SalesOrderItems GROUP BY Year, Quarter
ORDER BY Year, Quarter;

Year Quarter Average Variance

2000 1 25.775148 14.2794

2000 2 27.050847 15.0270

... ... ... ...

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.179 STDDEV_SAMP Function [Aggregate]

Computes the standard deviation of a sample consisting of a numeric-expression, as a DOUBLE.

 Syntax

STDDEV_SAMP ( [ ALL ] <expression> )

Parameters

expression

SAP IQ SQL Reference


SQL Functions INTERNAL 527
The expression (commonly a column name) whose sample-based standard deviation is calculated over a
set of rows.

Returns

DOUBLE

Remarks

 Note

STDDEV_SAMP is an alias for STDDEV.

Computes the sample standard deviation of the provided <value expression> evaluated for each row of the
group or partition (if DISTINCT was specified, then each row that remains after duplicates have been
eliminated), defined as the square root of the sample variance.

NULL returns NULL for a one-element input set.

Standard deviations are computed according to the following formula, which assumes a normal distribution:

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement lists the average and variance in the number of items per order in different time
periods:

SELECT year( ship_date ) AS Year, quarter( ship_date )


AS Quarter, AVG( quantity ) AS Average,
STDDEV_SAMP( quantity ) AS Variance
FROM SalesOrderItems GROUP BY Year, Quarter
ORDER BY Year, Quarter;

SAP IQ SQL Reference


528 INTERNAL SQL Functions
Year Quarter Average Variance

2000 1 25.775148 14.3218

2000 2 27.050847 15.0696

... ... ... ...

Related Information

Windowing Aggregate Function Usage [page 197]


STDDEV Function [Aggregate] [page 524]
VARIANCE Function [Aggregate] [page 558]

6.11.180 STR Function [String]

Returns the string equivalent of a number.

 Syntax

STR ( <numeric-expression> [ , <length>[ , <decimal> ] ] )

Parameters

numeric-expression

Any approximate numeric (FLOAT, REAL, or DOUBLE precision) expression.


length

The number of characters to be returned (including the decimal point, all digits to the right and left of the
decimal point, the sign, if any, and blanks). The default is 10 and the maximum length is 255.
decimal

The number of digits to the right of the decimal point to be returned. The default is 0.

Returns

VARCHAR

SAP IQ SQL Reference


SQL Functions INTERNAL 529
Remarks

If the integer portion of the number cannot fit in the length specified, then the result is NULL.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Examples

● The following statement returns a string of six spaces followed by 1234, for a total of 10 characters:

SELECT STR( 1234.56 ) FROM iq_dummy

● The following statement returns the result 1234.5:

SELECT STR( 1234.56, 6, 1 ) FROM iq_dummy

● The following statement returns NULL because the integer portion of the number cannot fit in the specified
length:

SELECT STR( 1234.56, 3 ) FROM iq_dummy

6.11.181 STR_REPLACE Function [String]

Takes three arguments as input of type BINARY or STRING and replaces any instances of the second string
expression (<string_expr2>) that occur within the first string expression (<string_expr1>) with a third
expression (<string_expr3>).

 Syntax

REPLACE ( <string_expr1>, <string_expr2>, <string_expr3> )

Parameters

string_expr1

The source string, or the string expression to be searched, expressed as CHAR, VARCHAR, UNICHAR,
UNIVARCHAR, VARBINARY, or BINARY data type.
string_expr2

SAP IQ SQL Reference


530 INTERNAL SQL Functions
The pattern string, or the string expression to find within the first expression (<string_expr1>) and is
expressed as CHAR, VARCHAR, UNICHAR, UNIVARCHAR, VARBINARY, or BINARY data type.
string_expr3

The replacement string expression, expressed as CHAR, VARCHAR, UNICHAR, UNIVARCHAR, VARBINARY, or
BINARY data type.

Remarks

STR_REPLACE is an alias of REPLACE function.

● Takes any data type as input and returns STRING or BINARY.


For example, an empty string passed as an argument ("") is replaced with one space (" ") before further
evaluation occurs. This is true for both BINARY and STRING types.
● All arguments can have a combination of BINARY and STRING data types.
● The result length may vary, depending upon what is known about the argument values when the
expression is compiled. If all arguments are columns or host variables assigned to constants, SAP IQ
calculates the result length as:

result_length = ((s/p)*(r-p)+s)
WHERE
s = length of source string
p = length of pattern string
r = length of replacement string
IF (r-p) <= 0, result length = s

● If SAP IQ cannot calculate the result length because the argument values are unknown when the
expression is compiled, the result length used is 255.
● RESULT_LEN never exceeds 32767.

Standards and Compatibility

SQL – Transact-SQL extension to ISO/ANSI SQL grammar

Examples

● Replaces the string <def> within the string <cdefghi> with <yyy>:

select replace("cdefghi", "def", "yyy")


-------------
cyyyghi
(1 row(s) affected)

● Replaces all spaces with “toyota”:

select str_replace ("chevy, ford, mercedes", "","toyota")


----------

SAP IQ SQL Reference


SQL Functions INTERNAL 531
chevy,toyotaford,toyotamercedes
(1 row(s) affected)

● Accepts NULL in the third parameter and treats it as an attempt to replace <string_expr2> with NULL,
effectively turning STR_REPLACE into a “string cut” operation. Returns “abcghijklm”:

select str_replace("abcdefghijklm", "def", NULL)


----------
abcghijklm
(1 row affected)

Related Information

BIT_LENGTH Function [String] [page 281]


BYTE_LENGTH Function [String] [page 283]
CHAR_LENGTH Function [String] [page 293]
COL_LENGTH Function [System] [page 299]
DATALENGTH Function [System] [page 316]
LEN Function [String] [page 405]
LENGTH Function [String] [page 406]
OBJECT_NAME Function [System] [page 446]
OCTET_LENGTH Function [String] [page 447]

6.11.182 STRING Function [String]

Concatenates one or more strings into one large string.

 Syntax

STRING ( <string-expression> [ , … ] )

Parameters

string-expression

A string. If only one argument is supplied, it is converted into a single expression. If more than one
argument is supplied, they are concatenated into a single string. A NULL is treated as an empty string ('').

SAP IQ SQL Reference


532 INTERNAL SQL Functions
Returns

● LONG BINARY
● LONG NVARCHAR
● LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use STRING in a SELECT INTO statement, you must have
an Unstructured Data Analytics Option license or use CAST and set STRING to the correct data type and
size.

Remarks

Numeric or date parameters are converted to strings before concatenation. You can also use the STRING
function to convert any single expression to a string by supplying that expression as the only parameter.

If all parameters are NULL, STRING returns NULL.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value testing123:

SELECT STRING( 'testing', NULL, 123 )


FROM iq_dummy

6.11.183 STRTOUUID Function [String]

Converts a string value to a unique identifier (UUID or GUID) value.

 Syntax

STRTOUUID ( <string-expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 533
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, NULL is returned.

You can use STRTOUUID to insert UUID values into an SAP IQ database.

Standards and Compatibility

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

CREATE TABLE T (
pk uniqueidentifier primary key,
c1 int);
INSERT INTO T (pk, c1)
VALUES (STRTOUUID
('12345678-1234-5678-9012-123456789012'), 1);

Related Information

Binary Data Types [page 123]


NEWID Function [Miscellaneous] [page 432]
UUIDTOSTR Function [String] [page 553]
Character Data Types [page 115]
Binary Data Type Compatibility [page 159]

SAP IQ SQL Reference


534 INTERNAL SQL Functions
6.11.184 STUFF Function [String]

Deletes a number of characters from one string and replaces them with another string.

 Syntax

STUFF ( <string-expression1>, <start>, <length>, <string-expression2> )

Parameters

string-expression1

The string to be modified by the STUFF function.


start

The character position at which to begin deleting characters. The first character in the string is position 1.
length

The number of characters to delete.


string-expression2

The string to be inserted. To delete a portion of a string using the STUFF function, use a replacement string
of NULL

Returns

LONG VARCHAR or LONG NVARCHAR, depending on the data type of the input expressions.

Remarks

To delete a portion of a string using STUFF, use a replacement string of NULL. To insert a string using STUFF,
use a length of zero.

The STUFF function will return a NULL result in the following situations:

● Any of the first three parameters is a NULL value.


● Either the start or length parameter is a negative value.
● The start parameter is greater than the length of string-expression1.

SAP IQ SQL Reference


SQL Functions INTERNAL 535
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value “chocolate pie”:

SELECT STUFF( 'chocolate cake', 11, 4, 'pie' )


FROM iq_dummy

Related Information

INSERTSTR Function [String] [page 390]


REPLACE Function [String] [page 489]

6.11.185 SUBSTRING Function [String]

Returns a substring of a string.

 Syntax

{ SUBSTRING | SUBSTR } ( <string-expression>, <start> [ , <length> ] )

Parameters

string-expression

The string from which a substring is to be returned.


start

The start position of the substring to return, in characters. A negative starting position specifies a number
of characters from the end of the string instead of the beginning. The first character in the string is at
position 1.
length

The length of the substring to return, in characters:

● A positive <length> specifies that the substring ends <length> characters to the right of the starting
position.

SAP IQ SQL Reference


536 INTERNAL SQL Functions
● A negative <length> specifies that the substring ends <length> characters to the left of the starting
position.

Returns

● LONG BINARY
● LONG NVARCHAR
● LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use STRING in a SELECT INTO statement, you must have
an Unstructured Data Analytics Option license or use CAST and set STRING to the correct data type and
size.

Remarks

If <length> is specified, the substring is restricted to that length. If no length is specified, the remainder of the
string is returned, starting at the <start> position.

Both <start> and <length> can be negative. Using appropriate combinations of negative and positive
numbers, you can get a substring from either the beginning or end of the string.

When the ansi_substring database option is set to ON (default), negative values are invalid.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – SAP Adaptive Server Enterprise does not support SUBSTR; use SUBSTRING
instead.

Example

● The following statement returns back:

SELECT SUBSTRING ( 'back yard', 1 , 4 )


FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 537
● The following statement returns yard:

SELECT SUBSTR ( 'back yard', -1 , -4 )


FROM iq_dummy

● The following statement returns 0x2233:

SELECT SUBSTR ( 0x112233445566, 2, 2 )


FROM iq_dummy

In this section:

SUBSTRING Function [Unstructured Data Analytics] [page 538]


The SUBSTRING function returns a variable-length character string of the LONG VARCHAR column or
variable parameter. If any of the arguments are NULL, SUBSTRING returns NULL.

Related Information

CHARINDEX Function [String] [page 296]


ANSI_SUBSTRING Option [TSQL] [page 1761]
ANSI_SUBSTRING Option [TSQL] [page 1761]

6.11.185.1 SUBSTRING Function [Unstructured Data


Analytics]

The SUBSTRING function returns a variable-length character string of the LONG VARCHAR column or variable
parameter. If any of the arguments are NULL, SUBSTRING returns NULL.

 Syntax

{ SUBSTRING | SUBSTR } ( <long-varchar-column>, <start> [, <length> ] )

Parameters

long-varchar-column

The name of a LONG VARCHAR column or variable.


start

An integer expression indicating the start of the substring. A positive integer starts from the beginning of
the string, with the first character at position 1. A negative integer specifies a substring starting from the
end of the string, with the final character at position -1.
length

SAP IQ SQL Reference


538 INTERNAL SQL Functions
An integer expression indicating the character length of the substring. A positive length specifies the
number of characters to return, starting at the <start> position. A negative length specifies the number
of characters to return, ending at the <start> position.

Remarks

SUBSTRING supports LONG VARCHAR variables of any size of data. Currently, a SQL variable can hold up to 2
GB - 1 in length. SUBSTRING does not support LONG BINARY variables or searching LONG BINARY columns.

When the ansi_substring database option is set to ON (default), negative values are invalid.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.186 SUBSTRING64 Function [String]

The SUBSTRING64 function returns a variable-length character string of the large object column or variable
parameter.

SUBSTRING64 supports searching LONG VARCHAR and LONG BINARY columns and LONG VARCHAR and LONG
BINARY variables of any size of data. Currently, a SQL variable can hold up to 2 GB – 1 in length.

If you are licensed to use the Unstructured Data Analytics functionality, you can use this function with large
object data.

In this section:

SUBSTRING64 Function [Unstructured Data Analytics] [page 539]


The SUBSTRING64 function returns a variable-length character string of the large object column or
variable parameter.

6.11.186.1 SUBSTRING64 Function [Unstructured Data


Analytics]

The SUBSTRING64 function returns a variable-length character string of the large object column or variable
parameter.

 Syntax

SUBSTRING64 ( <large-object-column>, <start> [, <length> ] )

SAP IQ SQL Reference


SQL Functions INTERNAL 539
Parameters

large-object-column

The name of a LONG VARCHAR or LONG BINARY column or variable.


start

An 8-byte integer indicating the start of the substring. SUBSTRING64 interprets a negative or zero
<start> offset as if the string were padded on the left with "non-characters." The first character starts at
position 1.
length

An 8-byte integer indicating the length of the substring. If <length> is negative, an error is returned.

Example

Values returned by SUBSTRING64, given a column named col1 that contains the string ("ABCDEFG"):

● SUBSTRING64( col1, 2, 4 ) returns the string "BCDE"


● SUBSTRING64( col1, 1, 3 ) returns the string "ABC"
● SUBSTRING64( col1, 0, 3 ) returns the string "AB"
● SUBSTRING64( col1, -1, 3 ) returns the string "A"

Remarks

● If any of the arguments are NULL, SUBSTRING64 returns NULL.


● Nested operations of the functions SUBSTRING64, SUBSTRING, SUBSTR, BYTE_SUBSTR, and
BYTE_SUBSTR64 do not support large object columns or variables.
● SUBSTRING64 supports searching LONG VARCHAR and LONG BINARY columns and LONG VARCHAR and
LONG BINARY variables of any size of data. Currently, a SQL variable can hold up to 2GB - 1 in length.

See Function Support of Large Object Data in SAP IQ Administration: Unstructured Data Analytics.

6.11.187 SUM Function [Aggregate]

Returns the total of the specified expression for each group of rows.

 Syntax

SUM ( <expression> | DISTINCT <column-name> )

SAP IQ SQL Reference


540 INTERNAL SQL Functions
Parameters

expression

The object to be summed. This is commonly a column name.


DISTINCT column-name

Computes the sum of the unique values in <column-name> for each group of rows. This is of limited
usefulness, but is included for completeness.

Returns

● INTEGER
● DOUBLE
● NUMERIC
● BIGINT (SIGNED or UNSIGNED)

Remarks

Rows where the specified expression is NULL are not included.

Returns NULL for a group containing no rows.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value 3749146.740:

SELECT SUM( salary )


FROM Employees

Related Information

Windowing Aggregate Function Usage [page 197]

SAP IQ SQL Reference


SQL Functions INTERNAL 541
AVG Function [Aggregate] [page 277]
COUNT Function [Aggregate] [page 314]

6.11.188 SUSER_ID Function [System]

Returns an integer user identification number.

 Syntax

SUSER_ID ( [ <user-name> ] )

Parameters

user-name

The user name.

Returns

INT

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Examples

● The following statement returns the user identification number 1:

SELECT SUSER_ID ('DBA') FROM iq_dummy

● The following statement returns the user identification number 0:

SELECT SUSER_ID ('SYS') FROM iq_dummy

SAP IQ SQL Reference


542 INTERNAL SQL Functions
Related Information

SUSER_NAME Function [System] [page 543]


USER_ID Function [System] [page 551]
USER_NAME Function [System] [page 552]

6.11.189 SUSER_NAME Function [System]

Returns the user name.

 Syntax

SUSER_NAME ( [ <user-id> ] )

Parameters

user-id

The user identification number.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use SUSER_NAME in a SELECT INTO statement, you must
have an Unstructured Data Analytics Option license or use CAST and set SUSER_NAME to the correct data
type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ. In SAP ASE,
SUSER_NAME returns the server user name.

SAP IQ SQL Reference


SQL Functions INTERNAL 543
Examples

● The following statement returns the value DBA:

SELECT SUSER_NAME ( 1 ) FROM iq_dummy

● The following statement returns the value SYS:

SELECT SUSER_NAME ( 0 ) FROM iq_dummy

Related Information

SUSER_ID Function [System] [page 542]


USER_ID Function [System] [page 551]
USER_NAME Function [System] [page 552]

6.11.190 TAN Function [Numeric]

Returns the tangent of a number.

 Syntax

TAN ( <numeric-expression> )

Parameters

numeric-expression

An angle, in radians.

Returns

DOUBLE

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

SAP IQ SQL Reference


544 INTERNAL SQL Functions
● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

Returns the value 0.572561:

SELECT TAN( 0.52 ) FROM iq_dummy

Related Information

ACOS Function [Numeric] [page 267]


ASIN Function [Numeric] [page 273]
ATAN Function [Numeric] [page 274]
ATAN2 Function [Numeric] [page 275]
COS Function [Numeric] [page 308]
COT Function [Numeric] [page 310]
SIN Function [Numeric] [page 508]

6.11.191 TODAY Function [Date and time]

Returns the current date. This is the historical syntax for CURRENT DATE.

 Syntax

TODAY ( * )

Returns

DATE

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Functions INTERNAL 545
Example

The following statement returns the current day according to the system clock:

SELECT TODAY( * ) FROM iq_dummy

6.11.192 TRIM Function [String]

Returns a string, trimmed of all the leading and trailing characters present in the trim character set.

 Syntax

TRIM ( <string-expression>, [ <trim_character_set> ] )

Parameters

string-expression

The string to be trimmed.


trim_character_set The set of characters to use for trim.

Returns

Trimmed string.

Standards

● STANDARD function.

Example

The following statement removes all leading and trailing a and b characters from the given string and returns
the value Aabend.

SELECT TRIM ('babababENDbababa','ab') "trim" FROM iq_dummy

SAP IQ SQL Reference


546 INTERNAL SQL Functions
Related Information

LTRIM Function [String] [page 419]


RTRIM Function [String] [page 502]

6.11.193 TRUNCNUM Function [Numeric]

Truncates a number at a specified number of places after the decimal point.

 Syntax

TRUNCNUM ( <numeric-expression>, <integer-expression> )

Parameters

numeric-expression

The number to be truncated.


integer-expression

A positive integer specifies the number of significant digits to the right of the decimal point at which to
round. A negative expression specifies the number of significant digits to the left of the decimal point at
which to round.

Returns

NUMERIC

Remarks

This function is the same as TRUNCATE, but does not cause keyword conflicts.

You can use combinations of ROUND, FLOOR, and CEILING to provide similar functionality.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

SAP IQ SQL Reference


SQL Functions INTERNAL 547
● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 600:

SELECT TRUNCNUM( 655, -2 ) FROM iq_dummy

● The following statement returns the value 655.340:

SELECT TRUNCNUM( 655.348, 2 ) FROM iq_dummy

Related Information

ROUND Function [Numeric] [page 496]

6.11.194 UCASE Function [String]

Converts all characters in a string to uppercase.

 Syntax

UCASE ( <string-expression> )

Parameters

string-expression

The string to be converted to uppercase.

Returns

● LONG NVARCHAR
● LONG VARCHAR
● NVARCHAR
● VARCHAR

SAP IQ SQL Reference


548 INTERNAL SQL Functions
 Note

The result data type is a LONG VARCHAR. If you use UCASE in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license, or use CAST and set UCASE to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – UCASE is not supported by SAP Adaptive Server Enterprise, but UPPER provides
the same feature in a compatible manner.

Example

The following statement returns the value “CHOCOLATE”:

SELECT UCASE( 'ChocoLate' ) FROM iq_dummy

Related Information

LCASE Function [String] [page 401]


LEFT Function [String] [page 404]
LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UPPER Function [String] [page 549]

6.11.195 UPPER Function [String]

Converts all characters in a string to uppercase.

 Syntax

UPPER ( <string-expression> )

SAP IQ SQL Reference


SQL Functions INTERNAL 549
Parameters

string-expression

The string to be converted to uppercase.

Returns

● LONG NVARCHAR
● LONG VARCHAR
● NVARCHAR
● VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use UPPER in a SELECT INTO statement, you must have an
Unstructured Data Analytics Option license, or use CAST and set UPPER to the correct data type and size.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – compatible with SAP Adaptive Server Enterprise

Example

The following statement returns the value “CHOCOLATE”:

SELECT UPPER( 'ChocoLate' ) FROM iq_dummy

Related Information

LCASE Function [String] [page 401]


LEFT Function [String] [page 404]
LOWER Function [String] [page 417]
REPLACE Function [String] [page 489]
REVERSE Function [String] [page 493]
RIGHT Function [String] [page 495]
UCASE Function [String] [page 548]

SAP IQ SQL Reference


550 INTERNAL SQL Functions
6.11.196 USER_ID Function [System]

Returns an integer user identification number.

 Syntax

USER_ID ( [ <user-name> ] )

Parameters

user-name

The user name.

Returns

INT

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ

Examples

● The following statement returns the user identification number 1:

SELECT USER_ID ('DBA') FROM iq_dummy

● The following statement returns the user identification number 0:

SELECT USER_ID ('SYS') FROM iq_dummy

Related Information

SUSER_ID Function [System] [page 542]


SUSER_NAME Function [System] [page 543]

SAP IQ SQL Reference


SQL Functions INTERNAL 551
USER_NAME Function [System] [page 552]

6.11.197 USER_NAME Function [System]

Returns the user name.

 Syntax

USER_NAME ( [ <user-id> ] )

Parameters

user-id

The user identification number.

Returns

LONG VARCHAR

 Note

The result data type is a LONG VARCHAR. If you use USER_NAME in a SELECT INTO statement, you must
have an Unstructured Data Analytics Option license, or use CAST and set USER_NAME to the correct data
type and size.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise function implemented for SAP IQ. In SAP ASE,
USER_NAME returns the user name, not the server user name.

Examples

● The following statement returns the value “DBA”:

SELECT USER_NAME ( 1 ) FROM iq_dummy

SAP IQ SQL Reference


552 INTERNAL SQL Functions
● The following statement returns the value “SYS”:

SELECT USER_NAME ( 0 ) FROM iq_dummy

Related Information

SUSER_ID Function [System] [page 542]


SUSER_NAME Function [System] [page 543]
USER_ID Function [System] [page 551]

6.11.198 UUIDTOSTR Function [String]

Converts a unique identifier value (UUID, also known as GUID) to a string value.

 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 unique identifier, NULL is returned.

SAP IQ SQL Reference


SQL Functions INTERNAL 553
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

To convert a unique identifier value into a readable format, execute a query similar to:

CREATE TABLE T3 (
pk uniqueidentifier primary key,c1 int);
INSERT INTO T3 (pk, c1)
values (0x12345678123456789012123456789012, 1)
SELECT UUIDTOSTR(pk) FROM T3

Related Information

Binary Data Types [page 123]


NEWID Function [Miscellaneous] [page 432]
STRTOUUID Function [String] [page 533]
Character Data Types [page 115]
Binary Data Type Compatibility [page 159]

6.11.199 VAR_POP Function [Aggregate]

Computes the statistical variance of a population consisting of a numeric-expression, as a DOUBLE.

 Syntax

VAR_POP ( [ ALL ] <expression> )

Parameters

expression

The expression (commonly a column name) that has a population-based variance that is calculated over a
set of rows.

SAP IQ SQL Reference


554 INTERNAL SQL Functions
Returns

DOUBLE

Remarks

Computes the population variance of the provided <value expression> evaluated for each row of the group
or partition (if DISTINCT was specified, then each row that remains after duplicates have been eliminated),
defined as the sum of squares of the difference of <value expression>, from the mean of <value
expression>, divided by the number of rows (remaining) in the group or partition.

Population-based variances are computed according to the following formula:

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement lists the average and variance in the number of items per order in different time
periods:

SELECT year( ShipDate ) AS Year, quarter( ShipDate )


AS Quarter, AVG( Quantity ) AS Average,
VAR_POP( Quantity ) AS Variance
FROM SalesOrderItems GROUP BY Year, Quarter
ORDER BY Year, Quarter

Year Quarter Average Variance

2000 1 25.775148 203.9021

2000 2 27.050847 225.8109

... ... ... ...

SAP IQ SQL Reference


SQL Functions INTERNAL 555
Related Information

Windowing Aggregate Function Usage [page 197]

6.11.200 VAR_SAMP Function [Aggregate]


Computes the statistical variance of a sample consisting of a numeric-expression, as a DOUBLE.

 Syntax

VAR_SAMP ( [ ALL ] <expression> )

Parameters

expression

The expression (commonly a column name) that has a sample-based variance that is calculated over a set
of rows.

Returns

DOUBLE

Remarks

 Note

VAR_SAMP is an alias of VARIANCE.

Computes the sample variance of <value expression> evaluated for each row of the group or partition (if
DISTINCT was specified, then each row that remains after duplicates have been eliminated), defined as the
sum of squares of the difference of <value expression>, from the mean of <value expression>, divided
by one less than the number of rows (remaining) in the group or partition.

NULL returns NULL for a one-element input set in SAP IQ.

Variances are computed according to the following formula, which assumes a normal distribution:

SAP IQ SQL Reference


556 INTERNAL SQL Functions
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

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_SAMP( Quantity ) AS Variance
FROM SalesOrderItems GROUP BY Year, Quarter
ORDER BY Year, Quarter

Year Quarter Average Variance

2000 1 25.775148 205.1158

2000 2 27.050847 227.0939

... ... ... ...

Related Information

Windowing Aggregate Function Usage [page 197]

6.11.201 VAREXISTS function [Miscellaneous]

Returns 1 if a user-defined variable exists with the specified name. Returns 0 if no such variable exists.

 Syntax

VAREXISTS( <variable-name-string> [, <owner> ] )

SAP IQ SQL Reference


SQL Functions INTERNAL 557
Parameters

variable-name-string

The name of the variable to be tested, as a string (for example, 'myVariable').


owner The user ID of the owner of the variable, as a string. <owner> is only for use with owned database-
scope variables.

Returns

INT

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following IF statement checks to see if a variable called start_time exists. If it doesn't, then the
database server creates a connection-scope variable with that name, and sets its value to the current time.

IF VAREXISTS( 'start_time' ) = 0 THEN


CREATE VARIABLE start_time TIMESTAMP;
END IF;
SET start_time = CURRENT TIMESTAMP;

The following IF statement checks to see if a database-scope variable named run_time owned by user ID
jsmith exists. If it doesn't, then the database server creates the variable, and sets its value to the current
time.

IF VAREXISTS( 'run_time', 'jsmith' ) = 0 THEN


CREATE DATABASE VARIABLE jsmith.run_time TIMESTAMP = CURRENT TIMESTAMP;
END IF;

6.11.202 VARIANCE Function [Aggregate]

Returns the variance of a set of numbers.

 Syntax

VARIANCE ( [ ALL ] <expression> )

SAP IQ SQL Reference


558 INTERNAL SQL Functions
Parameters

expression

Any numeric data type (FLOAT, REAL, or DOUBLE) expression.

The expression (commonly a column name) whose sample-based variance is calculated over a set of rows.

Returns

DOUBLE

Remarks

The formula used to calculate VARIANCE is

VARIANCE returns a result of data type double-precision floating-point. If applied to the empty set,
the result is NULL, which returns NULL for a one-element input set.

VARIANCE does not support the keyword DISTINCT. A syntax error is returned if DISTINCT is used with
VARIANCE.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● Given this data:

SELECT Salary FROM Employees WHERE DepartmentID = 300

SAP IQ SQL Reference


SQL Functions INTERNAL 559
salary

51432.000

57090.000

42300.000

43700.00

36500.000

138948.000

31200.000

58930.00

75400.00

The following statement returns the value 1063923790.99999994:

SELECT VARIANCE ( Salary ) FROM Employees


WHERE DepartmentID = 300

● Given this data:

SELECT UnitPrice FROM Products WHERE name = 'Tee Shirt'

UnitPrice

9.00

14.00

14.00

The following statement returns the value 8.33333333333334327:

SELECT VARIANCE ( UnitPrice ) FROM Products


WHERE name = 'Tee Shirt'

Related Information

Windowing Aggregate Function Usage [page 197]


STDDEV Function [Aggregate] [page 524]
STDDEV_SAMP Function [Aggregate] [page 527]

SAP IQ SQL Reference


560 INTERNAL SQL Functions
6.11.203 WEEKS Function [Date and Time]

Returns the number of weeks since an arbitrary starting date/time, returns the number of weeks between two
specified date/times, or adds the specified integer-expression number of weeks to a date/time.

 Syntax

Syntax 1: Return the number of years between year 0000 and a TIMESTAMP value

WEEKS( <timestamp-expression> )

Syntax 2: Return the number of years between two TIMESTAMP values

WEEKS( <timestamp-expression>, <timestamp-expression> )

Syntax 3: Add years to a TIMESTAMP value

WEEKS( <timestamp-expression>, <integer-expression> )

Parameters

timestamp-expression

A date and time value of type TIMESTAMP.


integer-expression

The number of weeks (as a SMALLINT value) to be added to the <timestamp-expression>. If


<integer-expression> is negative, the appropriate number of weeks are subtracted from the date/
time<timestamp-expression>. Hours, minutes, and seconds are ignored. If you supply an integer
expression, the <timestamp-expression> must be explicitly cast as a DATETIME data type.

Returns

INTEGER (SMALLINT) when comparing two TIMESTAMP values.

TIMESTAMP when adding weeks to a TIMESTAMP value.

Remarks

Weeks are defined as going from Sunday to Saturday, as they do in a North American calendar. The number
returned by the first syntax is often useful for determining if two dates are in the same week:

WEEKS ( invoice_sent ) = WEEKS ( payment_received ) FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 561
For syntax 2, the value of WEEKS is calculated from the number of Sundays between the two dates. Hours,
minutes, and seconds are ignored. This function is not affected by the DATE_FIRST_DAY_OF_WEEK option.

Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 104278:

SELECT WEEKS( '1998-07-13 06:07:12' ) FROM iq_dummy

● The following statement returns the value 9, to signify the difference between the two dates:

SELECT WEEKS( '1999-07-13 06:07:12',


'1999-09-13 10:07:12' ) FROM iq_dummy

● The following statement returns the timestamp value 1999-06-16 21:05:07.000:

SELECT WEEKS( CAST( '1999-05-12 21:05:07'


AS TIMESTAMP ), 5) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
YEAR Function [Date and Time] [page 566]
YEARS Function [Date and Time] [page 568]

SAP IQ SQL Reference


562 INTERNAL SQL Functions
6.11.204 WEIGHTED_AVG Function [Aggregate]

Calculates an arithmetically (or linearly) weighted average.

 Syntax

WEIGHTED_AVG (<expression>) OVER (<window-spec>)

Parameters

expression

A numeric expression for which a weighted value is being computed.


window-spec

Specified when using this function as a window function.

Remarks

A weighted average is an average in which each quantity to be averaged is assigned a weight. Weightings
determine the relative importance of each quantity that make up the average.

Use the WEIGHTED_AVG function to create a weighted moving average. In a weighted moving average, weights
decrease arithmetically over time. Weights decrease from the highest weight for the most recent data points,
down to zero.

Figure 1: WEIGHTED_AVG Calculation

To exaggerate the weighting, you can average two or more weighted moving averages together, or use an
EXP_WEIGHTED_AVG function instead.

The <window-spec> parameter represents usage as a window function in a SELECT statement. As such, you
can specify elements of <window-spec> either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement.

● Must contain an ORDER BY specifier.


● Cannot contain FOLLOWING or RANGE specifiers.
● The second argument of the ROW specifier — if provided — must be CURRENT ROW.
● Cannot contain NULL values.
● Cannot contain the DISTINCT specifier.
● UNBOUNDED PRECEDING is supported, but may result in poor performance if used

SAP IQ SQL Reference


SQL Functions INTERNAL 563
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar

Example

The following example returns a weighted average of salaries by department for employees in Florida, with the
salary of recently hired employees contributing the most weight to the average:

SELECT DepartmentID, Surname, Salary,


WEIGHTED_AVG(Salary) OVER (PARTITION BY DepartmentID
ORDER BY YEAR(StartDate) DESC) as "W_AVG"
FROM Employees
WHERE State IN ('FL') ORDER BY DepartmentID

The returned result set is:

DepartmentID Surname Salary W_AVG

100 Lull 87,900.000 87,900.000000

100 Gowda 59,840.000 69,193.333333

200 Sterling 64,900.000 64,900.000000

200 Kelly 87,500.000 79,966.666667

300 Litton 58,930.000 58,930.000000

400 Evans 68,940.000 68,940.000000

400 Charlton 28,300.000 41,846.666667

400 Francis 53,870.000 47,858.333333

Related Information

Windowing Aggregate Function Usage [page 197]


EXP_WEIGHTED_AVG Function [Aggregate] [page 359]

SAP IQ SQL Reference


564 INTERNAL SQL Functions
6.11.205 WIDTH_BUCKET Function [Numerical]

For a given expression, the WIDTH_BUCKET function returns the bucket number that the result of this
expression will be assigned after it is evaluated.

 Syntax

WIDTH_BUCKET ( <expression>, <min_value>, <max_value>, <num_buckets> )

Parameters

expression

The expression for which the histogram is being created. This expression must evaluate to a numeric or
datetime value or to a value that can be implicitly converted to a numeric or datetime value. If <expr>
evaluates to null, then the expression returns null.
min_value

An expression that resolves to the end points of the acceptable range for <expr>. Must also evaluate to
numeric or datetime values and cannot evaluate to null.
max_value

An expression that resolves to the end points of the acceptable range for <expr>. Must also evaluate to
numeric or datetime values and cannot evaluate to null.
num_buckets

Is an expression that resolves to a constant indicating the number of buckets. This expression must
evaluate to a positive integer.

Remarks

You can generate equi-width histograms with the WIDTH_BUCKET function. Equi-width histograms divide data
sets into buckets whose interval size (highest value to lowest value) is equal. The number of rows held by each
bucket will vary. A related function, NTILE, creates equi-height buckets.

Equi-width histograms can be generated only for numeric, date or datetime data types; therefore, the first
three parameters should be all numeric expressions or all date expressions. Other types of expressions are not
allowed. If the first parameter is NULL, the result is NULL. If the second or the third parameter is NULL, an error
message is returned, as a NULL value cannot denote any end point (or any point) for a range in a date or
numeric value dimension. The last parameter (number of buckets) should be a numeric expression that
evaluates to a positive integer value; 0, NULL, or a negative value will result in an error.

Buckets are numbered from 0 to (n+1). Bucket 0 holds the count of values less than the minimum. Bucket(n+1)
holds the count of values greater than or equal to the maximum specified value.

SAP IQ SQL Reference


SQL Functions INTERNAL 565
Standards and Compatibility

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following example creates a 10-bucket histogram on the credit_limit column for customers in
Massachusetts in the sample table and returns the bucket number (“Credit Group”) for each customer.
Customers with credit limits greater than the maximum value are assigned to the overflow bucket, 11:

select EmployeeID, Surname, Salary, WIDTH_BUCKET(Salary, 29000, 60000, 4)


"Wages" from Employees where State = 'FL' order by "Wages"

EMPLOYEEID SURNAME SALARY Wages


---------- ------- ------ -----
888 Charlton 28300.000 0
1390 Litton 58930.000 4
207 Francis 53870.000 4
266 Gowda 59840.000 4
445 Lull 87900.000 5
1021 Sterling 64900.000 5
902 Kelly 87500.000 5
1576 Evans 68940.000 5

When the bounds are reversed, the buckets are open-closed intervals. For example: WIDTH_BUCKET
(<credit_limit>, <5000>, <0>, <5>). In this example, bucket number 1 is (4000, 5000), bucket number 2 is
(3000, 4000), and bucket number 5 is (0, 1000). The overflow bucket is numbered 0 (5000, +infinity), and the
underflow bucket is numbered 6 (-infinity, 0).

6.11.206 YEAR Function [Date and Time]

Returns a 4-digit number corresponding to the year of the given date/time.

 Syntax

YEAR ( <timestamp-expression> )

Parameters

timestamp-expression

A date and time.

SAP IQ SQL Reference


566 INTERNAL SQL Functions
Returns

SMALLINT

Remarks

The YEAR function is the same as the YEARS (<timestamp-expression>) function.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

The following statement returns the value 1998:

SELECT YEAR( '1998-07-13 06:07:12' ) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEARS Function [Date and Time] [page 568]
NTILE Function [Analytical] [page 440]

SAP IQ SQL Reference


SQL Functions INTERNAL 567
6.11.207 YEARS Function [Date and Time]
Returns a 4-digit number corresponding to the year of a given date/time, returns the number of years between
two specified date/times, or adds the specified integer-expression number of years to a date/time.

 Syntax

Syntax 1: Return the Number of Years Between Year 0000 and a TIMESTAMP Value

YEARS( <timestamp-expression> )

Syntax 2: Return the Number of Years Between Two TIMESTAMP Values

YEARS( <timestamp-expression>, <timestamp-expression> )

Syntax 3: Add Years to a TIMESTAMP Value

YEARS( <timestamp-expression>, <integer-expression> )

Parameters

timestamp-expression

A date and time value of type TIMESTAMP.


integer-expression

The number of years (as a SMALLINT value) to be added to <timestamp-expression>. If <integer-


expression> is negative, the appropriate number of years are subtracted from <timestamp-
expression>. If you supply an <integer-expression>, the <timestamp-expression> must be
explicitly cast as a DATE, TIME, or TIMESTAMP value. If <timestamp-expression> is a TIME, the current
year is assumed.

Returns

INTEGER (SMALLINT) when comparing two TIMESTAMP values.

TIMESTAMP when adding years to a TIMESTAMP value.

Remarks

The YEAR function is the same as YEARS (<timestamp-expression>).

For syntax 2, the value of YEARS is computed by counting the number of first days of the year between the two
dates. The number might be negative. Hours, minutes, and seconds are ignored.

Syntax 3 adds an <integer-expression> number of years to the given date. If the new date is past the end
of the month (such as SELECT YEARS ( CAST ( ‘1992-02-29’ AS TIMESTAMP ), 1 )), the result is set to the last

SAP IQ SQL Reference


568 INTERNAL SQL Functions
day of the month. If <integer-expression> is negative, the appropriate number of years is subtracted from
the date. Hours, minutes, and seconds are ignored.

Standards and compatibility

● SQL—Vendor extension to ISO/ANSI SQL grammar.


● SAP Database Products—Not supported by SAP Adaptive Server Enterprise.

Examples

● The following statement returns the value 1998:

SELECT YEARS( '1998-07-13 06:07:12' ) FROM iq_dummy

● The following statement returns the value 2, to signify the difference between the two dates.

SELECT YEARS( '1997-07-13 06:07:12',


'1999-09-13 10:07:12' ) FROM iq_dummy

● The following statement returns the value 2004-05-12 21:05:07.000.

SELECT YEARS( CAST( '1999-05-12 21:05:07'


AS TIMESTAMP ), 5) FROM iq_dummy

Related Information

CAST Function [Data Type Conversion] [page 288]


CONVERT Function [Data Type Conversion] [page 303]
HOURS Function [Date and Time] [page 373]
MINUTES Function [Date and Time] [page 425]
MONTHS Function [Date and Time] [page 430]
REPLACE Function [String] [page 489]
SECOND Function [Date and Time] [page 503]
WEEKS Function [Date and Time] [page 561]
YEAR Function [Date and Time] [page 566]

SAP IQ SQL Reference


SQL Functions INTERNAL 569
6.11.208 YMD Function [Date and Time]

Returns a date value corresponding to the given year, month, and day of the month.

 Syntax

YMD ( <integer-expression1>, <integer-expression2>, <integer-expression3> )

Parameters

integer-expression1

The year.
integer-expression2

The number of the month. If the month is outside the range 1–12, the year is adjusted accordingly.
integer-expression3

The day number. The day is allowed to be any integer, the date is adjusted accordingly.

Returns

DATE

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following statement returns the value 1998-06-12:

SELECT YMD( 1998, 06, 12 ) FROM iq_dummy

● If the values are outside their normal range, the date adjusts accordingly. For example, the following
statement returns the value 1993-03-01:

SELECT YMD( 1992, 15, 1 ) FROM iq_dummy

SAP IQ SQL Reference


570 INTERNAL SQL Functions
● The following statement returns the value 1993-02-28:

SELECT YMD ( 1992, 15, 1-1 ) FROM iq_dummy

● The following statement returns the value 1992-02-29:

SELECT YMD ( 1992, 3, 1-1 ) FROM iq_dummy

SAP IQ SQL Reference


SQL Functions INTERNAL 571
7 System Procedures

Use the system-supplied stored procedures in SAP IQ databases to retrieve system information.

SAP IQ includes the following kinds of system procedures:

● System functions that are implemented as stored procedures.


● Catalog stored procedures, for displaying system information in tabular form.
● Multiplex stored procedures, which include both of the above types of procedures, for multiplex server
operations. See System Procedures in SAP IQ Administration: Multiplex.
● Transact-SQL system and catalog procedures.
● System stored procedures related specifically to Large Object data, including sp_iqsetcompression and
sp_iqshowcompression. See Stored Procedure Support in SAP IQ Administration: Unstructured Data
Analytics

In this section:

Managing Privileged System Procedure Execution [page 573]


There are two security models under which privileged system procedures can run. Each model grants
the ability to run the system procedure differently.

Syntax Rules for Stored Procedures [page 579]


Use of parentheses and quotes in stored procedure calls varies, depending on whether you enter the
procedure name directly, as you can in Interactive SQL, or invoke it with a CALL statement.

Understanding Statistics Reported by Stored Procedures [page 579]


Many stored procedures report information on the state of SAP IQ at the time the procedure executes.

Procedures Supported bySAP SQL Anywhere [page 580]


SAP IQ supports SAP SQL Anywhere system procedures.

Alphabetical List of System Stored Procedures [page 580]


System stored procedures carry out System Administrator tasks in the IQ main store.

Alphabetical List of Catalog Stored Procedures [page 818]


Catalog store stored procedures return result sets displaying database server, database, and
connection properties in tabular form.

SAP ASE System and Catalog Procedures [page 977]


SAP Adaptive Server Enterprise provides system and catalog procedures to carry out many
administrative functions and to obtain system information. SAP IQ supports some of these procedures.

SAP IQ SQL Reference


572 INTERNAL System Procedures
7.1 Managing Privileged System Procedure Execution

There are two security models under which privileged system procedures can run. Each model grants the
ability to run the system procedure differently.

 Note

The following information applies to SAP IQ privileged system procedures only, not user-defined stored
procedures.

The first model, called the SYSTEM PROCEDURE DEFINER model, runs a privileged system procedure with the
privileges of its owner, typically dbo. The second model, called the SYSTEM PROCEDURE INVOKER model, runs
a privileged system procedure with the privileges of the person executing it.

To run a privileged system procedure using the SYSTEM PROCEDURE DEFINER model, grant explicit EXECUTE
object-level privilege on the procedure. Any system privileges required to run any underlying authorized tasks
of the system procedure are automatically inherited from the owner (definer of the system procedure).

For privileged system procedures using the SYSTEM PROCEDURE INVOKER model, the EXECUTE object-level
privilege is granted to the PUBLIC role, and since, by default, every user is a member of the PUBLIC role, every
user automatically inherits the EXECUTE object-level privilege. However, since the PUBLIC role is not the owner
of the system procedures, and is not granted any system privileges, the system privileges required to run any
underlying authorized tasks must be granted directly or indirectly to the user.

By default, a database created in versions 16.x and later runs all privileged system procedures using the
SYSTEM PROCEDURE INVOKER model. A database created in versions earlier than 16.x and upgraded to
versions 16.x and later runs privileged system procedures using a combination of both the SYSTEM
PROCEDURE DEFINER and SYSTEM PROCEDURE INVOKER models. In the combined model, all pre- 16.x
privileged system procedures use the SYSTEM PROCEDURE DEFINER model, and any privileged system
procedures introduced with 16.x (or any future release) use the SYSTEM PROCEDURE INVOKER model. You
can override the default security model when creating or upgrading a database, or any time thereafter.
However, SAP recommends that you not do so, as it may result in loss of functionality on custom stored
procedures and applications.

When running privileged system procedures using the SYSTEM PROCEDURE DEFINER model, the DBO system
role is typically the owner of the procedures. By default, the dbo system role is granted the
SYS_AUTH_DBA_ROLE compatibility role. This ensures that the role is indirectly granted all privileges
necessary to execute system procedures. Migrating the SYS_AUTH_DBA_ROLE compatibility role can result in
the dbo system role losing the ability to execute privileged system procedures. See Implications of Migrating
Compatibility Roles [page 574] for details.

In this section:

Implications of Migrating Compatibility Roles [page 574]


Some system roles are indirectly granted the system privileges necessary to execute privileged tasks
through membership in compatibility roles.

Granting the Ability to Run a Privileged System Procedure [page 575]


The process by which you grant the ability to run a privileged system procedure is dependent on the
security model under which it runs.

Revoking the Ability to Run a Privileged System Procedure [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 573
The process by which you revoke the ability to run a privileged system procedure is dependent on the
security model under which it runs.

Determining the Security Model Used by a Database [page 576]


There are two security models a database can use.

Pre-16.x Privileged System Procedures [page 577]


A list of pre-16.x privileged system procedures.

7.1.1 Implications of Migrating Compatibility Roles


Some system roles are indirectly granted the system privileges necessary to execute privileged tasks through
membership in compatibility roles.

You cannot revoke the underlying system privileges of a compatibility role; you must first migrate it to a user-
defined role. Only then can you revoke individual underlying system privileges from the new role and grant
them to other user-defined roles per the organization's security requirements. This enforces separation of
duties.

You can migrate compatibility roles automatically or manually. The method of migration can impact the ability
of a system role or the DBO system role to continue performing authorized tasks.
Regardless of the migration method used, once a compatibility role or the SYS_AUTH_DBA_ROLE role is
dropped, if you revoke a system privilege from the new user-defined role and grant it to another user-defined
role, you must do one of the following to ensure that system roles especially the dbo system role, retains all the
system privileges required to execute the applicable privileged tasks or multiplex management stored
procedures:

● Grant each system privilege revoked from the migrated user-defined role directly to the applicable system
roles or dbo role; or
● Grant membership in the user-defined role to which the system privileges are granted to the applicable
system roles or dbo system role.

The system roles that are members of compatibility roles, and might potentially be impacted by migration
include:

System Role Compatibility Role

dbo SYS_AUTH_DBA_ROLE

SYS_AUTH_RESOURCE_ROLE

SYS_RUN_REPLICATION_ROLE SYS_AUTH_DBA_ROLE

Automatic Migration

The ALTER ROLE statement creates a new user-defined role, automatically grants all underlying system
privileges of the compatibility role to the new user-defined role, makes each member of the compatibility role a
member of the new user-defined role, then drops the compatibility role.

Automatic migration assumes that the destination user-defined role does not already exist and that all system
privileges are migrated to the same new user-defined role.

SAP IQ SQL Reference


574 INTERNAL System Procedures
Manual Migration

Use the CREATE ROLE statement to create a new user-defined role. Use the GRANT statement to grant each
underlying system privilege to one or more users or roles. Use the DROP statement to drop the compatibility
role once all underlying system privileges are granted to at least one other user or role.

Members of the migrated compatibility role are not automatically granted membership in the new user-defined
role. As a result, members of some system roles may no longer be able to perform the expected privileged
tasks once the compatibility role is dropped. You must grant membership in the new user-defined role to the
affected system roles or directly grant the required system privileges to affected members.

7.1.2 Granting the Ability to Run a Privileged System


Procedure

The process by which you grant the ability to run a privileged system procedure is dependent on the security
model under which it runs.

For a privileged system procedure using the SYSTEM PROCEDURE DEFINER model, grant EXECUTE object-
level privilege on the system procedure to the user:

GRANT EXECUTE ON <sys_procedure_name>


TO <grantee> [,...]

For a privileged system procedure using the SYSTEM PROCEDURE INVOKER model, grant the underlying
system privileges required by the system procedure to the user. Use sp_proc_priv() to identify the system
privileges required to run a system procedure.

GRANT <system_privilege_name>
TO <grantee> [,...]

 Example

This statement grants the EXECUTE privilege on procedure sp_test1 to user Joe. sp_test1 uses the
SYSTEM PROCEDURE DEFINER model:

GRANT EXECUTE ON sp_test1 TO Joe

This statement identifies the system privileges necessary to run procedure sp_test2:

sp_proc_priv sp_test2;

Results:

proc_name privilege

sp_test2 MANAGE ANY DBSPACE, ALTER ANY INDEX

This statement grants those privileges to user Joe:

GRANT MANAGE ANY DBSPACE, ALTER ANY INDEX TO Joe

SAP IQ SQL Reference


System Procedures INTERNAL 575
Related Information

GRANT EXECUTE Privilege Statement [page 1499]


GRANT System Privilege Statement [page 1511]

7.1.3 Revoking the Ability to Run a Privileged System


Procedure

The process by which you revoke the ability to run a privileged system procedure is dependent on the security
model under which it runs.

For a privileged system procedure using the SYSTEM PROCEDURE DEFINER model, revoke the EXECUTE
object-level privilege on the system procedure from the user:

REVOKE EXECUTE ON <sys_procedure_name>


FROM <grantee> [,...]

For a privileged system procedure using the SYSTEM PROCEDURE INVOKER model, revoke the underlying
system privileges required by the system procedure from the user:

REVOKE <system_privilege_name>
FROM <grantee> [,...]

Related Information

REVOKE EXECUTE Privilege Statement [page 1625]


REVOKE System Privilege Statement [page 1635]

7.1.4 Determining the Security Model Used by a Database

There are two security models a database can use.

To determine the security model a database is using, execute:

select IF ((HEXTOINT(substring(db_property('Capabilities'),
1,length(db_property('Capabilities'))-20)) & 8) = 8)
THEN 1
ELSE 0
END IF

Where:

● 1 – indicates the database is using the SYSTEM PROCEDURE INVOKER model.


● 0 – indicates that the database is using the combined model.

SAP IQ SQL Reference


576 INTERNAL System Procedures
In the combined model, only pre-16.0 privileged system procedures run using the SYSTEM PROCEDURE
DEFINER. Refer to the pre-16.0 privileged system procedures list to identify these system procedures.

You cannot configure a new or upgraded database version 16.0 or later to run all system procedures using the
SYSTEM PROCEDURE DEFINER model.

7.1.5 Pre-16.x Privileged System Procedures

A list of pre-16.x privileged system procedures.

Privileged System Procedures Using the Combined Security Model

For these privileged system procedures, if the database is configured to use SYSTEM PROCEDURE DEFINER,
you only need EXECUTE object-level privilege on the procedure to run it. If the database is configured to use
SYSTEM PROCEDURE INVOKER, you also need the individual system privileges required by each procedure.
Refer to SAP IQ SQL Reference for the system privileges required to run each system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 577
● sa_audit_string ● sp_iqdbspace ● sp_iqmpxinfo
● sa_checkpoint_execute ● sp_iqdbspaceinfo ● sp_iqmpxversioninfo
● sa_disable_auditing_type ● sp_iqdbspaceobjectinfo ● sp_iqobjectinfo
● sa_disk_free_space ● sp_iqdbstatistics ● sp_iqpkeys
● sa_enable_auditing_type ● sp_iqdroplogin ● sp_iqprocedure
● sa_external_library_unload ● sp_iqemptyfile ● sp_iqprocparm
● sa_flush_cache ● sp_iqestdbspaces ● sp_iqrebuildindex
● sa_list_external_library ● sp_iqestspace ● sp_iqrename
● sa_server_option ● sp_iqevent ● sp_iqrestoreaction
● sa_procedure_profile ● sp_iqfile ● sp_iqrowdensity
● sa_procedure_profile_summary ● sp_iqhelp ● sp_iqsetcompression
● sa_table_page_usage ● sp_iqindex ● sp_iqsharedtempdistrib
● sa_validate ● sp_iqindex_alt ● sp_iqshowcompression

● sp_iq_reset_identity ● sp_iqindexadvice ● sp_iqshowpsexe

● sp_iqaddlogin ● sp_iqindexfragmentation ● sp_iqspaceinfo

● sp_iqbackupdetails ● sp_iqindexinfo ● sp_iqspaceused

● sp_iqbackupsummary ● sp_iqindexmetadata ● sp_iqstatistics

● sp_iqcardinality_analysis ● sp_iqindexsize ● sp_iqstatus

● sp_iqcheckdb ● sp_iqindexuse ● sp_iqsysmon

● sp_iqcheckoptions ● sp_iqlmconfig ● sp_iqtable

● sp_iqclient_lookup ● sp_iqlocks ● sp_iqtablesize

● sp_iqcolumn ● sp_iqmodifyadmin ● sp_iqtableuse

● sp_iqcolumnuse ● sp_iqmodifylogin ● sp_iqtransaction

● sp_iqconnection ● sp_iqmpxcheckdqpconfig ● sp_iqunusedcolumn

● sp_iqconstraint ● sp_iqmpxdumptlvlog ● sp_iqunusedindex

● sp_iqcontext ● sp_iqmpxfilestatus ● sp_iqunusedtable

● sp_iqconstraint ● sp_iqmpxincconnpoolinfo ● sp_iqversionuse

● sp_iqcontext ● sp_iqmpxincheartbeatinfo ● sp_iqview

● sp_iqcursorinfo ● sp_iqcopyloginpolicy ● sp_iqwho

● sp_iqdatatype ● sp_iqmpxincconnpoolinfo ● sp_iqworkmon

● sp_iqdbsize ● sp_iqmpxincheartbeatinfo

Privileged System Procedures Using Invoker Privileges

These pre-16.x privileged system procedures run with the privileges of the user who is running the procedure,
not the owner of the procedure, regardless of the security model setting. Therefore, in addition to the EXECUTE
object-level privilege on the system procedure, which is, by default, granted through membership in PUBLIC
role, you must also be granted the additional system privileges required by the system procedure. See the SAP
IQ SQL Reference for the system privileges required to run each system procedure.

● sa_describe_shapefile
● sa_get_user_status
● sa_locks
● sa_performance_diagnostics
● sa_report_deadlocks
● sa_text_index_stats

SAP IQ SQL Reference


578 INTERNAL System Procedures
7.2 Syntax Rules for Stored Procedures
Use of parentheses and quotes in stored procedure calls varies, depending on whether you enter the procedure
name directly, as you can in Interactive SQL, or invoke it with a CALL statement.

Some variations are permitted because the product supports both SAP IQ SQL and Transact-SQL syntax. If you
need Transact-SQL compatibility, be sure to use Transact-SQL syntax.

Syntax Syntax Type Explanation

<procedure_name> SAP IQ Quotes are required if you enclose parameters in parenthe­


('<param>') ses.

<procedure_name> SAP IQ Parentheses are optional if you enclose parameters in


'<param>' quotes.

<procedure_name> <param> Transact-SQL If you omit quotes around parameters, you must also omit
parentheses.

 Note
Quotes are always required around parameters when
the owner is specified. For example, assuming the owner
is <dba>, sp_iqtablesize 'dba.emp1' requires
quotes around the parameters. sp_iqtablesize
emp1 does not.

<procedure_name> SAP IQ or Transact- Use this syntax if you run a procedure with no parameters di­
SQL rectly in Interactive SQL, and the procedure has no parame­
ters.

call <procedure_name> SAP IQ Use this syntax to call a procedure that passes a parameter
(<param>='<value>') value.

When you use Transact-SQL stored procedures, you must use the Transact-SQL syntax.

7.3 Understanding Statistics Reported by Stored


Procedures
Many stored procedures report information on the state of SAP IQ at the time the procedure executes.

This means that you get a snapshot view. For example, a report column that lists space in use by a connection
shows only the space in use at the instant the procedure executes, not the maximum space used by that
connection.

To monitor SAP IQ usage over an extended period, use the SAP IQ monitor, which collects and reports statistics
from the time you start the monitor until you stop it, at an interval you specify.

SAP IQ SQL Reference


System Procedures INTERNAL 579
7.4 Procedures Supported bySAP SQL Anywhere

SAP IQ supports SAP SQL Anywhere system procedures.

 Tip

SAP SQL Anywhere stored procedures do not contain "iq" in the procedure name.

The sa_get_table_definition procedure is only supported for SAP SQL Anywhere tables. If run against an
SAP IQ table, the procedure returns the error not implemented for IQ tables.

7.5 Alphabetical List of System Stored Procedures

System stored procedures carry out System Administrator tasks in the IQ main store.

System stored procedures are owned by the user ID dbo.

 Note

By default, the maximum length of column values displayed by Interactive SQL Classic is 30 characters.
This might be inadequate for displaying output of stored procedures such as sp_iqstatus. To avoid
truncated output, increase the length by selecting Command Options from the Interactive SQL
menu, then select and enter a higher value for Limit Display Columns, Limit Output Columns, or both.

In this section:

(Deprecated) sp_iqaddlogin Procedure [page 585]


Adds a new SAP IQ user account to the specified login policy.

sp_iqbackupdetails Procedure [page 588]


Shows all the dbfiles included in a particular backup.

sp_iqbackupsummary Procedure [page 590]


Summarizes backup operations performed.

sp_iqcalcbaserlvstore Procedure [page 592]


Determines the minimum memory requirements for row-level versioning of the given table.

(Deprecated) sp_iqcardinality_analysis Procedure [page 596]


Analyzes the cardinality of columns in a table.

sp_iqcheckdb Procedure [page 598]


Checks validity of the current database. Optionally corrects allocation problems for dbspaces or
databases. sp_iqcheckdb does not check a partitioned table if partitioned data exists on offline
dbspaces.

sp_iqcheckfpconsistency Procedure [page 606]


Checks consistency of default indexes created on table columns.

sp_iqcheckoptions Procedure [page 608]

SAP IQ SQL Reference


580 INTERNAL System Procedures
For the connected user, sp_iqcheckoptions displays a list of the current value and the default value
of database and server startup options that have been changed from the default.

sp_iqclient_lookup Procedure [page 610]


Allows a client application to determine the SAP IQ user account responsible for a particular data
stream, as observed in a network analyzer originating from a specific client IP address/port.

sp_iqcolumn Procedure [page 612]


Displays information about columns in a database.

sp_iqcolumnmetadata Procedure [page 615]


Returns details about column indexes in one or more tables.

sp_iqcolumnuse Procedure [page 616]


Reports detailed usage information for columns accessed by the workload.

sp_iqconnection Procedure [page 618]


Shows information about connections and versions, including which users are using temporary
dbspace, which users are keeping versions alive, what the connections are doing inside SAP IQ,
connection status, database version status, and so on.

sp_iqconstraint Procedure [page 622]


Lists referential integrity constraints defined using CREATE TABLE or ALTER TABLE for the specified
table or column.

sp_iqcontext Procedure [page 624]


Tracks and displays, by connection, information about statements that are currently executing.

sp_iqcopyloginpolicy Procedure [page 627]


Creates a new login policy by copying an existing one.

sp_iqcursorinfo Procedure [page 628]


Displays detailed information about cursors currently open on the server.

sp_iqdatatype Procedure [page 631]


Displays information about system data types and user-defined data types.

sp_iqdbsize Procedure [page 634]


Displays the size of the current database.

sp_iqdbspace Procedure [page 636]


Displays detailed information about each SAP IQ dbspace.

sp_iqdbspaceinfo Procedure [page 639]


Displays the size of each object and subobject used in the specified table. Not supported for RLV
dbspaces.

sp_iqdbspaceobjectinfo Procedure [page 643]


Lists objects and subobjects of type table (including columns, indexes, metadata, primary keys, unique
constraints, foreign keys, and partitions) for a given dbspace. Not supported for RLV dbspaces.

sp_iqdbstatistics Procedure [page 646]


Reports results of the most recent sp_iqcheckdb.

sp_iqdroplogin Procedure [page 648]


Drops an SAP IQ user account.

sp_iqemptyfile Procedure [page 650]


Empties a dbfile and moves the objects in the dbfile to another available read-write dbfile in the same
dbspace. Not available for files in an RLV dbspace.

SAP IQ SQL Reference


System Procedures INTERNAL 581
sp_iqestdbspaces Procedure [page 652]
Estimates the number and size of dbspaces needed for a given total index size.

sp_iqestspace Procedure [page 655]


Estimates the amount of space needed to create an index based on the number of rows in the table.

sp_iqevent Procedure [page 656]


Displays information about system and user-defined events.

sp_iqfile Procedure [page 659]


Displays detailed information about each dbfile in a dbspace.

sp_iqhelp Procedure [page 663]


Displays information about system and user-defined objects and data types.

sp_iqindex and sp_iqindex_alt Procedures [page 669]


Lists information about indexes.

sp_iqindexadvice Procedure [page 673]


Displays stored index advice messages. Optionally clears advice storage.

sp_iqindexfragmentation Procedure [page 674]


Reports information about the percentage of page space taken up within the B-trees, garrays, and
bitmap structures in SAP IQ indexes.

sp_iqindexinfo Procedure [page 676]


Displays the number of blocks used per index per main dbspace for a given object. If the object resides
on several dbspaces, sp_iqindexinfo returns the space used in all dbspaces, as shown in the
example.

sp_iqindexmetadata Procedure [page 679]


Displays index metadata for a given index.

sp_iqindexrebuildwidedata Procedure [page 683]


Identifies wide columns in migrated databases that you must rebuild before they are available for read/
write activities.

sp_iqindexsize Procedure [page 685]


Gives the size of the specified index.

sp_iqindexuse Procedure [page 687]


Reports detailed usage information for secondary (non-FP) indexes accessed by the workload.

sp_iqlmconfig Procedure [page 689]


Controls license management configuration, properties, and authorizations.

sp_iqlocks Procedure [page 693]


Shows information about locks in the database, for both the IQ main store and the IQ catalog store.

sp_iqmergerlvstore Procedure [page 696]


Triggers a merge of a single row-level versioned (RLV) table store into the IQ main store.

sp_iqmergerlvtables Procedure [page 697]


Triggers a merge of a group of row-level version (RLV) table stores into the IQ main store.

sp_iqmodifyadmin Procedure [page 701]


Sets an option on a named login policy to a certain value. If no login policy is specified, the option is set
on the root policy. In a multiplex, sp_iqmodifyadmin takes an optional parameter that is the multiplex
server name.

SAP IQ SQL Reference


582 INTERNAL System Procedures
sp_iqmodifylogin Procedure [page 703]
Assigns a user to a login policy.

sp_iqmovetablefromfile Procedure [page 704]


Moves the table from all read-only dbfiles to read-write dbfiles of the same dbspace. It can move
multiple tables in the same dbspace in parallel via multiple concurrent connections to the server.

sp_iqmpxcheckdqpconfig Procedure [page 707]


sp_iqmpxcheckdqpconfig is a diagnostic tool that checks the DQP configuration for the current
connection. If DQP fails, run sp_iqmpxcheckdqpconfig to determine if DQP configuration issues are
causing the query distribution failure.

sp_iqmpxdumptlvlog Procedure [page 708]


Returns the contents of the table version log in a readable format.

sp_iqmpxfilestatus Procedure [page 710]


If run on the coordinator node, displays file status for coordinator and for every shared dbspace file on
every included secondary node. If executed on a secondary node, displays file status for only the
current node.

sp_iqmpxincconnpoolinfo Procedure [page 711]


If run on the coordinator node, displays INC connection pool status for every node. If executed on a
secondary node, displays INC connection pool status for only the current node.

sp_iqmpxincheartbeatinfo Procedure [page 713]


If run on the coordinator node, displays INC heartbeat status for every node. If executed on a
secondary node, displays INC heartbeat status for just the current node.

sp_iqmpxincstatistics Procedure [page 714]


Displays a snapshot of the aggregate statistics of internode communication (INC) status since server
startup as of the moment of execution.

sp_iqmpxinfo Procedure [page 716]


Returns a row for every node in the multiplex. Can be run from any multiplex node.

sp_iqmpxsuspendedconninfo Procedure [page 718]


Shows details about currently suspended connections and transactions on the coordinator node.

sp_iqmpxvalidate Procedure [page 720]


Checks multiplex configuration for inconsistencies.

sp_iqmpxversioninfo Procedure [page 721]


Shows the current version information for this server, including server type (write server, query server,
single-node mode) and synchronization status.

sp_iqobjectinfo Procedure [page 722]


Returns partitions and dbspace assignments of database objects and subobjects.

(Deprecated) sp_iqpassword Procedure [page 725]


Changes a user’s password.

sp_iqpkeys Procedure [page 727]


Displays information about primary keys and primary key constraints by table, column, table owner, or
for all SAP IQ tables in the database.

sp_iqprocedure Procedure [page 729]


Displays information about system and user-defined procedures.

sp_iqprocparm Procedure [page 732]

SAP IQ SQL Reference


System Procedures INTERNAL 583
Displays information about stored procedure parameters, including result set variables and
SQLSTATE/SQLCODE error values.

sp_iqpurgebackuphistory Procedure [page 735]


Deletes rows from the SysIQBackupHistory and SysIQBackupHistoryDetail system tables.

sp_iqrebuildindex Procedure [page 737]


Rebuilds column indexes.

sp_iqrebuildindexwide Procedure [page 741]


Rebuilds pre-16.1 FP indexes wider than 255 bytes.

sp_iqrename Procedure [page 744]


Renames user-created tables, columns, indexes, constraints (unique, primary key, foreign key, and
check), stored procedures, and functions.

sp_iq_reset_identity Procedure [page 746]


Sets the seed of the Identity/Autoincrement column associated with the specified table to the specified
value.

sp_iqrestoreaction Procedure [page 748]


Identifies actions required to bring the database to a state consistent with a given date.

sp_iqrlvmemory Procedure [page 750]


Monitors RLV store memory usage per table.

sp_iqrowdensity Procedure [page 752]


Reports information about the internal row fragmentation for a table at the FP index level.

sp_iqsetcompression Procedure [page 754]


Sets compression of data in columns of LONG BINARY (BLOB) and LONG VARCHAR (CLOB) data types.

sp_iqsharedtempdistrib Procedure [page 755]


Shows the current shared temp space usage distribution. If run from the coordinator,
sp_iqsharedtempdistrib displays shared temp space distribution for all nodes. If run from a
secondary node, displays shared temp space usage for only that node.

sp_iqshowcompression Procedure [page 757]


Displays compression settings for columns of LONG BINARY (BLOB) and LONG VARCHAR (CLOB) data
types.

sp_iqshowpsexe Procedure [page 758]


Displays information about the settings of database options that control the priority of tasks and
resource usage for connections.

sp_iqspaceinfo Procedure [page 760]


Displays the number of blocks used by each object in the current database and the name of the
dbspace in which the object is located.

sp_iqspaceused Procedure [page 762]


Shows information about space available and space used in the IQ store, IQ temporary store, RLV store,
and IQ global and local shared temporary stores.

sp_iqstatistics Procedure [page 765]


Returns serial number, name, description, value, and unit specifier for each available statistic, or a
specified statistic.

sp_iqstatus Procedure [page 768]


Displays a variety of SAP IQ status information about the current database.

SAP IQ SQL Reference


584 INTERNAL System Procedures
sp_iqsysmon Procedure [page 772]
Monitors multiple components of SAP IQ, including the management of buffer cache, memory, threads,
locks, I/O functions, and CPU utilization.

sp_iqtable Procedure [page 790]


Displays information about tables in the database.

sp_iqtablesize Procedure [page 795]


Returns the size of the specified table.

sp_iqtableuse Procedure [page 797]


Reports detailed usage information for tables accessed by the workload.

sp_iqtransaction Procedure [page 799]


Shows information about transactions and versions.

sp_iqunusedcolumn Procedure [page 802]


Reports IQ columns that were not referenced by the workload.

sp_iqunusedindex Procedure [page 803]


Reports IQ secondary (non-FP) indexes that were not referenced by the workload.

sp_iqunusedtable Procedure [page 805]


Reports IQ tables that were not referenced by the workload.

sp_iqversionuse Procedure [page 807]


Displays version usage for the IQ main store.

sp_iqview Procedure [page 809]


Displays information about views in a database.

sp_iqwho Procedure [page 812]


Displays information about all current users and connections, or about a particular user or connection.

sp_iqworkmon Procedure [page 815]


Controls collection of workload monitor usage information, and reports monitoring collection status.
sp_iqworkmon collects information for all SQL statements.

sp_iqzonemapenable Procedure [page 817]


Identifies columns with a ridmap version of zero (0).

7.5.1 (Deprecated) sp_iqaddlogin Procedure

Adds a new SAP IQ user account to the specified login policy.

 Note

Though sp_iqaddlogin is still supported for backwards compatibility, use CREATE USER to create new
users.

 Syntax

Syntax 1

call sp_iqaddlogin ('<username_in>', '<pwd>',


[ '<password_expiry_on_next_login>'] [ , '<policy_name>'] )

SAP IQ SQL Reference


System Procedures INTERNAL 585
Syntax 2

sp_iqaddlogin '<username_in>', '<pwd>',


[ '<password_expiry_on_next_login>'] [ , '<policy_name>']

Syntax 3

sp_iqaddlogin <username_in>, <pwd>,


[ <password_expiry_on_next_login>] [ , <policy_name> ]

Go to:

● Remarks
● Privileges
● Side Effects
● Examples

Parameters

(back to top)

username_in

The user’s login name. Login names must conform to the rules for identifiers.
pwd

The user's password. Passwords must conform to rules for passwords, that is, they must be valid
identifiers.
password_expiry_on_next_login

(Optional) Specifies whether user’s password expires as soon as this user’s login is created. Default setting
is OFF (password does not expire).
policy_name

(Optional) Creates the user under the named login policy. If unspecified, user is created under the root
login policy.

Remarks

(back to top)

Adds a new SAP IQ user account, assigns a login policy to the user and adds the user to the ISYSUSER system
table. If the user already has a user ID for the database but is not in ISYSUSER, (for example, if the user ID was
added using the GRANT CONNECT statement or SAP IQ Cockpit), sp_iqaddlogin adds the user to the table.

If you do not specify a login policy name when calling the procedure, SAP IQ assigns the user to the root login
policy.

SAP IQ SQL Reference


586 INTERNAL System Procedures
 Note

If the maximum number of logins for a login policy is unlimited, then a user belonging to that login policy
can have an unlimited number of connections.

The first user login forces a password change and assigns a login policy to the newly created user.

A <username_in> and <pwd> created using sp_iqaddlogin and set to expire in one day is valid all day
tomorrow and not valid on the following day. That is, a login created today and set to expire in <n> days is not
usable once the date changes to the <(n+1)>th day.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY USER System privilege GRANT System Privilege Statement [page 1511]

Side Effects

(back to top)

None

Example

(back to top)

These calls add the user rose with a password irk324 under the login policy named expired_password.
This example assumes the expired_password login policy already exists:

call sp_iqaddlogin('rose', 'irk324', 'ON', 'expired_password')

sp_iqaddlogin 'rose','irk324', 'ON', 'expired_password'

Related Information

sp_expireallpasswords System Procedure [page 920]

SAP IQ SQL Reference


System Procedures INTERNAL 587
sp_iqcopyloginpolicy Procedure [page 627]
sp_iqmodifylogin Procedure [page 703]
(Deprecated) sp_iqpassword Procedure [page 725]
CREATE USER Statement [page 1402]
sp_iqdroplogin Procedure [page 648]
Determining the Security Model Used by a Database [page 576]

7.5.2 sp_iqbackupdetails Procedure

Shows all the dbfiles included in a particular backup.

 Syntax

sp_iqbackupdetails <backup_id>

Parameters

backup_id

The backup operation transaction identifier.

Returns

Column Name Description

backup_id Identifier for the backup transaction.

backup_time Time of the backup.

backup_type Type of backup:

● "Full"
● "Incremental since incremental"
● "Incremental since full"

selective_type Subtype of backup:

● "All inclusive"
● "All RW files in RW dbspaces"
● "Set of RO dbspace/file"

depends_on_id Identifier for previous backup that the backup depends on.

dbspace_id Identifier for the dbspace being backed up.

SAP IQ SQL Reference


588 INTERNAL System Procedures
Column Name Description

dbspace_name Name of the dbspace from SYSIQBACKUPHISTORYDETAIL. If dbspace name


matches the dbspace name in SYSDBSPACE for a given dbspace_id. Otherwise "null."

dbspace_rwstatus "ReadWrite" or "Read Only."

dbspace_createid Dbspace creation transaction identifier.

dbspace_alterid Alter DBSPACE read-write mode transaction identifier.

dbspace_online Status "Online" or "Offline."

dbspace_size Size of dbspace, in KB, at time of backup.

dbspace_backup_size Size of data, in KB, backed up in the dbspace.

dbfile_id Identifier for the dbfile being backed up.

dbfile_name The logical file name, if it was not renamed after the backup operation. If renamed,
"null."

dbfile_rwstatus "ReadWrite" or "Read Only."

dbfile_createid Dbfile creation transaction identifier.

dbfile_alterid Alter DBSPACE alter FILE read-write mode transaction identifier

dbfile_size in MB Size of the dbfile, in MB.

dbfile_backup_size Size of the dbfile backup, in KB.

dbfile_path The dbfile path from SYSBACKUPDETAIL, if it matches the physical file path
("file_name") in SYSDBFILE for a given dbspace_id and the dbfile_id. Otherwise "null."

Remarks

To obtain the <backup_id> value from the SYSIQBACKUPHISTORY table, execute:

select * from sysiqbackuphistory

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 589
Example

Sample output from sp_iqbackupdetails:

backup_id backup_time backup_type selective_type depends_on_id


883 2008-09-23 13:58:49.0 Full All inclusive 0
dbspace_id dbspace_name dbspace_rwstatus dbspace_createid
0 system ReadWrite 0
dbspace_alterid dbspace_online dbspace_size dbspace_backup_size dbfile_id
0 0 2884 2884 0
dbfile_name dbfile_rwstatus dbfile_createid dbfile_alterid dbfile_size
system ReadWrite 0 0 2884

dbfile_backup_size dbfile_path
2884 C:\\Documents and Settings\\All Users\\IQ\\demo\\iqdemo.db

Related Information

SYSIQBACKUPHISTORY System View [page 1033]


Determining the Security Model Used by a Database [page 576]

7.5.3 sp_iqbackupsummary Procedure

Summarizes backup operations performed.

 Syntax

sp_iqbackupsummary [ <timestamp> | <backup_id> ]

Parameters

timestamp or backup_id

(Optional) The interval for which to report backup operations. If you specify <timestamp> or
<backup_id>, only those records with backup_time greater than or equal to the time you enter are
returned. If you specify no timestamp, the procedure returns all the backup records in
ISYSIQBACKUPHISTORY.

SAP IQ SQL Reference


590 INTERNAL System Procedures
Returns

Column Name Description

backup_id Identifier for the backup transaction

backup_time Time of the backup

backup_type Type of backup:

● "Full"
● "Incremental since incremental"
● "Incremental since Full"
● "PITR"

selective_type Subtype of backup:

● "All inclusive"
● "All RW files in RW dbspaces"
● "Set of RO dbspace/file"

virtual_type Type of virtual backup:

● "Non-virtual"
● "Decoupled"
● "Encapsulated"

depends_on_id Identifier for backup that the backup depends on

creator Creator of the backup

backup_size Size, in KB, of the backup

user_comment User comment

backup_command The backup statement issued (minus the comment)

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 591
Example

Sample output of sp_iqbackupsummary:

backup_id backup_time backup_type selective_type virtual_type


883 2008-09-23 13:58:49.0 Full All inclusive Non virtual
depends_on_id creator backup_size user_comment backup_command
0 DBA 10864 backup database to
'c:\\\\temp\\\\b1'

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.4 sp_iqcalcbaserlvstore Procedure

Determines the minimum memory requirements for row-level versioning of the given table.

 Syntax

sp_iqcalcbaserlvstore ( <table_name>, <max_subfragments>, <num_rows>,


<rv_initial_blocksize>, <rv_fixed_blocksize>, <rv_delta_increase>,
<rv_percent_increase>)

Go to:

● Returns
● Remarks
● Privileges
● Side Effects
● Examples

Parameters

(back to top)

table_name

Name of the table for which the user wants to determine in-memory storage. If not specified, default value
of '%' is used.
max_subfragments

Maximum number of subfragments to assume for in-memory storage. If not specified, default value of 1 is
used.
num_rows

SAP IQ SQL Reference


592 INTERNAL System Procedures
Number of rows expected in the RLV store. If not specified, default value of 1 is used.
rv_initial_blocksize

The size (in bytes) of the first array allocation for fixed length data type columns in the RLV in-memory
store. It is used as a starting size by all fixed block allocation strategies. If not specified, default value of
4096 bytes (KB) is used.
rv_fixed_blocksize

The size (in bytes) of every subsequent array allocation for fixed length data type columns in the RLV in-
memory store. It is used by the Constant allocation strategy. If not specified, default value of 16777216
bytes (16 MB) is used.
rv_delta_increase

The delta size increase size (in Bytes) for subsequent array allocation for fixed length data type columns in
the RLV in-memory store. The nth block size is the value of (n-1)th block size +
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE. This is used by the Delta Increase allocation strategy. If
not specified, default value of 1024 bytes (1 KB) is used.
rv_percent_increase

The percentage size increase for subsequent array allocation for fixed length data type columns in the RLV
in-memory store. The nth block size is the value of (n-1)th block size + ((n-1)th block size *
RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZE / 100). This is used by the Percent Increase
allocation strategy. If not specified, default value of 100 (%) is used.

Returns

(back to top)

Name Data Type Description

table_name VARCHAR(257) Name of the table.

table_id INT Table identifier.

is_rlv CHAR(1) A Boolean variable, valid values are:

● T – indicates that table is an RLV table.


● F – indicates that it is not.

max_subfragments INT Maximum number of sub-fragments assumed for the in-


memory storage.

num_rows BIGINT Number of rows expected in the RLV store; the default is 1.

fixed_Columns INT Number of fixed columns in the table schema; includes:

● Fixed-width datatypes
● NBIT columns
● Internal columns

var_columns INT Number of variable columns in the table schema, including


VARCHAR, flat FP, and VARBINARY flat FP.

twoblock_size_MB NUMERIC(10,2) Total space, in MB, required by an RLV-enabled table when


two block allocation strategy is used.

SAP IQ SQL Reference


System Procedures INTERNAL 593
Name Data Type Description

percent_size_MB NUMERIC(10,2) Total space, in MB, required by an RLV-enabled table when


percent increase block allocation strategy is used.

delta_size_MB NUMERIC(10,2) Total space, in MB, required by an RLV-enabled table when


delta increase block allocation strategy is used.

constant_size_MB NUMERIC(10,2) Total space, in MB, required by an RLV-enabled table when


constant block allocation strategy is used.

Remarks

(back to top)

Displays the estimated minimum memory requirements for given allocation strategies to convert a table to
row-level-versioning.

The parameter values can be adjusted to calculate different memory requirements for the RLV store. Each
parameter corresponds to a database option.

Parameter Database Option

<rv_initial_blocksize> RV_INITIAL_FIXED_DATA_BLOCKSIZE

<rv_fixed_blocksize> RV_FIXED_DATA_BLOCKSIZE

<rv_delta_increase> RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE

<rv_percent_increase> RV_PERCENT_INCREASE_IN_FIX_DTA_BLOCKSIZE

Parameter values are used by the stored procedure. They are not utilized by the actual RLV store. To change
the memory usage of the RLV store, modify the corresponding database option.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

(back to top)

None

SAP IQ SQL Reference


594 INTERNAL System Procedures
Examples

(back to top)

● The following example example returns the in-memory usage for the RLV-enabled table tab1 using 1
subfragment with 10 million rows:

CREATE TABLE tab1(col1 varchar(20) IQ UNIQUE (100000)) ENABLE RLV STORE;

call sp_iqcalcbaserlvstore('tab1', 1, 10000000);

Result set returned is as follows, where:


○ fixed_Columns = 2 because the table contains one NBIT column and one internal column.
○ var_Columns = 0 because the table contains no variable width columns.
○ Memory requirements for each of the allocation strategies (twoblock, percent, delta, constant) are
displayed.

max_subfrag­
table_name table_id is_rlv ments num_rows fixed_Columns

tab1 782 T 1 10000000 2

var_columns twoblock_size_MB percent_size_MB delta_size_MB constant_size_MB

0 212.01 212.00 194.99 212.01

● The following example returns the in-memory usage for the RLV-enabled table tab2 using 10
subfragments with 1 million rows.

create table tab2(col1 int, col2 varchar(500) iq unique(60000), col3


varchar(30) iq unique(0), col4 bit, col5 bigint iq unique(0));

call sp_iqcalcbaserlvstore('tab2', 10, 10000000);

Result set returned is as follows, where:


○ fixed_Columns = 5 The table contains two fixed width columns, two NBIT columns, and one internal
column.
○ var_Columns = 0 The table contains one variable width column.

table_name table_id is_rlv max_subfragments num_rows fixed_Columns

tab2 781 F 10 10000000 5

var_columns twoblock_size_MB percent_size_MB delta_size_MB constant_size_MB

1 819.69 229.38 216.94 819.53

SAP IQ SQL Reference


System Procedures INTERNAL 595
7.5.5 (Deprecated) sp_iqcardinality_analysis Procedure

Analyzes the cardinality of columns in a table.

 Note

sp_iqcardinality_analysis no longer returns an index type value or index recommendation. Users


are advised to Run Index Advisor for suggestions about additional column indexes.
sp_iqcardinality_analysis is deprecated and will be removed in a future release.

 Syntax

sp_iqcardinality_analysis ( [ '<table_name>' ], [ '<table_owner>' ],


[ '<script>' ] )

Parameters

table_name

Name of the table.


table_owner

Name of the table owner. If this parameter is not specified, then the procedure looks for a table owned by
the current user.
script

The script:

● table_name
● table_owner
● column_name
● cardinality
● index_type
● index recommendation

Remarks

If you do not specify any parameters, then SAP IQ displays create_index SQL statements for all columns in
all tables owned by the current user.

If you specify <script>, you can redirect the output to generate the script file:

OUTPUT TO 'indexfile.sql' FORMAT ASCII QUOTE '';

SAP IQ SQL Reference


596 INTERNAL System Procedures
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● CREATE ANY INDEX System privileges GRANT System Privilege Statement [page 1511]

● ALTER ANY INDEX


● CREATE ANY OBJECT
● ALTER ANY OBJECT

If you own the table, no additional system privilege is required.

For tables owned by others, you also need:

Privilege Name Privilege Type Grant Statement

SELECT ANY TABLE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

sp_iqcardinality_analysis 'Departments', 'GROUPO'

Index Recommen­
table_name table_owner column_name cardinality index type dation

Departments GROUPO DepartmentID 5 Run Index Advisor

Departments GROUPO DepartmentName 5 Run Index Advisor

Departments GROUPO DepartmentHeadID 5 Run Index Advisor

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 597
7.5.6 sp_iqcheckdb Procedure

Checks validity of the current database. Optionally corrects allocation problems for dbspaces or databases.
sp_iqcheckdb does not check a partitioned table if partitioned data exists on offline dbspaces.

 Syntax

sp_iqcheckdb '<mode> <target> [ … ] [ resources <resource-percent> ]'

<mode> ::=
{ allocation
| check
| verify }
| dropleaks

<target> ::=
[ indextype <index-type> […] ] database
| database resetclocks
| { [ indextype <index-type> ] […] table <table-name> [ partition
<partition-name> ] […]
| index <index-name>
| […] dbspace <dbspace-name>}
| cache <main-cache-name>

Go to:

● Remarks
● Privileges
● Side Effects
● Examples

Parameters

(back to top)

database

If the target is a database, all dbspaces must be online.


index-type

One of the following index types: FP, CMP, HG, HNG, WD, DATE, TIME, DTTM, TEXT.

If the specified <index-type> does not exist in the target, an error message is returned. If multiple index
types are specified and the target contains only some of these index types, the existing index types are
processed by sp_iqcheckdb.
index-name

May contain owner and table qualifiers: [[<owner>.]<table-name>.]<index-name>.

If <owner> is not specified, current user and database owner (dbo) are substituted in that order. If
<table> is not specified, <index-name> must be unique.
table-name

SAP IQ SQL Reference


598 INTERNAL System Procedures
May contain an owner qualifier: [<owner>.]<table-name>

If <owner> is not specified, current user and database owner (dbo) are substituted in that order. <table-
name> cannot be a temporary or pre-join table.

 Note

If either the table name or the index name contains spaces, enclose the <table-name> or <index-
name> parameter in double quotation marks:

sp_iqcheckdb 'check index "dbo.sstab.i2" resources 75'

partition-name

The <partition-name> parameter contains no qualifiers. If it contains spaces, enclose it in double


quotation marks.

The partition filter causes sp_iqcheckdb to examine a subset of the corresponding table’s rows that
belong to that partition. A partition filter on a table and table target without the partition filter are
semantically equivalent when the table has only one partition.
dbspace-name

The <dbspace-name> parameter contains no qualifiers. If it contains spaces, enclose it in double


quotation marks.

The dbspace target examines a subset of the database's pages that belong to that dbspace. The dbspace
must be online. The dbspace and database target are semantically equivalent when the table has only one
dbspace.
resource-percent

The input parameter <resource-percent> must be an integer greater than zero. The resources
percentage allows you to limit the CPU utilization of the database consistency checker by controlling the
number of threads with respect to the number of CPUs. If <resource-percent> = 100 (the default
value), then one thread is created per CPU. If <resource-percent> > 100, then there are more threads
than CPUs, which might increase performance for some machine configurations. The minimum number of
threads is one.
main-cache-name

The cache target compares pages in the main cache dbspace against the original pages in the IQ main
store.

 Note

The sp_iqcheckdb parameter string must be enclosed in single quotes and cannot be greater than 255
bytes in length.

Allocation problems can be repaired in dropleaks mode.

Remarks

(back to top)

SAP IQ SQL Reference


System Procedures INTERNAL 599
sp_iqcheckdb reads all storage in the database. On successful completion, the database free list (an internal
allocation map) is updated to reflect the true storage allocation for the database. sp_iqcheckdb then
generates a report listing the actions it has performed.

If an error is found, sp_iqcheckdb reports the name of the object and the type of error. sp_iqcheckdb does
not update the free list if errors are detected.

sp_iqcheckdb also allows you to check the consistency of a specified table, index, index type, or the entire
database.

 Note

sp_iqcheckdb is the user interface to the SAP IQ database consistency checker (DBCC) and is
sometimes referred to as DBCC.

There are three modes for checking database consistency, and one for resetting allocation maps. If mode and
target are not both specified in the parameter string, SAP IQ returns the error message:

At least one mode and target must be specified to DBCC.

sp_iqcheckdb checks the allocation of every block in the database and saves the information in the current
session until the next sp_iqdbstatistics procedure is issued. sp_iqdbstatistics displays the latest
result from the most recent execution of sp_iqcheckdb.

sp_iqcheckdb can perform several different functions, depending on the parameters specified.

 Note

See Database Verification for detailed information on checking database consistency with sp_iqcheckdb.

SAP IQ SQL Reference


600 INTERNAL System Procedures
Mode Description

Allocation Checks allocation with blockmap information for the entire database, a specific index, a specific
index type, a specific partition, specific table, or a specific dbspace. Does not check index consis­
tency.

Detects duplicate blocks (blocks for which two or more objects claim ownership) or extra blocks
(unallocated blocks owned by an object).

 Note
If sp_iqcheckdb detects a block ownership conflict, it adds a **Blocks with
Multiple Owners*** section to the report, listing the implicated object names, and
physical block numbers. Block ownership conflicts are only analyzed if the target of
sp_iqcheckdb is either a database or a dbspace. Example of a block ownership conflict:

** Blocks with Multiple Owners ******


** DBA.dupowned1.ASIQ_IDX_T1707_C1_FP 411552 ******
** DBA.dupowned2.ASIQ_IDX_T1708_C1_FP 411552 ******
** DBA.dupowned1.ASIQ_IDX_T1707_C1_FP 411553 ******
...

This section of the report can help you recover from corruption caused by block ownership
conflicts. In the event of a block ownership conflict, contact SAP Support for advice on how to
resolve the reported conflicts.

Detects leaked blocks (allocated blocks unclaimed by any object in the specified target) for data­
base or dbspace targets.

When the target is a partitioned table, allocation mode:

● Checks metadata of all the table’s partition allocation bitmaps


● Checks metadata of the tables allocation bitmap
● Verifies that blockmap entries are consistent with the table’s allocation bitmap
● Verifies that none of the table’s partition allocation bitmaps overlap
● Checks that rows defined in the table’s partition allocation bitmaps form a superset of the ta­
ble’s existence bitmap
● Checks that rows defined in the table’s partition allocation bitmaps form a superset of the ta­
ble’s allocation bitmap
● Verifies that the main cache pages are consistent with the IQ main store pages.

 Note
sp_iqcheckdb cannot check all allocation problems if you specify the name of a single in­
dex, index type, or table in the input parameter string.

Run in allocation mode:

● To detect duplicate or unowned blocks (use database or specific tables or indexes as the tar­
get)
● If you encounter page header errors

The DBCC option resetclocks is used only with allocation mode. resetclocks is used with
forced recovery to convert a multiplex secondary server to a coordinator. For information on multi­

SAP IQ SQL Reference


System Procedures INTERNAL 601
Mode Description

plex capability, see SAP IQ Administration: Multiplex. resetclocks corrects the values of inter­
nal database versioning clocks, in the event that these clocks are behind. Do not use the
resetclocks option for any other purpose, unless you contact SAP IQ Technical Support.

The resetclocks option must be run in single-user mode and is allowed only with the DBCC
statement allocation database. The syntax of resetclocks is:

sp_iqcheckdb 'allocation database resetclocks'

Check Verifies that all database pages can be read for the entire database, main cache, specific index,
specific index type, specific table, specific partition, or specific dbspace. If the table is partitioned,
then check mode will check the table’s partition allocation bitmaps.

Run in check mode if metadata, null count, or distinct count errors are returned when running a
query.

Verify Verifies the contents of non-FP indexes with their corresponding FP indexes for the entire data­
base, main cache, a specific index, a specific index type, specific table, specific partition, or spe­
cific dbspace. If the specified target contains all data pages for the FP and corresponding non-FP
indexes, then verify mode detects the following inconsistencies:

● Missing key – a key that exists in the FP but not in the non-FP index.
● Extra key – a key that exists in the non-FP index but not in the FP index.
● Missing row – a row that exists in the FP but not in the non-FP index.
● Extra row – a row that exists in the non-FP index but not in the FP index.

If the specified target contains only a subset of the FP pages, then verify mode can detect only the
following inconsistencies:

● Missing key
● Missing row

If the target is a partitioned table, then verify mode also verifies that each row in the table or table
partition has been assigned to the correct partition.

Run in verify mode if metadata, null count, or distinct count errors are returned when running a
query.

 Note
sp_iqcheckdb does not check referential integrity or repair referential integrity violations.

Dropleaks When the SAP IQ server runs in single-node mode, you can use dropleaks mode with either a data­
base or dbspace target to reset the allocation map for the entire database or specified dbspace
targets. If the target is a dbspace, then the dropleaks operation must also prevent read-write oper­
ations on the named dbspace. All dbspaces in the database or dbspace list must be online.

On a multiplex coordinator node, dropleaks mode also detects leaked blocks, duplicate blocks, or
extra blocks across the multiplex.

DBCC Performance
The execution time of DBCC varies, depending on the size of the database for an entire database check, the
number of tables or indexes specified, and the size of the machine. Checking only a subset of the database
(that is, only specified tables, indexes, or index types) requires less time than checking an entire database.

SAP IQ SQL Reference


602 INTERNAL System Procedures
The processing time of sp_iqcheckdb dropleaks mode depends on the number of dbspace targets.

This table summarizes the actions and output of the four sp_iqcheckdb modes.

Mode Errors Detected Output Speed

Allocation Allocation errors Allocation statistics only 4 TB per hour

Check Allocation errors All available statistics 60 GB per hour

Most index errors

Verify Allocation errors All available statistics 15 GB per hour

All index errors

Dropleaks Allocation errors Allocation statistics only 4 TB per hour

Output

Depending on the execution mode, sp_iqcheckdb output includes summary results, errors, informational
statistics, and repair statistics. The output may contain as many as three results sets, if you specify multiple
modes in a single session. Error statistics are indicated by asterisks (*****), and appear only if errors are
detected.

The output of sp_iqcheckdb is also copied to the SAP IQ message file .iqmsg. If the DBCC_LOG_PROGRESS
option is ON, sp_iqcheckdb sends progress messages to the IQ message file, allowing the user to follow the
progress of the DBCC operation as it executes.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

ALTER DATABASE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

(back to top)

None

SAP IQ SQL Reference


System Procedures INTERNAL 603
Examples

(back to top)

● Checks the allocation for the entire database:

sp_iqcheckdb 'allocation database'

● Executes dropleaks mode on dbspace IQ_SYSTEM_MAIN:

sp_iqcheckdb 'dropleaks dbspace IQ_SYSTEM_MAIN'

● Performs a detailed check on indexes i1, i2, and dbo.t1.i3. If you do not specify a new mode,
sp_iqcheckdb applies the same mode to the remaining targets, as shown in the following command:

sp_iqcheckdb 'verify index i1 index i2 index dbo.t1.i3'

● You can combine all modes and run multiple checks on a database in a single session. Perform a quick
check of partition p1 in table t2, a detailed check of index i1, and allocation checking for the entire
database using half of the CPUs:

sp_iqcheckdb 'check table t2 partition p1 verify index i1


allocation database resources 50'

● Checks all indexes of the type FP in the database:

sp_iqcheckdb 'check indextype FP database'

● Verifies the FP and HG indexes in the table t1 and the HNGindexes in the table t2:

sp_iqcheckdb 'verify indextype FP indextype HG table t1 indextype HNG table


t2'

● Check for LVC cell inconsistencies:

sp_iqcheckdb 'check index EFG2JKL.ASIQ_IDX_T208_C504_FP'


------------------------------------
Index Statistics:
** Inconsistent Index: abcd.EFG2JKL.ASIQ_IDX_T208_C504_FP ****** FP
Indexes Checked: 1
** Unowned LVC Cells: 212 ******

The sp_iqcheckdb LVC cells messages include:


○ Unowned LVC cells
○ Duplicate LVC cell rows
○ Unallocated LVC cell rows
These messages indicate inconsistencies with a VARCHAR, VARBINARY, LONG BINARY (BLOB), or LONG
VARCHAR (CLOB) column. Unowned LVC cells represent a small amount of unusable disk space and can
safely be ignored. Duplicate and Unallocated LVC cells are serious errors that can be resolved only by
dropping the damaged columns.
To drop a damaged column, create a new column from a copy of the old column, then drop the original
column and rename the new column to the old column.

 Note

LVC is a VARCHAR or VARBINARY column with a width greater than 255. LONG BINARY (BLOB) and
LONG VARCHAR (CLOB) also use LVC.

SAP IQ SQL Reference


604 INTERNAL System Procedures
● Run sp_iqcheckdb 'allocation database':

===================================================================
DBCC Allocation Mode Report
===================================================================
DBCC Status No Errors Detected
===================================================================
Allocation Summary
===================================================================
Blocks Total 25600
Blocks in Current Version 5917
Blocks in All Versions 5917
Blocks in Use 5917
% Blocks in Use 23
===================================================================
Allocation Statistics
===================================================================
Marked Logical Blocks 8320
Marked Physical Blocks 5917
Marked Pages 520
Blocks in Freelist 2071196
Imaginary Blocks 2014079
Highest PBN in Use 1049285
Total Free Blocks 19683
Usable Free Blocks 19382
% Total Space Fragmented 1
% Free Space Fragmented 1
Max Blocks Per Page 16
1 Block Page Count 165
3 Block Page Count 200
4 Block Page Count 1
10 Block Page Count 1
16 Block Page Count 153
2 Block Hole Count 1
3 Block Hole Count 19
6 Block Hole Count 12
7 Block Hole Count 1
10 Block Hole Count 1
15 Block Hole Count 1
16 Block Hole Count 1220
Partition Summary
Database Objects Checked 2
Blockmap Identity Count 2
Bitmap Count 2
===================================================================
Connection Statistics
===================================================================
Sort Records 3260
Sort Sets 2
===================================================================
DBCC Info
===================================================================
DBCC Work units Dispatched 197
DBCC Work units Completed 197
DBCC Buffer Quota 255
DBCC Per-Thread Buffer Quota 255
Max Blockmap ID found 200
Max Transaction ID found 404

 Note

The report may indicate leaked space. Leaked space is a block that is allocated according to the
database free list (an internal allocation map), but DBCC finds that the block is not part of any
database object.

SAP IQ SQL Reference


System Procedures INTERNAL 605
Related Information

Determining the Security Model Used by a Database [page 576]

7.5.7 sp_iqcheckfpconsistency Procedure

Checks consistency of default indexes created on table columns.

 Syntax

sp_iqcheckfpconsistency ( <table_name>, <column_name>, <table_owner> )

Parameters

table_name

The name of the table that you want to check.


column_name

The name of the column to check.


table_owner

The name of the owner of tables to check.

Remarks

When you create a table, SAP IQ assigns a default index to each new column. This procedure checks these
indexes and diagnoses corrupted tables and columns.

All parameters are optional. You may run the procedure in several ways:

● None – verifies all columns of all tables:

call sp_iqcheckfpconsistency()

 Note

This may take a long time.

● Specifying only <table_name> – verifies all columns of the given table:

call sp_iqcheckfpconsistency('<table_name>')

SAP IQ SQL Reference


606 INTERNAL System Procedures
● Specifying <table_name> and <column_name> – verifies <table_name>.<column_name> under all
owners:

call sp_iqcheckfpconsistency('<table_name>', '<column_name>')

● Specifying <table_name>, <column_name>, and <table_owner> – verifies the column uniquely


identified by <table_owner>.<table_name>.<column_name>

call sp_iqcheckfpconsistency('<table_name>', '<column_name>', '<table_owner>')

The procedure returns a result table that provides a summary report. If SAP IQ detects errors, it returns
detailed error messages in the SAP IQ message file.

Currently there is no consistency verification for columns with BIT data types. The report returns "No Errors
Detected," but does not actually verify them.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● This statement checks consistency for all columns in the customer table:

call sp_iqcheckfpconsistency('customer')

table_owner table_name column_name status

dba customer c_acctbal Errors Detected

dba customer c_address Errors Detected

dba customer c_comment No Errors Detected

dba customer c_custkey Errors Detected

dba customer c_name Errors Detected

dba customer c_phone Errors Detected

SAP IQ SQL Reference


System Procedures INTERNAL 607
table_owner table_name column_name status

... ... ... ...

See the SAP IQ message


file for detail error
messages

● This statement checks consistency for the column DBA.customer.c_address:

call sp_iqcheckfpconsistency('customer', 'c_address', 'dba')

table_owner table_name column_name status

dba customer c_address Errors Detected

See the SAP IQ message


file for detail error
messages.

7.5.8 sp_iqcheckoptions Procedure

For the connected user, sp_iqcheckoptions displays a list of the current value and the default value of
database and server startup options that have been changed from the default.

 Syntax

sp_iqcheckoptions

Returns

Column Name Description

User_name The name of the user or role for whom the option has been set. At database creation, all options
are set for the PUBLIC role. Any option that has been set for a role or user other than PUBLIC is
displayed.

Option_name The name of the option.

Current_value The current value of the option.

Default_value The default value of the option.

Option_type “Temporary” for a TEMPORARY option, else “Permanent”.

SAP IQ SQL Reference


608 INTERNAL System Procedures
Remarks

Returns one row for each option that has been changed from the default value. The output is sorted by option
name, then by user name.

For the connected user, the sp_iqcheckoptions stored procedure displays a list of the current value and the
default value of database and server startup options that have been changed from the default.
sp_iqcheckoptions considers all SAP IQ and SAP SQL Anywhere database options. SAP IQ modifies some
SAP SQL Anywhere option defaults, and these modified values become the new default values. Unless the new
SAP IQ default value is changed again, sp_iqcheckoptions does not list the option.

When sp_iqcheckoptions is run, the DBA sees all options set on a permanent basis for all roles and users
and sees temporary options set for DBA. Users who are not DBAs see their own temporary options. All users
see nondefault server startup options.

The DBA user sees all options set on a permanent basis for all roles and users, along with temporary options
set for the DBA. Users who are not DBAs see their own temporary options. All users see nondefault server
startup options.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

In these examples, the temporary option APPEND_LOAD is set to ON and the role myrole has the option
MAX_WARNINGS set to 9. The user joel has a temporary value of 55 set for MAX_WARNINGS.

● In the first example, sp_iqcheckoptions is run by the DBA:

User_name Option_name Current_value Default_value Option_type


DBA Ansi_update_constr CURSORS Off Permanent
PUBLIC Ansi_update_constr Cursors Off Permanent
DBA Checkpoint_time 20 60 Temporary
DBA Connection_authent Company=MyComp; Temporary
Application=DBTools;Signa
DBA Login_procedure DBA.sp_iq_proce sp_login_envir Permanent
PUBLIC Login_procedure DBA.sp_iq_proce sp_login_envir Permanent
myrole Max_Warnings 9 281474976710655 Permanent
DBA Thread_count 25 0 Temporary

SAP IQ SQL Reference


System Procedures INTERNAL 609
● In the second example, sp_iqcheckoptions is run by the user joel:

User_name Option_name Current_value Default_value Option_type


joel Ansi_update_constr CURSORS Off Permanent
PUBLIC Ansi_update_constr Cursors Off Permanent
joel Checkpoint_time 20 60 Temporary
joel Connection_authent Company=MyComp; Temporary
Application=DBTools;Signa
joel Login_procedure DBA.sp_iq_proce sp_login_envir Permanent
PUBLIC Login_procedure DBA.sp_iq_proce sp_login_envir Permanent
joel Max_Warnings 55 281474976710655 Temporary
joel Thread_count 25 0 Temporary

7.5.9 sp_iqclient_lookup Procedure

Allows a client application to determine the SAP IQ user account responsible for a particular data stream, as
observed in a network analyzer originating from a specific client IP address/port.

 Syntax

sp_iqclient_lookup [ '<IPaddress>' ], [ <Port> ], [ <UserID> ]

Parameters

IPaddress

The IP address of the originating client application.


Port

The port number of the originating client application.


UserID

The SAP IQ user ID.

Remarks

The sp_iqclient_lookup procedure takes the client IP address and port number and returns a single row
containing Number (the connection ID), IPaddress, Port, and UserID:

sp_iqclient_lookup '158.76.235.71',3360

Number IPaddress Port UserID


------ --------- ---- ------
15 158.76.235.71 3360 rdeniro

SAP IQ SQL Reference


610 INTERNAL System Procedures
Optionally, you can pass a third argument to select only the UserID. If no arguments are passed,
sp_iqclient_lookup returns all current logins with their IP addresses and port numbers. For example:

sp_iqclient_lookup

Number IPaddress Port UserID


------ --------- ---- ------
11 162.66.131.36 2082 mbrando
21 162.66.100.233 1863 apacino
22 162.66.100.206 8080 jcaan
23 162.66.100.119 6901 rduvall
24 162.66.100.125 7001 dkeaton
25 162.66.100.124 6347 jcazale
(6 rows affected)
(return status = 0)

If a client application is not using TCP/IP or for internal connections, the address appears as 127.0.0.1.

 Note

This information is available for logged on users only. No historical login data is kept on the server for this
purpose.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● SELECT ANY TABLE System privileges GRANT System Privilege Statement [page 1511]

● MONITOR
● DROP CONNECTION
● SERVER OPERATOR

Side Effects

The sp_iqclient_lookup stored procedure may impact server performance, which varies from one
installation to another. Finding the login name entails scanning through all current active connections on the
server; therefore, the impact may be greater on servers with large numbers of connections. Furthermore, this
information cannot be cached as it is dynamic — sometimes highly dynamic. It is, therefore, a matter for the
local system administrator to manage the use of this stored procedure, as well as monitor the effects on the
server, just as for any other client application that uses server facilities.

SAP IQ SQL Reference


System Procedures INTERNAL 611
Examples

● The following example shows IP addresses for UserID jcazale:

sp_iqclient_lookup null, null, jcazale

Number IPaddress Port UserID


------ ---------- ---- ------
11 162.66.131.36 2082 jcazale
15 164.66.131.36 1078 jcazale

● The following example shows IP addresses from client IP 162.66.131.36:

sp_iqclient_lookup '162.66.131.36'

Number IPaddress Port UserID


------ ---------- ---- ------
11 162.66.131.36 2082 jcazale
12 162.66.131.36 1078 jcaan

 Note

The result is empty when the user specifies an incorrect argument.

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.10 sp_iqcolumn Procedure

Displays information about columns in a database.

 Syntax

Syntax 1

sp_iqcolumn ( [ <table_name> ],[ <table_owner> ], [ <table_loc> ] )

Syntax 2

sp_iqcolumn [ table_name='<table_name>' ],
[ table_owner='<tableowner>' ],[ table_loc='<table_loc>' ]

Parameters

table_name

SAP IQ SQL Reference


612 INTERNAL System Procedures
A parameter that specifies the name of the table.
table_owner

A parameter that specifies the name of the table.


table_loc

A parameter that specifies the location of the table.

Returns

Column Name Description

table_name The name of the table.

table_owner The owner of the table.

column_name The name of the column.

domain_name The data type.

width The precision of numeric data types that have precision and scale or the storage width of numeric
data types without scale; the width of character data types.

scale The scale of numeric data types.

nulls Values are:

● 'Y' – if the column can contain NULLS


● 'N' – if the column cannot contain NULLS

default 'Identity/Autoincrement' if the column is an identity/autoincrement column; null if not.

cardinality The distinct count, if known, by indexes.

location Values are:

● TEMP – IQ temporary store


● MAIN – IQ main store
● SYSTEM – catalog store

isPartitioned Values are:

● 'Y' – if the column belongs to a partitioned table and has one or more partitions that have a
dbspace is different from the table partition’s dbspace
● 'N' – if the column's table is not partitioned or each partition of the column resides in the
same dbspace as the table partition.

remarks User comments added with the COMMENT statement.

check The check constraint expression.

Remarks

Displays information about columns in a database. Specifying the <table_name> parameter returns the
columns only from tables with that name. Specifying the table_owner parameter returns only tables owned by

SAP IQ SQL Reference


System Procedures INTERNAL 613
that user. Specifying both <table_name> and table_owner parameters chooses the columns from a unique
table, if that table exists. Specifying table_loc returns only tables that are defined in that segment type.
Specifying no parameters returns all columns for all tables in a database. sp_iqcolumn does not return
column information for system tables.

Syntax 1
If you specify <table_owner> without specifying <table_name>, you must substitute NULL for
<table_name>. For example, sp_iqcolumn NULL,DBA.

Syntax 2
The parameters can be specified in any order. Enclose '<table_name>' and '<table_owner>' in single quotes.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● The following variations in syntax both return all of the columns in the table Departments:

sp_iqcolumn Departments

call sp_iqcolumn (table_name='Departments')

table_name table_owner column_name domain_name width scale nulls de


fault
Departments GROUPO DepartmentID integer 4 0 N (N
ULL)
Departments GROUPO DepartmentName char 40 0 N (N
ULL)
Departments GROUPO DepartmentHead integer 4 0 Y (N
ULL)
cardinality location isPartitioned remarks check
5 Main N (NULL) (NULL)
0 Main N (NULL) (NULL)
0 Main N (NULL) (NULL)

● The following variation in syntax returns all of the columns in all of the tables owned by table owner DBA:

sp_iqcolumn table_owner='DBA'

SAP IQ SQL Reference


614 INTERNAL System Procedures
Related Information

sp_iqconstraint Procedure [page 622]


sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.11 sp_iqcolumnmetadata Procedure

Returns details about column indexes in one or more tables.

 Syntax

sp_iqcolumnmetadata [ <table.name> [, <owner-name> ] ]

Parameters

table.name

A parameter that specifies the name of the table.


owner-name

A parameter that specifies the owner name.

Remarks

sp_iqcolumnmetadata reads the index metadata to return details about column indexes in both base and
global temporary tables. Index metadata reported for a global temporary table is for the individual instance of
that table.

Include the optional <table.name> parameter to generate details for that table. Omit the <table.name>
parameter to generate details for all tables in the database.

SAP IQ SQL Reference


System Procedures INTERNAL 615
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

If you own the object, no additional privilege is require.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● ALTER ANY INDEX sys­ System privileges GRANT System Privilege Statement [page 1511]

tem privilege
● ALTER ANY OBJECT
system privilege
● REFERENCE permis­
sions on the table

Side Effects

None

7.5.12 sp_iqcolumnuse Procedure

Reports detailed usage information for columns accessed by the workload.

 Syntax

sp_iqcolumnuse

Returns

Column Name Description

TableName Table name.

ColumnName Column name.

Owner User name of column owner.

UID Column unique identifier, a number assigned by the system that uniquely identifies the instance of
the column (where instance is defined when an object is created).

LastDT Date/time of last access.

SAP IQ SQL Reference


616 INTERNAL System Procedures
Column Name Description

NRef Number of query references.

Remarks

Columns from tables created in SYSTEM are not reported.

 Tip

The INDEX_ADVISOR option generates messages suggesting additional column indexes that may improve
performance of one or more queries.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Type Privilege Name Grant Statement

System privilege MONITOR GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example shows sample output from the sp_iqcolumnuse procedure (the long numbers are
temporary IDs):

TableName ColumnName Owner UID LastDT NRef


orders o_orderdate DBA 151 20070917 22:41:22.. 13
orders o_shippriority DBA 154 20070917 22:41:22.. 13
lineitem l_orderkey DBA 186 20070917 22:41:22.. 13
lineitem l_extendedp.. DBA 191 20070917 22:41:22.. 13
lineitem l_discount DBA 192 20070917 22:41:22.. 13
lineitem l_shipdate DBA 196 20070917 22:41:22.. 13
#tmp1 expression DBA 10000000001218 20070917 22:57:36.. 1
#tmp1 expression DBA 10000000001222 20070917 22:41:58.. 1
...

SAP IQ SQL Reference


System Procedures INTERNAL 617
Related Information

sp_iqindexadvice Procedure [page 673]


sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]
sp_iqworkmon Procedure [page 815]

7.5.13 sp_iqconnection Procedure

Shows information about connections and versions, including which users are using temporary dbspace, which
users are keeping versions alive, what the connections are doing inside SAP IQ, connection status, database
version status, and so on.

 Syntax

sp_iqconnection [ <connhandle> ]

Go to:

● Returns
● Remarks
● Privileges
● Side Effects

Parameters

(back to top)

connhandle

The ID number of the connection.

Returns

(back to top)

Column Name Description

ConnHandle The ID number of the connection

SAP IQ SQL Reference


618 INTERNAL System Procedures
Column Name Description

Name The connection name specified by the ConnectionName (CON) connection parame­
ter.

Userid The user ID for the connection.

LastReqTime The time at which the last request for the specified connection started.

ReqType A string for the type of the last request.

IQCmdType SAP IQ side, if any. The command type reflects commands defined at the implemen­
tation level of the engine. These commands consist of transaction commands, DDL
and DML commands for data in the IQ store, internal IQ cursor commands, and spe­
cial control commands such as The current command executing on the OPEN and
CLOSE, BACKUP DATABASE, RESTORE DATABASE, and others.

LastIQCmdTime The time the last IQ command started or completed on the IQ side of the SAP IQ en­
gine on this connection.

IQCursors The number of cursors open in the IQ store on this connection.

LowestIQCursorState The IQ cursor state, if any. If multiple cursors exist on the connection, the state that
appears is the lowest cursor state of all the cursors; that is, the furthest from comple­
tion. Cursor state reflects internal SAP IQ implementation detail and is subject to
change in the future. Cursor states are:

● NONE – no cursors have been rendered.


● INITIALIZED – cursor is initialized.
● PARSED – cursor is parsed and costed.
● DESCRIBED – cursor information, such as column information, has been put into
the descriptor.
● COSTED – cursor cost has been costed.
● PREPARED –statement has been prepared; cursor is executing.
● EXECUTED – after PREPARED, cursor state transitions to EXECUTED.
● FETCHING – fetching rows from cursor result set.
● END_OF_DATA – seen the last record.
● CLOSED – closed; DFO tree stays in place for re-open.
● COMPLETED – is completed. Tearing down DFO tree.
● INVALID – unrecoverable error occurred.

As suggested by the names, the cursor state changes at the end of the operation. A
state of PREPARED, for example, indicates that the cursor is executing.

IQthreads The number of SAP IQ

TxnID The transaction ID of the current transaction on the connection. This is the same as
the transaction ID in the .iqmsg file by the BeginTxn, CmtTxn, and PostCmtTxn mes­
sages, as well as the Txn ID Seq logged when the database is opened.

ConnCreateTime The time the connection was created.

TempTableSpaceKB The number of kilobytes of IQ temporary store space in use by this connection for
data stored in IQ temp tables. threads currently assigned to the connection. Some
threads may be assigned but idle. This column can help you determine which connec­
tions are using the most resources. threads currently assigned to the connection.
Some threads may be assigned but idle. This column can help you determine which
connections are using the most resources.nullnullnull

SAP IQ SQL Reference


System Procedures INTERNAL 619
Column Name Description

TempWorkSpaceKB nullThe number of kilobytes of IQ temporary store space in use by this connection for
working space such as sorts, hashes, and temporary bitmaps. Space used by bitmaps
or other objects that are part of indexes on SAP IQ temporary tables are reflected in
TempTableSpaceKB.

IQConnID The 10-digit connection ID included as part of all messages in the .iqmsg file. This is
a monotonically increasing integer unique within a server session.

satoiq_count An internal counter used to display the number of crossings from the SAP SQL
Anywhere side to the IQ side of the SAP IQ engine. This might be occasionally useful
in determining connection activity. Result sets are returned in buffers of rows and do
not increment satoiq_count or iqtosa_count once per row.

iqtosa_count An internal counter used to display the number of crossings from the IQ side to the
SAP SQL Anywhere side of the SAP IQ engine. This might be occasionally useful in de­
termining connection activity.

CommLink The communication link for the connection. This is one of the network protocols sup­
ported by SAP IQ, or is local for a same-machine connection.

NodeAddr The node for the client in a client/server connection.

LastIdle The number of ticks between requests.

MPXServerName If an INC connection, the VARCHAR(128) value contains the name of the multiplex
server where the INC connection originates. NULL if not an INC connection.

LSName The logical server name of the connection. NULL if logical server context is unknown
or not applicable.

INCConnName The name of the underlying INC connection for a user connection. The data type for
this column is VARCHAR(255). If sp_iqconnection shows an INC connection
name for a suspended user connection that user connection has an associated INC
connection that is also suspended.

INCConnSuspended The value "Y" in this column indicates that the underlying INC connection for a user
connection is in a suspended state. The value "N" indicates that the connection is not
suspended.

Remarks

(back to top)

<connhandle> is equal to the Number connection property and is the ID number of the connection. The
connection_property system function returns the connection ID:

SELECT connection_property ( 'Number' )

When called with an input parameter of a valid <connhandle>, sp_iqconnection returns the one row for
that connection only.

sp_iqconnection returns a row for each active connection. The columns ConnHandle, Name, Userid,
LastReqTime, ReqType, CommLink, NodeAddr, and LastIdle are the connection properties Number, Name,
Userid, LastReqTime, ReqType, CommLink, NodeAddr, and LastIdle, respectively, and return the same

SAP IQ SQL Reference


620 INTERNAL System Procedures
values as the system function sa_conn_info. The additional columns return connection data from the SAP IQ
side of the SAP IQ engine. Rows are ordered by ConnCreateTime.

The column MPXServerName stores information related to internode communication (INC), as shown:

Server Where Run MPXServerName Column Content

SAP IQ server NULL (All connections are local/user connections)

Multiplex coordinator ● NULL for local or user connections.


● Contains value of secondary node's server name (source of connection) for every INC con­
nection (either on-demand or dedicated heartbeat connection).

Multiplex secondary ● NULL for local or user connections.


● Contains value of coordinator's server name (source of connection).

In Java applications, specify SAP IQ-specific connection properties from TDS clients in the RemotePWD field.
This example, where myconnection becomes the IQ connection name, shows how to specify IQ-specific
connection parameters:

p.put("RemotePWD",",,CON=myconnection");

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● DROP CONNECTION System privileges GRANT System Privilege Statement [page 1511]

● MONITOR
● SERVER OPERATOR

Side Effects

(back to top)

None

SAP IQ SQL Reference


System Procedures INTERNAL 621
7.5.14 sp_iqconstraint Procedure

Lists referential integrity constraints defined using CREATE TABLE or ALTER TABLE for the specified table or
column.

 Syntax

sp_iqconstraint [ '<table-name>', '<column-name>', '<table-owner>' ]

Parameters

table-name

A parameter that specifies the name of the table.


column-name

A parameter that specifies the name of the column.


table-owner

A parameter that specifies the table owner.

Remarks

If table name and column name are omitted, reports all referential integrity constraints for all tables including
temporary ones in the current connected database. The information includes unique or primary key constraint,
referential constraint, and associated role name that are defined by the CREATE TABLE and/or ALTER TABLE
statements.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

SAP IQ SQL Reference


622 INTERNAL System Procedures
Example

This is sample output that displays all primary key/foreign key pairs where either the candidate key or foreign
key contains column ck1 for owner bob in all tables:

call sp_iqconstraint('','ck1','bob')

PTAB1 bob ASIQ_IDX_T27_HG unique ck1,ck2 selftab bob CK6FK3 Y


ASIQ_IDX_T42_HG ck1,ck2PTAB2 bob ASIQ_IDX_T27_HG unique ck1,ck2 selftab bob
CK6FK4 Y
ASIQ_IDX_T206_I42_HG ck1,ck2selftab bob ASIQ_IDX_T26_HG unique ck1,ck2
selftab bob CK3FK1 Y
ASIQ_IDX_T206_I42_HG ck1,ck2

The columns displayed are:

● Primary enforced table


● Table owner
● Candidate key index
● Primary key or inique
● Primary key columns
● Foreign table
● Foreign table owner
● Foreign key role name
● Enforced status (“Y” for enforced, “N” for unenforced)
● Foreign key index
● Foreign key columns
● Location (“TEMP,” “MAIN,” or “SYSTEM”)

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 623
7.5.15 sp_iqcontext Procedure

Tracks and displays, by connection, information about statements that are currently executing.

 Syntax

sp_iqcontext [ <connhandle> ]

Parameter

connhandle

The ID number of the connection.

Returns

Column Name Description

ConnOrCursor CONNECTION, CURSOR, or DQP.

ConnHandle The ID number of the connection or 0 for DQP.

Name The name of the server (leader name).

Userid The user ID for the connection, cursor, or DQP worker.

numIQCursors If column 1 is CONNECTION the number of cursors open on this connection. If column
1 is:

● CURSOR – a number assigned sequentially to cursors associated with this con­


nection.
● DQP – then 0. CONNECTION can also return a value of 0.

IQthreads The number of IQ threads currently assigned to the connection. Some threads may
be assigned but idle. For DQP threads, indicates the number of threads assigned to
the DQP worker.

TxnID The transaction ID of the current transaction. In the case of a worker thread, indicates
the leader’s transaction ID.

ConnOrCurCreateTime The time this connection, cursor, or DQP worker was created.

IQConnID The connection ID displayed as part of all messages in the .iqmsg file. This is a mo­
notonically increasing integer unique within a server session.

SAP IQ SQL Reference


624 INTERNAL System Procedures
Column Name Description

IQGovernPriority A value that indicates the order in which the queries of a user are queued for execu­
tion. 1 indicates high priority, 2 (the default) medium priority, and 3 low priority. A
value of -1 indicates that IQGovernPriority does not apply to the operation. Set the IQ­
GovernPriority value with the database option IQGOVERN_PRIORITY.

For DQP connections, this column displays No command.

CmdLine First 4096 characters of the user command being executed.

For DQP connections, this column displays No command.

Attributes Unique ID for the query being distributed.

Remarks

The input parameter <connhandle> is equal to the Number connection property and is the ID number of the
connection. For example, SELECT CONNECTION_PROPERTY('NUMBER').

When called with an input parameter of a valid <connhandle>, sp_iqcontext returns the information only
for that connection.

sp_iqcontext lets the DBA determine what statements are running on the system at any given moment, and
identify the user and connection that issued the statement. With this information, you can use this utility to:

● Match the statement text with the equivalent line in sp_iqconnection to get resource usage and
transactional information about each connection
● Match the statement text to the equivalent line in the SQL log created when the -zr server option is set to
ALL or SQL
● Use connection information to match the statement text in sp_iqcontext to the equivalent line in
the .iqmsg file, which includes the query plan, when SAP IQ can collect it
● Match statement text to an SAP IQ stack trace (stktrc-yyyymmdd-hhnnss_#.iq), if one is produced
● Collate this information with an operating system stack trace that might be produced, such as pstack on
Sun Solaris

The maximum size of statement text collected is the page size of the catalog store.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

SAP IQ SQL Reference


System Procedures INTERNAL 625
Privilege Name Privilege Type Grant Statement

● MANAGE ANY USER System privileges GRANT System Privilege Statement [page 1511]
● MONITOR

Side Effects

None

Example

The following example shows an excerpt from output when sp_iqcontext is issued with no parameter,
producing results for all current connections. Column names are truncated due to space considerations:

ConnOrCu.. ConnHandle Name UserId numIQ.. IQthr.. TxnID Conn.. IQcon.. IQGov..
Cmd.. Attributes
CONNECTION 2 sun7bar dbo 0 0 0 2010-08-04 15:15:40.0 15 No command NO COMMAND
CONNECTION 7 sun7bar dbo 0 0 0 2010-08-04 15:16:00.0 32 No command NO COMMAND
CONNECTION 10 sun7bar dbo 0 0 0 2010-08-04 15:16:21.0 46 No command NO COMMAND
...
CONNECTION 229 sun7bar DBA 0 0 1250445 2010-08-05 18:28:16.0 50887 2 select
server_name,
inc_state, coordinator_failover from sp_iqmpxinfo() order by server_name
...
DQP 0 dbsrv2873_node_c1DBA 0 1 10000 2010-08-05 18:28:16.0 no command no command
Query ID:
12345; Condition: c1 > 100;
DQP 0 dbsrv2873_node_c1DBA 0 1 10001 2010-08-05 18:28:16.0 no command no command
Query ID:
12346; Node #12 Join (Hash);

The first line of output shows connection 2 (IQ connection ID 15). This connection is on server sun7bar, user
dbo. This connection was not executing a command when sp_iqcontext was issued.

Connection 229 shows the user command being executed (the command contains less than the maximum
4096 characters the column can display). The 2 before the user command fragment indicates that this is a
medium priority query.

The connection handle (2 for the first connection in this example) identifies results in the -zr log. The IQ
connection ID (15 for the first connection in this example) identifies results in the .iqmsg file. On UNIX
systems, you can use grep to locate all instances of the connection handle or connection ID, making it easy to
correlate information from all sources.

The second-last line (TxnID 10000) shows a DQP worker thread. The worker connection is running two
invariant conditions.

The last line (TxnID 10001) shows connection is running a hash join.

SAP IQ SQL Reference


626 INTERNAL System Procedures
Related Information

CONNECTION_PROPERTY Function [System] [page 302]


sp_iqshowpsexe Procedure [page 758]
Determining the Security Model Used by a Database [page 576]

7.5.16 sp_iqcopyloginpolicy Procedure

Creates a new login policy by copying an existing one.

 Syntax

Syntax 1

call sp_iqcopyloginpolicy ('<existing-policy-name>', '<new-policy-name>' )

Syntax 2

sp_iqcopyloginpolicy '<existing-policy-name>', '<new-policy-name>'

Parameters

existing-policy-name

A parameter that specifies the login policy to copy.


new-policy-name

A CHAR(128) parameter that specifies the name of the new login policy to create.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY LOGIN POL­ System privilege GRANT System Privilege Statement [page 1511]
ICY

SAP IQ SQL Reference


System Procedures INTERNAL 627
Side Effects

None

Example

The following example creates a new login policy named <lockeduser> by copying the login policy option
values from the existing login policy named "root":

call sp_iqcopyloginpolicy ('root','lockeduser')

Related Information

sp_expireallpasswords System Procedure [page 920]


(Deprecated) sp_iqaddlogin Procedure [page 585]
sp_iqmodifylogin Procedure [page 703]
(Deprecated) sp_iqpassword Procedure [page 725]
Determining the Security Model Used by a Database [page 576]

7.5.17 sp_iqcursorinfo Procedure

Displays detailed information about cursors currently open on the server.

 Syntax

sp_iqcursorinfo [ <cursor-name> ] [, <conn-handle> ]

Parameters

cursor-name

The name of the cursor. If only this parameter is specified, sp_iqcursorinfo returns information about
all cursors that have the specified name in all connections.
conn-handle

An integer representing the connection ID. If only this parameter is specified, sp_iqcursorinfo returns
information about all cursors in the specified connection.

SAP IQ SQL Reference


628 INTERNAL System Procedures
Returns

Column Name Description

Name The name of the cursor.

ConnHandle The ID number of the connection.

IsUpd Y: the cursor is updatable; N otherwise.

IsHold Y: the cursor is a hold cursor; N otherwise.

IQConnID The 10-digit connection ID displayed as part of all messages in the .iqmsg file. This number is a
monotonically increasing integer that is unique within a server session.

UserID User ID (or user name) for the user who created and ran the cursor.

CreateTime The time of cursor creation.

CurrentRow The current position of the cursor in the result set.

NumFetch The number of times the cursor fetches a row. The same row can be fetched more than once.

NumUpdate The number of times the cursor updates a row, if the cursor is updatable. The same row can be
updated more than once.

NumDelete The number of times the cursor deletes a row, if the cursor is updatable.

NumInsert The number of times the cursor inserts a row, if the cursor is updatable.

RWTabOwner The owner of the table that is opened in RW mode by the cursor.

RWTabName The name of the table that is opened in RW mode by the cursor.

CmdLine The first 4096 characters of the command the user executed.

Remarks

The sp_iqcursorinfo procedure can be invoked without any parameters. If no parameters are specified,
sp_iqcursorinfo returns information about all cursors currently open on the server. If both parameters are
specified, sp_iqcursorinfo reports information about all of the cursors that have the specified name and are
in the specified connection.

If you do not specify the first parameter, but specify the second parameter, you must substitute NULL for the
omitted parameter. For example, sp_iqcursorinfo NULL, 1.

The sp_iqcursorinfo stored procedure displays detailed information about cursors currently open on the
server. The sp_iqcursorinfo procedure enables database administrators to monitor cursor status using just
one stored procedure and view statistics such as how many rows have been updated, deleted, and inserted.

If you specify one or more parameters, the result is filtered by the specified parameters. For example, if
<cursor-name> is specified, only information about the specified cursor is displayed. If <conn-handle> is
specified, sp_iqcursorinfo returns information only about cursors in the specified connection. If no
parameters are specified, sp_iqcursorinfo displays information about all cursors currently open on the
server.

SAP IQ SQL Reference


System Procedures INTERNAL 629
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Examples

● The following example displays information about all cursors currently open on the server:

sp_iqcursorinfo
Name ConnHandle IsUpd IsHold IQConnID UserID
---------------------------------------------------------------------
crsr1 1 Y N 118 DBA
crsr2 3 N N 118 DBA
CreateTime CurrentRow NumFetch NumUpdate
----------------------------------------------------------------
2009-06-26 15:24:36.000 19 100000000 200000000
2009-06-26 15:38:38.000 20000 200000000
NumDelete NumInsert RWTabOwner RWTabName CmdLine
----------------------------------------------------------------------
20000000 3000000000 DBA test1 call proc1()
call proc2()

● The following example displays information about all cursors currently open on the server:

sp_iqcursorinfo

● The following example displays information about the all cursors named cursor1 in all connections:

sp_iqcursorinfo 'cursor1'

● The following example displays information about all cursors in connection 3:

sp_iqcursorinfo NULL, 3

● The following example displays information about all the cursors named cursor2 in connection 4:

sp_iqcursorinfo 'cursor2', 4

SAP IQ SQL Reference


630 INTERNAL System Procedures
Related Information

Determining the Security Model Used by a Database [page 576]

7.5.18 sp_iqdatatype Procedure

Displays information about system data types and user-defined data types.

 Syntax

sp_iqdatatype [ <type-name> ], [ <type-owner> ], [ <type-type> ]

Parameters

type-name

The name of the data type.


type-owner

The name of the creator of the data type.


type-type

The type of data type. Allowed values are:

● SYSTEM – displays information about system defined data types (data types owned by user SYS or
dbo) only
● ALL – displays information about user and system data types
● Any other value – displays information about user data types

Returns

Column Name Description

type_name The name of the data type.

creator The owner of the data type.

nulls Y indicates the user-defined data type allows nulls; N indicates the data type does not allow nulls
and U indicates the null value for the data type is unspecified.

width Displays the length of string columns, the precision of numeric columns, and the number of bytes
of storage for all other data types.

scale Displays the number of digits after the decimal point for numeric data type columns and zero for
all other data types.

SAP IQ SQL Reference


System Procedures INTERNAL 631
Column Name Description

"default" The default value for the data type.

"check" The CHECK condition for the data type.

Remarks

The sp_iqdatatype procedure can be invoked without any parameters. If no parameters are specified, only
information about user-defined data types (data types not owned by dbo or SYS) is displayed by default.

If you do not specify either of the first two parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example, sp_iqdatatype NULL, NULL, SYSTEM and
sp_iqdatatype NULL, user1.

The sp_iqdatatype stored procedure displays information about system and user-defined data types in a
database. User-defined data types are also referred to as domains. Predefined domain names are not included
in the sp_iqdatatype output.

If you specify one or more parameters, the sp_iqdatatype result is filtered by the specified parameters. For
example, if <type-name> is specified, only information about the specified data type is displayed. If <type-
owner> is specified, sp_iqdatatype only returns information about data types owned by the specified owner.
If no parameters are specified, sp_iqdatatype displays information about all the user-defined data types in
the database.

The sp_iqdatatype procedure returns information in the following columns:

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● The following example displays information about the user-defined data type country_t:

sp_iqdatatype country_t
type_name creator nulls width scale "default" "check"

SAP IQ SQL Reference


632 INTERNAL System Procedures
country_t DBA U 15 0 (NULL) (NULL)

● The following example displays information about all user-defined data types in the database:

sp_iqdatatype

● The following example displays information about the user-defined data type named country_t:

sp_iqdatatype country_t

● In the following example, no rows are returned, as the data type non_existing_type does not exist:

sp_iqdatatype non_existing_type

● The following example displays information about all user-defined data types owned by DBA:

sp_iqdatatype NULL, DBA

● The following example displays information about the data type country_t owned by DBA:

sp_iqdatatype country_t, DBA

● In the following example, rowid is a system-defined data type. If there is no user-defined data type also
named rowid, no rows are returned. (By default, only user-defined data types are returned.):

sp_iqdatatype rowid

● In the following example, no rows are returned, as the data type rowid is not a user-defined data type (by
default, only user-defined data types are returned):

sp_iqdatatype rowid, SYS

● The following example displays information about all system defined data types (owned by dbo or SYS):

sp_iqdatatype NULL, NULL, SYSTEM

● The following example displays information about the system data type rowid:

sp_iqdatatype rowid, NULL, SYSTEM

● The following example displays information about the user-defined and system data types:

sp_iqdatatype NULL, NULL, 'ALL'

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]

SAP IQ SQL Reference


System Procedures INTERNAL 633
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.19 sp_iqdbsize Procedure

Displays the size of the current database.

 Syntax

sp_iqdbsize ( [ main ] )

Returns

Column Name Description

Database The path name of the database file.

PhysicalBlocks The total database size in blocks. An IQ database consists of one or more dbspaces. Each dbspace
has a fixed size, which is originally specified in units of megabytes. This megabyte quantity is con­
verted to blocks using the IQ page size and the corresponding block size for that IQ page size. The
Physical Blocks column reflects the cumulative total of each SAP IQ dbspace size, represented in
blocks.

KBytes The total size of the database, in kilobytes. This value is the total size of the database in blocks
(PhysicalBlocks in the previous sp_iqdbsize column) multiplied by the block size. The
block size depends on the IQ page size.

Pages The total number of IQ pages necessary to represent in memory all of the data stored in tables and
the metadata for these objects. This value is always greater than or equal to the value of
CompressedPages (the next sp_iqdbsize column).

CompressedPages The total number of IQ pages necessary to store on disk the data in tables and metadata for these
objects. This value is always less than or equal to the value of Pages (the previous
sp_iqdbsize column), because SAP IQ compresses pages when the IQ page is written from
memory to disk. The sp_iqdbsize CompressedPages column represents the number of
compressed pages.

NBlocks The total size in blocks used to store the data in tables. This value is always less than or equal to
the sp_iqdbsize PhysicalBlocks value.

CatalogBlocks The total size in blocks used to store the metadata for tables.

RLVLogBlocks The number of blocks used for log information for the RLV store.

RLVLogKBytes The total size of the RLV log, in kilobytes.

SAP IQ SQL Reference


634 INTERNAL System Procedures
Remarks

Returns the total size of the database. Also returns the number of pages required to hold the database in
memory and the number of IQ pages when the database is compressed (on disk).

If run on a multiplex database, the default parameter is main, which returns the size of the shared IQ store.

If run when there are no rows in any RLV-enabled tables, the Physical Blocks, the RLVLogBlocks and
RLVLogKBytes columns will contain non-zero entries, and the remaining columns contain zeros. This indicates
no row-level versioned tables.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

ALTER DATABASE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example displays size information for the database iqdemo:

sp_iqdbsize

Database PhysicalBlocks KBytes Pages CompressedPages

/system1/IQ/IQ-16_1/ 19786 456 15 13


demo/iqdemo.db

NBlocks CatalogBlocks RLVLogBlocks RLVLogKBytes

57 36 512

SAP IQ SQL Reference


System Procedures INTERNAL 635
Related Information

Determining the Security Model Used by a Database [page 576]

7.5.20 sp_iqdbspace Procedure

Displays detailed information about each SAP IQ dbspace.

 Syntax

sp_iqdbspace [ <dbspace-name> ]

Parameters

dbspace-name

(Optional) A parameter that specifies the name of the dbspace.

Returns

Column Name Description

DBSpaceName The name of the dbspace as specified in the CREATE DBSPACE state­
ment. Dbspace names are always case-insensitive, regardless of the
CREATE DATABASE...CASE IGNORE or CASE RESPECT specifica-
tion.

DBSpaceType The type of the dbspace (MAIN, SHARED_TEMP, TEMPORARY, RLV, or


CACHE).

Writable T (writable) or F (not writable).

Online T (online) or F (offline).

Usage The percent of dbspace currently in use by all files in the dbspace.

TotalSize The total size of all files in the dbspace in the units:

● B (bytes)
● K (kilobytes)
● M (megabytes)
● G (gigabytes)
● T (terabytes)
● P (petabytes)

SAP IQ SQL Reference


636 INTERNAL System Procedures
Column Name Description

Reserve The total reserved space that can be added to all files in the dbspace.

NumFiles The number of files in the dbspace.

NumRWFiles The number of read-write files in the dbspace.

Stripingon T (on) or F (off).

StripeSize Always 1, if disk striping is on.

BlkTypes The space used by both user data and internal system structures.

OkToDrop "Y" indicates the dbspace can be dropped; otherwise "N".

lsname The logical server associated with the DAS dbspace.

is_dbspace_preallocated "F" indicates that the NOPREALLOCATE keyword was used in the CRE­
ATE DBSPACE statement when creating the dbspace on a cooked (not
raw) filesystem; otherwise "T" (the default).

Remarks

Use the information from sp_iqdbspace to determine whether data must be moved, and for data that has
been moved, whether the old versions have been deallocated.

The sp_iqdbspace procedure returns:

Values of the BlkTypes block type identifiers:

● A – active version
● B – backup structures
● C – checkpoint log
● D – database identity
● F – free list
● G – global free list manager
● H – header blocks of the free list
● I – index advice storage
● M – multiplex CM. The multiplex commit identity block (actually 128 blocks) exists in all SAP IQ databases,
even though it is not used by SAP IQ databases.
● N – column use
● O – old version
● R – RLV free list manager. The manager first reserves the blocks from the main store freelist and marks
them as free. As RLV logging uses these blocks, they are marked as in use.
● RC – number of blocks actually in use by RLV store logs
● RU – number of blocks used by the commit log
● T – table use
● U – index use
● X – drop at checkpoint

SAP IQ SQL Reference


System Procedures INTERNAL 637
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBSPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

Displays information about dbspaces:

DBSpaceName DBSpaceType Writable Online Usage

iq_main MAIN T T 26

IQ_SYSTEM_LOG PITR T T 0

IQ_SYSTEM_MAIN MAIN T T 22

IQ_SYSTEM_MAIN TEMPORARY T T 23

rvspace RLV T T 17

TotalSize Reserve NumRWFiles NumFiles Stripingon

100 M 200 M 1 1 T

0B 0B 1 1 F

100 M 200 M 1 1 T

25 M 200 M 1 1 T

1000 M 0B 1 1 F

is_dbspace_preallo­
StripSize BlkTypes OkToDrop lsname cated

1K 1H,3254A N (NULL) T

0B 1H N (NULL) T

1K 1H,2528F,32D,128M N (NULL) T

1K 1H,64F,16A N (NULL) T

SAP IQ SQL Reference


638 INTERNAL System Procedures
is_dbspace_preallo­
StripSize BlkTypes OkToDrop lsname cated

1K 1H,20480R,2096RU, N lsname T
1040RC

 Note

For the rvspace RLV dbspace, in the BlkTypes column, of the 20480 blocks reserved for RLV store logs
(20489R), 2096 blocks are in use (RU), 1040 blocks (RC) of which are in use by the commit log.

Related Information

sp_iqindexinfo Procedure [page 676]


sp_iqdbspaceinfo Procedure [page 639]
sp_iqspaceinfo Procedure [page 760]
Determining the Security Model Used by a Database [page 576]

7.5.21 sp_iqdbspaceinfo Procedure

Displays the size of each object and subobject used in the specified table. Not supported for RLV dbspaces.

 Syntax

sp_iqdbspaceinfo [ <dbspace-name> ]
[, <owner_name> ] [, <object_name> ] [, <object-type> ]

Parameters

dbspace-name

(Optional) If specified, sp_iqdbspaceinfo displays one line for each table that has any component in the
specified dbspace. Otherwise, the procedure shows information for all dbspaces in the database.
owner_name

(Optional) Owner of the object. If specified, sp_iqdbspaceinfo displays output only for tables with the
specified owner. If not specified, sp_iqdbspaceinfo displays information on tables for all users in the
database.
object_name

(Optional) Name of the table. If not specified, sp_iqdbspaceinfo displays information on all tables in the
database.
object_type

SAP IQ SQL Reference


System Procedures INTERNAL 639
(Optional) Valid table objects.

Returns

Column Name Description

dbspace_name The name of the dbspace.

object_type The type of the object (table or joinindex only).

owner The name of the owner of the object.

object_name The name of the object on the dbspace.

object_id The global object ID of the object.

id The table ID of the bject

columns The size of column storage space on the given dbspace.

indexes The size of index storage space on the given dbspace. Does not use sys­
tem-generated indexes (for example, HG indexes in unique constraints or
FP indexes).

metadata The size of storage space for metadata objects on the given dbspace.

primary_key The size of storage space for primary key related objects on the given
dbspace.

unique_constraint The size of storage space for unique constraint-related objects on the
given dbspace.

foreign_key The size of storage space for foreign-key-related objects on the given
dbspace.

dbspace_online Indicates if the dbspace is online (Y) or offline (N).

is_dbspace_preallocate "F" indicates that the NOPREALLOCATE keyword was used in the CRE­
ATE DBSPACE statement when creating the dbspace on a cooked (not
raw) filesystem; otherwise "T" (the default).

Remarks

All parameters are optional, and any parameter may be supplied independent of another parameter’s value.

The sp_iqdbspaceinfo stored procedure supports wildcard characters for interpreting <dbspace_name>,
<object_name>, and <owner_name>. It shows information for all dbspaces that match the given pattern in
the same way the LIKE clause matches patterns inside queries.

The procedure returns no results if you specify an RLV dbspace.

sp_iqdbspaceinfo shows the DBA the amount of space used by objects that reside on each dbspace. The
DBA can use this information to determine which objects must be relocated before a dbspace can be dropped.
The subobject columns display sizes reported in integer quantities followed by the suffix B, K, M, G, T, or P,
representing bytes, kilobytes, megabytes, gigabytes, terabytes, and petabytes, respectively.

SAP IQ SQL Reference


640 INTERNAL System Procedures
For tables, sp_iqdbspaceinfo displays subobject sizing information for all subobjects (using integer
quantities with the suffix B, K, M, G, T, or P) sorted by <dbspace_name>, <object_name>, and
<owner_name>.

If you run sp_iqdbspaceinfo against a server you have started with the -r switch (read-only), you see the
following error:
Msg 13768, Level 14, State 0: SAP SQL Anywhere
Error -757: Modifications not permitted for read-only database.
This behavior is expected. The error does not occur on other stored procedures such as sp_iqdbspace,
sp_iqfile, sp_iqdbspaceobjectinfo, or sp_iqobjectinfo.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● BACKUP DATABASE System privileges GRANT System Privilege Statement [page 1511]
● SERVER OPERATOR
● MANAGE ANY DBSPACE

Side Effects

None

Examples

These examples show objects in the iqdemo database to better illustrate output. iqdemo includes a sample
user dbspace named iq_main that may not be present in your own databases.

● The following example displays the size of all objects and subobjects in all tables in all dbspaces in the
database:

sp_iqdbspaceinfo

dbspace_name object_type owner object_name object_id id columns


iq_main table DBA emp1 3689 741 96K
iq_main table DBA iq_dummy 3686 740 24K
iq_main table DBA sale 3698 742 96K
iq_main table GROUPO Contacts 3538 732 288K
iq_main table GROUPO Customers 3515 731 240K
iq_main table GROUPO Departments 3632 738 72K
iq_main table GROUPO Employees 3641 739 408K

SAP IQ SQL Reference


System Procedures INTERNAL 641
iq_main table GROUPO FinancialCodes 3612 736 72K
iq_main table GROUPO FinancialData 3621 737 96K
iq_main table GROUPO Products 3593 735 272K
iq_main table GROUPO SalesOrderItems 3580 734 120K
iq_main table GROUPO SalesOrders 3565 733 144K
indexes metadata primary_key unique_constraint foreign_key dbspace_online
is_dbspace_preallocate
0B 1.37M 0B 0B 0B Y
T
0B 464K 0B 0B 0B Y
T
0B 1.22M 0B 0B 0B Y
T
0B 5.45M 24K 0B 48K Y
T
48K 4.63M 24K 0B 0B Y
T
0B 1.78M 24K 0B 48K Y
T
0B 8.03M 24K 0B 48K Y
T
0B 1.53M 24K 0B 0B Y
T
0B 2.19M 24K 0B 48K Y
T
192K 4.67M 24K 0B 0B Y
T
0B 2.7M 24K 0B 104K Y
T
0B 3.35M 24K 0B 144K Y
T

● The following example displays the size of all objects and subobjects owned by a specified user in a
specified dbspace in the database:

sp_iqdbspaceinfo iq_main,GROUPO

dbspace_name object_type owner object_name object_id id columns


iq_main table GROUPO Contacts 3538 732 288K
iq_main table GROUPO Customers 3515 731 240K
iq_main table GROUPO Departments 3632 738 72K
iq_main table GROUPO Employees 3641 739 408K
iq_main table GROUPO FinancialCodes 3612 736 72K
iq_main table GROUPO FinancialData 3621 737 96K
iq_main table GROUPO Products 3593 735 272K
iq_main table GROUPO SalesOrderItems 3580 734 120K
iq_main table GROUPO SalesOrders 3565 733 144K
indexes metadata primary_key unique_constraint foreign_key dbspace_online
is_dbspace_preallocate
0B 5.45M 24K 0B 48K Y
T
48K 4.63M 24K 0B 0B Y
T
0B 1.78M 24K 0B 48K Y
T
0B 8.03M 24K 0B 48K Y
T
0B 1.53M 24K 0B 0B
Y T
0B 2.19M 24K 0B 48K Y
T
192K 4.67M 24K 0B 0B Y
T
0B 2.7M 24K 0B 104K Y
T

SAP IQ SQL Reference


642 INTERNAL System Procedures
0B 3.35M 24K 0B 144K Y
T

● The following example displays the size of a specified object and its subobjects owned by a specified user
in a specified dbspace in the database:

sp_iqdbspaceinfo iq_main,GROUPO,Departments

Related Information

sp_iqindexinfo Procedure [page 676]


sp_iqdbspace Procedure [page 636]
sp_iqspaceinfo Procedure [page 760]
Determining the Security Model Used by a Database [page 576]

7.5.22 sp_iqdbspaceobjectinfo Procedure

Lists objects and subobjects of type table (including columns, indexes, metadata, primary keys, unique
constraints, foreign keys, and partitions) for a given dbspace. Not supported for RLV dbspaces.

 Syntax

sp_iqdbspaceobjectinfo [ <dbspace-name> ]
[ , <owner_name> ] [ , <object_name> ] [ , <object-type> ]

Parameters

dbspace-name

(Optional) If specified, sp_iqdbspaceobjectinfo displays output only for the specified dbspace.
Otherwise, it shows information for all dbspaces in the database.
owner_name

(Optional) Owner of the object. If specified, sp_iqdbspaceobjectinfo displays output only for tables
with the specified owner. If not specified, sp_iqdbspaceobjectinfo displays information for tables for
all users in the database.
object_name

(Optional) Name of the table. If not specified, sp_iqdbspaceobjectinfo displays information for all
tables in the database.
object-type

(Optional) Valid object types for table objects.

SAP IQ SQL Reference


System Procedures INTERNAL 643
Returns

Column Name Description

dbspace_name Name of the dbspace.

dbspace_id Identifier of the dbspace.

object_type Table.

owner Name of the owner of the object.

object_name Name of the table object on the dbspace.

object_id Global object ID of the object.

id Table ID of the object.

columns Number of table columns located on the given dbspace. If a column or one of the col­
umn-partitions is located on a dbspace, it is counted to be present on that dbspace.
The result is shown in the form n/N (n out of total N columns of the table are on the
given dbspace).

indexes Number of user-defined indexes on the table located on the given dbspace. Shown in
the form n/N (n out of total N indexes on the table are on the given dbspace). This
does not contain indexes, which are system-generated, such as FP indexes and HG in­
dexes in the case of unique constraints.

metadata

primary_key Boolean field (1/0) that denotes whether the primary key of the table, if any, is lo­
cated on this dbspace.Boolean field (Y/N) that denotes whether the metadata infor­
mation of the subobject is also located on this dbspace.

unique_constraint Number of unique constraints on the table that are located on the given dbspace. Ap­
pears in the form n/N (n out of total N unique constraints on the table are in the given
dbspace).

foreign_key Boolean fieldNumber of foreign_keys on the table that are located on the given
dbspace. Appears in the form n/N (n out of total N foreign keys on the table are in the
given dbspace).

partitions Number of partitions of the table that are located on the given dbspace. Appears in
the form n/N (n out of total N partitions of the table are in the given dbspace).

Remarks

All parameters are optional and any parameter may be supplied independent of the value of other parameters.

The sp_iqdbspaceobjectinfo stored procedure supports wildcard characters for interpreting


<dbspace_name>, <object_name>, and <owner_name>. It displays information for all dbspaces that match
the given pattern in the same way as the LIKE clause matches patterns inside queries.

The procedure returns no results if you specify an RLV dbspace.

For tables, sp_iqdbspaceobjectinfo displays summary information for all associated subobjects sorted by
dbspace_name, owner and object_name.

SAP IQ SQL Reference


644 INTERNAL System Procedures
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

These examples show objects in the iqdemo database to better illustrate output. iqdemo includes a sample
user dbspace named iq_main that may not be present in your own databases.

● The following example displays information about a specific dbspace in the database:

sp_iqdbspaceobjectinfo iq_main

dbspace_name dbspace_id object_type owner object_name object_id id colu


mns
iq_main 16387 table DBA emp1 3689 741 4/4
iq_main 16387 table DBA iq_dummy 3686 740 1/1
iq_main 16387 table DBA sale 3698 742 4/4
iq_main 16387 table GROUPO Contacts 3538 732 12/
12
iq_main 16387 table GROUPO Customers 3515 731 10/
10
iq_main 16387 table GROUPO Departments 3632 738 3/3
iq_main 16387 table GROUPO Employees 3641 739 21/
21
iq_main 16387 table GROUPO FinancialCodes 3612 736 3/3
iq_main 16387 table GROUPO FinancialData 3621 737 4/4
iq_main 16387 table GROUPO Products 3593 735 8/8
iq_main 16387 table GROUPO SalesOrderItems3580 734 5/5
iq_main 16387 table GROUPO SalesOrders 3565 733 6/6
indexes metadata primary_key unique_constraint foreign_key partitions
0/0 Y 0 0/0 0/0 0/0
0/0 Y 0 0/0 0/0 0/0
0/0 Y 0 0/0 0/0 0/0
0/0 Y 1 0/0 1/1 0/0
1/1 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 1/1 0/0
0/0 Y 1 0/0 1/1 0/0
0/0 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 1/1 0/0
4/4 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 2/2 0/0
0/0 Y 1 0/0 3/3 0/0

● The following example displays information about the objects owned by a specific user in a specific
dbspace in the database:

sp_iqdbspaceobjectinfo iq_main,GROUPO

SAP IQ SQL Reference


System Procedures INTERNAL 645
dbspace_name dbspace_id object_type owner object_name object_id id co
lumns
iq_main 16387 table GROUPO Contacts 3538 732 2/
12
iq_main 16387 table GROUPO Customers 3515 731 10
/10
iq_main 16387 table GROUPO Departments 3632 738 3/
3
iq_main 16387 table GROUPO Employees 3641 739 21
/21
iq_main 16387 table GROUPO FinancialCodes 3612 736 3/
3
iq_main 16387 table GROUPO FinancialData 3621 737 4/
4
iq_main 16387 table GROUPO Products 3593 735 8/
8
iq_main 16387 table GROUPO SalesOrderItems3580 734 5/
5
iq_main 16387 table GROUPO SalesOrders 3565 733 6/
6
indexes metadata primary_key unique_constraint foreign_key partitions
0/0 Y 1 0/0 1/1 0/0
1/1 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 1/1 0/0
0/0 Y 1 0/0 1/1 0/0
0/0 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 1/1 0/0
4/4 Y 1 0/0 0/0 0/0
0/0 Y 1 0/0 2/2 0/0
0/0 Y 1 0/0 3/3 0/0

● In this example, the commands move all tables on dbspace_x to dbspace_y:

SELECT 'ALTER TABLE ' || owner || '.' ||


object_name || ' MOVE TO dbspace_y;'
FROM sp_iqdbspaceobjectinfo()
WHERE object_type = 'table' AND
dbspace_name = 'dbspace_x';

The result are the following ALTER TABLE commands:

ALTER TABLE DBA.dt1 MOVE TO dbspace_y;


ALTER TABLE DBA.dt2 MOVE TO dbspace_y;
ALTER TABLE DBA.dt3 MOVE TO dbspace_y;

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.23 sp_iqdbstatistics Procedure


Reports results of the most recent sp_iqcheckdb.

 Syntax

sp_iqdbstatistics

SAP IQ SQL Reference


646 INTERNAL System Procedures
Remarks

Displays the database statistics collected by the most recent execution of sp_iqcheckdb.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

ALTER DATABASE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example shows the output from sp_iqdbstatistics. For this example, the most recent
execution of sp_iqcheckdb was the command sp_iqcheckdb 'allocation database':

DB Statistics Value Flags


=====================================|===========================|=====
DBCC Allocation Mode Report | |
=====================================|===========================|=====
** DBCC Status |Errors Detected |*****
DBCC Work units Dispatched |163 |
DBCC Work units Completed |163 |
=====================================|===========================|=====
Allocation Summary | |
=====================================|===========================|=====
Blocks Total |8192 |
Blocks in Current Version |4954 |
Blocks in All Versions |4954 |
Blocks in Use |4986 |
% Blocks in Use |60 |
** Blocks Leaked |32 |*****
| |
=====================================|===========================|=====
Allocation Statistics | |
=====================================|===========================|=====
Blocks Created in Current TXN |382 |
Blocks To Drop in Current TXN |382 |
Marked Logical Blocks |8064 |
Marked Physical Blocks |4954 |
Marked Pages |504 |
Blocks in Freelist |126553 |

SAP IQ SQL Reference


System Procedures INTERNAL 647
Imaginary Blocks |121567 |
Highest PBN in Use |5432 |
** 1st Unowned PBN |452 |*****
Total Free Blocks |3206 |
Usable Free Blocks |3125 |
% Free Space Fragmented |2 |
Max Blocks Per Page |16 |
1 Block Page Count |97 |
3 Block Page Count |153 |
4 Block Page Count |14 |
...
9 Block Hole Count |2 |
16 Block Hole Count |194 |
| |
Database Objects Checked |1 |
B-Array Count |1 |
Blockmap Identity Count |1 |
=====================================|===========================|=====
Connection Statistics | |
=====================================|===========================|=====

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.24 sp_iqdroplogin Procedure

Drops an SAP IQ user account.

 Syntax

Syntax 1

call sp_iqdroplogin ('<userid>')

Syntax 2

sp_iqdroplogin '<userid>'

Syntax 3

sp_iqdroplogin <userid>

Syntax 4

sp_iqdroplogin ('<userid>')

Parameters

userid

SAP IQ SQL Reference


648 INTERNAL System Procedures
ID of the user to drop.

Remarks

sp_iqdroplogin drops the specified user.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Example

These commands all remove the user rose:

sp_iqdroplogin 'rose'

sp_iqdroplogin rose

call sp_iqdroplogin ('rose')

Related Information

(Deprecated) sp_iqaddlogin Procedure [page 585]


Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 649
7.5.25 sp_iqemptyfile Procedure

Empties a dbfile and moves the objects in the dbfile to another available read-write dbfile in the same dbspace.
Not available for files in an RLV dbspace.

 Syntax

sp_iqemptyfile ( <logical-file-name> )

Parameters

logical-file-name

An identifier.

Remarks

sp_iqemptyfile empties a dbfile. The dbspace must be read-write before you can execute the
sp_iqemptyfile procedure. Dbfiles must be read-only before you can execute the sp_iqemptyfile
procedure.. The procedure moves the objects in the file to another available read-write dbfile in the same
dbspace. If there is no other read-write dbfile available, then SAP IQ displays an error message.

 Note

In a shared multiplex environment, you can run sp_iqemptyfile only on the coordinator. There must be
one read-write dbspace available for the procedure to succeed.

If the dbfile is in an RLV dbspace, then this error message displays:


Cannot empty files in an rlv store dbspace.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● BACKUP DATABASE System privileges GRANT System Privilege Statement [page 1511]
● SERVER OPERATOR
● ALTER DATABASE

As well as one of the following:

SAP IQ SQL Reference


650 INTERNAL System Procedures
Privilege Type Privilege Name Grant Statement

System privileges ● INSERT ANY TABLE GRANT System Privilege Statement [page 1511]
● UPDATE ANY TABLE
● DELETE ANY TABLE
● ALTER ANY TABLE
● LOAD ANY TABLE
● TRUNCATE ANY TABLE
● ALTER ANY OBJECT

Side Effects

None

Example

The following example empties dbfile das1:

sp_iqemptyfile ('das1')

object_name bytes_emptied EmptiedFileSizePct


--------------------------------------- ------------- ------------------
admin_mpx.lineitem 180224 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C10_FP 507904 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C11_FP 5365760 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C12_FP 5488640 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C13_FP 5332992 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C14_FP 1048576 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C15_FP 1384448 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C16_FP 129589248 12.0
admin_mpx.lineitem.ASIQ_IDX_T780_C1_FP 6316032 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C2_FP 15523840 1.0
admin_mpx.lineitem.ASIQ_IDX_T780_C3_FP 7536640 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C4_FP 1056768 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C5_FP 2662400 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C6_FP 16949248 1.0
admin_mpx.lineitem.ASIQ_IDX_T780_C7_FP 1859584 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C8_FP 1966080 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_C9_FP 843776 0.0
admin_mpx.lineitem.ASIQ_IDX_T780_I17_HG 29990912 2.0
admin_mpx.lineitem.big_l_orderkey_hg 30236672 2.0
admin_mpx.lineitem.big_l_partkey_hg 39034880 3.0
admin_mpx.lineitem.big_l_suppkey_hg 17547264 1.0
admin_mpx.orders 3473408 0.0
admin_mpx.orders.ASIQ_IDX_T781_C1_FP 12124160 1.0
admin_mpx.orders.ASIQ_IDX_T781_C2_FP 9175040 0.0
admin_mpx.orders.ASIQ_IDX_T781_C3_FP 892928 0.0
admin_mpx.orders.ASIQ_IDX_T781_C4_FP 21782528 2.0
admin_mpx.orders.ASIQ_IDX_T781_C5_FP 5496832 0.0
admin_mpx.orders.ASIQ_IDX_T781_C6_FP 1531904 0.0
admin_mpx.orders.ASIQ_IDX_T781_C7_FP 6307840 0.0
admin_mpx.orders.ASIQ_IDX_T781_C8_FP 262144 0.0
admin_mpx.orders.ASIQ_IDX_T781_C9_FP 239976448 22.0

SAP IQ SQL Reference


System Procedures INTERNAL 651
Related Information

Determining the Security Model Used by a Database [page 576]

7.5.26 sp_iqestdbspaces Procedure

Estimates the number and size of dbspaces needed for a given total index size.

 Syntax

sp_iqestdbspaces ( <db_size_in_bytes>, <iq_page_size>,


<min_#_of_bytes>, <max_#_of_bytes> )

Parameters

db_size_in_bytes

A DECIMAL(16) parameter that specifies the size of the database in bytes.


iq_page_size

A SMALLINT parameter that specifies the page size defined for the IQ segment of the database (must be a
power of 2 between 65536 and 524288; the default is 131072).
min_#_of_bytes

An INT parameter that specifies the minimum number of bytes per dbspace segment. The default is
20,000,000 (20 MB).
max_#_of_bytes

An INT parameter that specifies the maximum number of bytes per dbspace segment. The default is
2,146,304,000 (2.146 GB).

Remarks

sp_iqestdbspaces reports several recommendations, depending on how much of the data is unique:

● min – if there is little variation in data, you can choose to create only the dbspace segments of the sizes
recommended as min. These recommendations reflect the best possible compression on data with the
least possible variation.
● avg – if your data has an average amount of variation, create the dbspace segments recommended as
min, plus additional segments of the sizes recommended as avg.
● max – if your data has a high degree of variation (many unique values), create the dbspace segments
recommended as min, avg, and max.

SAP IQ SQL Reference


652 INTERNAL System Procedures
● spare – if you are uncertain about the number of unique values in your data, create the dbspace segments
recommended as min, avg, max, and spare. You can always delete unused segments after loading your
data, but creating too few can cost you some time.

Displays information about the number and size of dbspace segments based on the size of the database, the IQ
page size, and the range of bytes per dbspace segment. This procedure assumes that the database was
created with the default block size for the specified IQ page size; otherwise, the returned estimated values are
incorrect.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● MANAGE ANY DBSPACE System privileges GRANT System Privilege Statement [page 1511]
● ALTER DATABASE

Side Effects

None

Example

This following example estimates the size and number of dbspace segments needed for a 12 GB database:

sp_iqestdbspaces 12000000000, 65536, 500000000, 2146304000

dbspace files Type Size Msg

1 min 2146304000

2 min 2146304000

3 min 507392000

4 avg 2146304000

5 max 2053697536

6 spare 1200001024

SAP IQ SQL Reference


System Procedures INTERNAL 653
You should create a minimum of three segments (listed as min) for the best compression, if you expect little
uniqueness in the data. If the data has an average amount of variation, create one more segment (listed as
avg). Data with a lot of variation (many unique values, requiring extensive indexing), may require an additional
segment (listed as max). You can ensure that your initial load succeeds by creating a spare segment of
1200001024 bytes. Once you have loaded the database, you can delete any unused dbspace segments.

In this section:

Using sp_iqestdbspaces With Other System Stored Procedures [page 654]


You need to run two stored procedures to provide the <db_size_in_bytes> parameter needed by
sp_iqestdbspaces.

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.26.1 Using sp_iqestdbspaces With Other System Stored


Procedures

You need to run two stored procedures to provide the <db_size_in_bytes> parameter needed by
sp_iqestdbspaces.

Context

Results of sp_iqestdbspaces are only estimates, based on the average size of an index. The actual size
depends on the data stored in the tables, particularly on how much variation there is in the data.

SAP strongly recommends that you create the spare dbspace segments, because you can delete them later if
they are unused.

Procedure

1. Run sp_iqestjoin for all the table pairs you expect to join frequently.
2. Select one of the suggested index sizes for each pair of tables.
3. Total the index sizes you selected for all tables.
4. Run sp_iqestspace for all tables.
5. Total all of the RAW DATA index sizes returned by sp_iqestspace.
6. Add the total from step 3 to the total from step 5 to determine total index size.

SAP IQ SQL Reference


654 INTERNAL System Procedures
7. Use the total index size calculated in step 6 as the <db_size_in_bytes> parameter in
sp_iqestdbspaces.

7.5.27 sp_iqestspace Procedure

Estimates the amount of space needed to create an index based on the number of rows in the table.

 Syntax

sp_iqestspace ( <table_name>, <#_of_rows>, <iq_page_size> )

Parameters

table_name

A CHAR(256) parameter that specifies the name of the table


#_of_rows

An INT parameter that specifies the number of rows in the table


iq_page_size

A SMALLINT parameter that specifies the page size defined for the IQ segment of the database (must be a
power of 2 between 65536 and 524288; the default is 131072)

Remarks

Displays the amount of space that a database requires based on the number of rows in the underlying
database tables and on the database IQ page size. This procedure assumes that the database was created with
the default block size for the specified IQ page size (or else the estimate is incorrect).

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

SAP IQ SQL Reference


System Procedures INTERNAL 655
Privilege Name Privilege Type Grant Statement

● CREATE ANY INDEX System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY INDEX
● CREATE ANY OBJECT
● ALTER ANY OBJECT

Side Effects

None

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.28 sp_iqevent Procedure

Displays information about system and user-defined events.

 Syntax

sp_iqevent [ <event-name> ], [ <event-owner> ], [ <event-type> ]

Parameter

event-name

The name of the event.


event-owner

The owner of the event.


event-type

The type of event. Allowed values are:

● SYSTEM – displays information about system events (events owned by user SYS or dbo) only
● ALL – displays information about user and system events
● Any other value – displays information about user events

SAP IQ SQL Reference


656 INTERNAL System Procedures
Returns

Column Name Description

event_name The name of the event.

event_owner The owner of the event.

event_type For system events, the event type as listed in the SYSEVENTTYPE system table.

enabled Indicates whether or not the event is allowed to fire (Y/N).

action The event handler definition.

condition The WHERE condition used to control firing of the event handler.

location The location where the event is allowed to fire:

● C – consolidated
● R – remote
● A – all

remarks A comment string.

Remarks

The sp_iqevent procedure can be invoked without any parameters. If no parameters are specified, only
information about user events (events not owned by dbo or SYS) is displayed by default.

If you do not specify either of the first two parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example:sp_iqevent NULL, NULL, SYSTEM and
sp_iqevent NULL, user1.

The sp_iqevent stored event displays information about events in a database. If you specify one or more
parameters, the result is filtered by the specified parameters. For example, if <event-name> is specified, only
information about the specified event is displayed. If <event-owner> is specified, sp_iqevent only returns
information about events owned by the specified owner. If no parameters are specified, sp_iqevent displays
information about all the user events in the database.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 657
Examples

● The following example displays information about all user events in the database:

sp_iqevent

● The following example displays information about the user-defined event e1:

sp_iqevent e1
event_name event_owner event_type enabled action
e1 DBA (NULL) Y (NULL)
condition location remarks
(NULL) A (NULL)

● The following example displays information about all system events:

sp_iqevent NULL, NULL, SYSTEM


event_name event_owner event_type enabled action
ev_iqbegintxn dbo IQTLVAvailable Y begin call
dbo.sp_iqlog...
ev_iqmpxcompact dbo (NULL) N begin Declare
_Catalog...
condition location remarks
(NULL) A (NULL)
(NULL) A (NULL)

● In the following example, No rows returned, as the event non_existing_event does not exist:

sp_iqevent non_existing_event

● The following example displays information about all events owned by DBA:

sp_iqevent NULL, DBA

● The following example displays information about the event e1 owned by DBA:

sp_iqevent e1, DBA

● In the following example, ev_iqbegintxn is a system-defined event. If there is no user-defined event also
named ev_iqbegintxn, no rows are returned. (By default, only user-defined events are returned):

sp_iqevent ev_iqbegintxn

● In the following example, no rows returned, as the event ev_iqbegintxn is not a user event (by default
only user events returned):

sp_iqevent ev_iqbegintxn, dbo

● The following example displays information about all system events (owned by dbo or SYS):

sp_iqevent NULL, NULL, SYSTEM

● The following example displays information about the system event ev_iqbegintxn:

sp_iqevent ev_iqbegintxn, NULL, SYSTEM

● The following example displays information about the system event ev_iqbegintxn owned by dbo:

sp_iqevent ev_iqbegintxn, dbo, ALL

SAP IQ SQL Reference


658 INTERNAL System Procedures
Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.29 sp_iqfile Procedure

Displays detailed information about each dbfile in a dbspace.

 Syntax

sp_iqfile [ <dbspace-name> ]

Returns

Column Name Description

DBSpaceName The name of the dbspace as specified in the CREATE DBSPACE state­
ment. Dbspace names are always case-insensitive, regardless of the
CREATE DATABASE...CASE IGNORE or CASE RESPECT specifi-
cation.

DBFileName The logical file name.

Path The location of the physical file or raw partition.

SegmentType The type of dbspace:

● MAIN
● TEMPORARY
● RLV
● CACHE

RWMode The mode of the dbspace; always read-write (RW).

SAP IQ SQL Reference


System Procedures INTERNAL 659
Column Name Description

Online ● T – online. This is the online value of both the file's associated
dbspace and the file in SYS.ISYSIQDBFILE.
● F – offline.

Usage The percent of dbspace currently in use by this file in the dbspace. When
run against a secondary node in a multiplex configuration, this column
displays NA.

DBFileSize The current size of the file or raw partition. For a raw partition, this size
value can be less than the physical size.

Reserve Reserved space that can be added to this file in the dbspace.

StripeSize Always 1, if disk striping is on.

BlkTypes The space used by both user data and internal system structures.

FirstBlk The first IQ block number assigned to the file.

LastBlk The last IQ block number assigned to the file.

OkToDrop "Y" indicates the file can be dropped; otherwise "N".

MirrorLogicalFileName The logical filename of the primary DAS dbfile.

IsDASSharedFile ● "T" – the DAS dbfile is a shared file system file


● "F" – not a shared file system file

Remarks

sp_iqfile displays the usage, properties, and types of data in each dbfile in a dbspace. You can use this
information to determine whether data must be moved, and for data that has been moved, whether the old
versions have been deallocated.

The identifiers and block types are:

● A – Active Version
● B – Backup Structures
● C – Checkpoint Log
● D – Database Identity
● F – Free List
● G – Global Free List Manager
● H – Header Blocks of the Free List
● I – Index Advice Storage
● M – Multiplex CM. The multiplex commit identity block (actually 128 blocks) exists in all SAP IQ databases,
even though it is not used by SAP IQ databases.
● N – Column Use
● O – Old Version
● R – RLV Free List manager
● T – Table Use

SAP IQ SQL Reference


660 INTERNAL System Procedures
● U – Index Use
● X – Drop at Checkpoint

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBSPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example displays information about the files in the dbspaces:

sp_iqfile;

sp_iqfile;
DBSpaceName,DBFileName,Path,SegmentType,RWMode,Online,
Usage,DBFileSize,Reserve,StripeSize,BlkTypes,FirstBlk,
LastBlk,OkToDrop,servername,mirrorLogicalFileName,IsDASSharedFile
'IQ_SYSTEM_MAIN','IQ_SYSTEM_MAIN',
'../mpx_configdb.iq','MAIN','RW','T','24','700M','0B','1K',
'1H,17888F,32D,2498A,151O,198X,128M,32C',1,89600,'N',,'(NULL)','F'
'dbsp1','dbsp1','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb1','MAIN','RW','T','1','50M','0B','1K','1H',
1045440,1051839,'N',,'(NULL)','F'
'dbsp2','dbsp2','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb2','MAIN','RW','T','1','50M','0B','1K','1H',
2090880,2097279,'N',,'(NULL)','F'
'dbsp3','dbsp3','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb3','MAIN','RW','T','1','50M','0B','1K','1H',
3136320,3142719,'N',,'(NULL)','F'
'dbsp4','dbsp4','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb4','MAIN','RW','T','1','50M','0B','1K','1H',
4181760,4188159,'N',,'(NULL)','F'
'dbsp5','dbsp5','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb5','MAIN','RW','T','1','50M','0B','1K','1H',
5227200,5233599,'N',,'(NULL)','F'
'dbsp6','dbsp6','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb6','MAIN','RW','T','1','50M','0B','1K','1H',
6272640,6279039,'N',,'(NULL)','F'
'dbsp7','dbsp71','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb71','MAIN','RW','T','1','200M','0B','1K','1H',

SAP IQ SQL Reference


System Procedures INTERNAL 661
7318080,7343679,'Y',,'(NULL)','F'
'dbsp7','dbsp72','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb72','MAIN','RW','T','1','200M','0B','1K','1H',
8363520,8389119,'Y',,'(NULL)','F'
'dbsp7','dbsp73','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb73','MAIN','RW','T','1','200M','0B','1K','1H',
9408960,9434559,'Y',,'(NULL)','F'
'dbsp8','dbsp81','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb81','MAIN','RW','T','1','20M','0B','1K','1H',
10454400,10456959,'Y',,'(NULL)','F'
'dbsp8','dbsp82','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb82','MAIN','RW','T','1','20M','0B','1K','1H'
,11499840,11502399,'Y',,'(NULL)','F'
'dbsp8','dbsp83','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
mpx_configdb.iqdb83','MAIN','RW','T','1','20M','0B','1K','1H',
12545280,12547839,'Y',,'(NULL)','F'
'das62H2','dasP62H2','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
das62H2_1.iq','MAIN','RW','T','1','10M','0B','1K','1H',
13590720,13591999,'Y',
'user4_1927_nw45780','(NULL)','F'
'das62H2','dasM62H2','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
das62H2_3.iq','MAIN','RW','T','1','10M','0B','1K','1H',14636160,14637439,'Y',
'user4_1927_nw55880','dasP62H2','F'
'das62H2','dasM62H2_11','/lint12dev7/users/user4/machine.lint12dev_local/
mpxstore/
das62H2_33.iq','MAIN','RW','T','1','10M','0B','1K','1H',15681600,15682879,'Y',
'user4_1927_nw45780','dasP62H2','F'
'das62H2','dasM62H2_22','/lint12dev7/users/user4/machine.lint12dev_local/
mpxstore/
das62H2_44.iq','MAIN','RW','T','1','10M','0B','1K','1H',16727040,16728319,'Y',
'user4_1927_nw45780','dasP62H2','F'
'das62H2','dasP62H_55','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
das62H_55.iq','MAIN','RW','T','1','50M','0B','1K','1H',17772480,17778879,'Y',
'user4_1927_nw55880','(NULL)','F'
'das62H2','dasM62H_55','/lint12dev7/users/user4/machine.lint12dev_local/mpxstore/
das62M_55.iq','MAIN','RW','T','1','50M','0B','1K','1H',18817920,18824319,'Y',
'user4_1927_nw45780','dasP62H_55','F'
'sfs_dbs','f1','/shared_disk1/users/user4/dasfmpx/nw35095/
f1.iq','MAIN','RW','T','1','7.81M','0B','1K','1H',2090880,2091879,'Y',
'nw35095_dbsrv7915','(NULL)','T'
'sfs_dbs','f1_m','/local_disk1/users/user4/dasfmpx/nw411359/
f1_m.iq','MAIN','RW','T','1','7.81M','0B','1K','1H',2090880,2091879,'Y',
'nw411359_dbsrv7915','f1','F'
'sfs_dbs','f2','/shared_disk2/users/user4/dasfmpx/nw35095/
f2.iq','MAIN','RW','T','1','7.81M','0B','1K','1H',3136320,3137319,'Y',
'nw35095_dbsrv7915','(NULL)','T'
'sfs_dbs','f2_m','/local_disk2/users/user4/dasfmpx/nw411359/
f2_m.iq','MAIN','RW','T','1','7.81M','0B','1K','1H',3136320,3137319,'Y',
'nw411359_dbsrv7915','f2','F'
'IQ_SYSTEM_TEMP','IQ_SYSTEM_TEMP','nc110203mpx_configdb.iqtmp','TEMPORARY',
'RW','T','1','300M','0B','1K','1H,64F,48A',1,38400,'N',
'tbucken_1927_nc110203','(NULL)','F'

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


662 INTERNAL System Procedures
7.5.30 sp_iqhelp Procedure

Displays information about system and user-defined objects and data types.

 Syntax

sp_iqhelp [ <obj-name> ], [ <obj-owner> ], [ <obj-category> ], [ <obj-type> ]

Parameters

obj-name

The name of the object.


obj-owner

The owner of the object.


obj-category

(Optional) A parameter that specifies the category of the object.

Columns, constraints, and indexes are associated with tables and cannot be queried directly. When a table
is queried, the information about columns, indexes, and constraints associated with that table is displayed.

If the specified object category is not one of the allowed values, displays an Invalid object category
message.

Allowed values are:

● table – object is a base table


● view – object is a view
● procedure – object is a stored procedure or function
● event – object is an event
● datatype – object is a system or user-defined data type
obj-type

The type of object. Allowed values are:

● SYSTEM – displays information about system objects (objects owned by user SYS or dbo) only
● ALL – displays information about all objects. By default, only information about non-system objects is
displayed. If the specified object type is not SYSTEM or ALL, displays an Invalid object type
message.

The sp_iqhelp procedure can be invoked without any parameters. If no parameters are specified, sp_iqhelp
displays information about all independent objects in the database, that is, base tables, views, stored
procedures, functions, events, and data types.

SAP IQ SQL Reference


System Procedures INTERNAL 663
Remarks

If you do not specify any of the first three parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example, sp_iqhelp NULL, NULL, NULL, SYSTEM
and sp_iqhelp NULL, user1, "table".

Enclose the <obj-category> parameter in single or double quotes., except when NULL.

If sp_iqhelp does not find an object in the database that satisfies the specified description, displays a No
object found for the given description message.

The sp_iqhelp stored procedure displays information about system and user-defined objects and data types
in an IQ database. Objects supported by sp_iqhelp are tables, views, columns, indexes, constraints, stored
procedures, functions, events, and data types.

If you specify one or more parameters, the result is filtered by the specified parameters. For example, if <obj-
name> is specified, only information about the specified object is displayed. If <obj-owner> is specified,
sp_iqhelp returns information only about objects owned by the specified owner. If no parameters are
specified, sp_iqhelp displays summary information about all user-defined tables, views, procedures, events,
and data types in the database.

The sp_iqhelp procedure returns either summary or detailed information, depending on whether the
specified parameters match multiple objects or a single object. The output columns of sp_iqhelp are similar
to the columns displayed by the stored procedures sp_iqtable, sp_iqindex, sp_iqview, and
sp_iqconstraint.

When multiple objects match the specified sp_iqhelp parameters, sp_iqhelp displays summary
information about those objects. Object types and the columns displayed are:

● Base table – table_name, table_owner, server_type, location, table_constraints, remarks


● View – view_name, view_creator, view_def, server_type, location, remarks
● Stored procedure – proc_name, proc_creator, proc_defn, replicate, srvid, remarks
● Function – proc_name, proc_creator, proc_defn, replicate, remarks
● Event – event_name, event_creator, enabled, location, event_type, action, external_action, condition,
remarks
● System and user-defined data types – type_name, creator, nulls, width, scale, default, check

SAP IQ SQL Reference


664 INTERNAL System Procedures
When a single object matches the specified sp_iqhelp parameters, sp_iqhelp displays detailed information
about the object:

Object Type Description Columns

Table Displays information about ● Table columns: table_name, table_owner, server_type, location,
the specified base table, its table_constraints, remarks
columns, indexes, and con­ ● Column columns: column_name, domain_name, width, scale,
straints. nulls, default, check, pkey, user_type, cardinality, est_cardinality,
remarks
● Index columns: index_name, column_name, index_type,
unique_index, location, remarks
● Constraint columns: constraint_name (role), column_name, in­
dex_name, constraint_type, foreigntable_name, foreignta­
ble_owner, foreigncolumn_name, foreignindex_name, location

View Displays information about ● View columns: view_name, view_creator, view_def, server_type,
the specified view and its location, remarks
columns ● Column columns: column_name, domain_name, width, scale,
nulls, default, check, pkey, user_type, cardinality, est_cardinality,
remarks

Stored procedure Displays information about ● Procedure columns: proc_name, proc_creator, proc_defn, repli­
the specified procedure and cate, srvid, remarks
its parameters ● Parameter columns: parameter_name, type, width, scale, de­
fault, mode

Function Displays information about ● Function columns: proc_name, proc_creator, proc_defn, repli­
the specified function and its cate, srvid, remarks
parameters ● Parameter columns: parameter_name, type, width, scale, de­
fault, mode

Event Displays information about ● Event columns: event_name, event_creator, enabled, location,
the specified event event_type, action, external_action, condition, remarks

Data type Displays information about ● Data type columns: type_name, creator, nulls, width, scale, de­
the specified data type fault, check

 Note

Procedure definitions (proc-defn) of system procedures are encrypted and hidden from view.

For descriptions of the individual output columns, refer to the related stored procedure. For example, for a
description of the table column, see the sp_iqtable procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 665
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● The following example displays detailed information about the table sale:

sp_iqhelp sale

Table_name Table_owner Server_type Location dbspace_id isPartitioned


table_constraints
========== =========== ========== ======= == ======= =============
sale DBA IQ Main 16387 N
Remarks table_constraints
======= ================== (NULL) (NULL)
column_name domain_name width scale nulls default cardinality
========== =========== ===== ===== ===== ======= ===========
prod_id integer 4 0 Y (NULL) 0
month_num integer 4 0 Y (NULL) 0
rep_id integer 4 0 Y (NULL) 0
sales integer 4 0 Y (NULL) 0
est_cardinality isPartitioned remarks check
============== ============= ======= =====
0 N (NULL) (NULL)
0 N (NULL) (NULL)
0 N (NULL) (NULL)
0 N (NULL) (NULL)
index_name column_name index_type unique_index location
========== =========== =========== =========== ========
ASIQ_IDX_T463_C2_FP month_num FP N Main
ASIQ_IDX_T463_C1_FP prod_id FP N Main
ASIQ_IDX_T463_C3_FP rep_id FP N Main
ASIQ_IDX_T463_C4_FP sales FP N Main
remarks
=======
(NULL)
(NULL)
(NULL)
(NULL)

● The following example displays detailed information about the procedure sp_customer_list:

sp_iqhelp sp_customer_list
proc_name proc_owner proc_defn
========== =========== =========
sp_customer_list DBA create procedure DBA.sp_customer_list()
result(id integer company_name char(35))
begin
select id company_name from Customers

SAP IQ SQL Reference


666 INTERNAL System Procedures
end
replicate srvid remarks
========= ===== =======
N (NULL) (NULL)
parm_name parm_type parm_mode domain_name width scale
========= ========= ========= =========== ===== =====
id result out integer 4 0
company_name result out char 35 0
default
=======
(NULL)

● The following example displays summary information about all user-defined tables, views, procedures,
events, and data types in the database:

sp_iqhelp

● The following example displays information about table t1 owned by user u1 and the columns, indexes,
and constraints associated with t1:

sp_iqhelp t1, u1, "table"

● The following example displays information about view v1u1 and the columns associated with v1:

sp_iqhelp NULL, u1, "view"

● The following example displays information about the procedure sp2 and the parameters of owned by user
sp2:

sp_iqhelp sp2

● The following example displays information about the event e1:

sp_iqhelp e1

● The following example displays information about the data type dt1:

sp_iqhelp dt1

● The following example displays summary information about all system objects (owned by dbo or SYS):

sp_iqhelp NULL, NULL, NULL, SYSTEM

● The following examples all return the error message owned by user"Object 'non_existing_obj'
not found", as the object non_existing_obj does not exist:

sp_iqhelp non_existing_obj

sp_iqhelp NULL, non_existing_user

sp_iqhelp t1, NULL, "apple"

sp_iqhelp t1, NULL, NULL, "USER"

In this section:

sp_iqhelp Compatibility with SAP ASE [page 668]

SAP IQ SQL Reference


System Procedures INTERNAL 667
The SAP IQ sp_iqhelp stored procedure is similar to the SAP Adaptive Server Enterprise sp_help
procedure, which displays information about any database object listed in the SYSOBJECTS system
table and about system and user-defined data types.

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.30.1 sp_iqhelp Compatibility with SAP ASE

The SAP IQ sp_iqhelp stored procedure is similar to the SAP Adaptive Server Enterprise sp_help procedure,
which displays information about any database object listed in the SYSOBJECTS system table and about
system and user-defined data types.

SAP IQ has some architectural differences from SAP ASE in terms of types of objects supported and the
namespace of objects. In SAP ASE, all objects (tables, views, stored procedures, logs, rules, defaults, triggers,
check constraints, referential constraints, and temporary objects) are stored in the SYSOBJECTS system table
and are in the same namespace. The objects supported by SAP IQ (tables, views, stored procedures, events,
primary keys, and unique, check, and referential constraints) are stored in different system tables and are in
different namespaces. For example, in SAP IQ a table can have the same name as an event or a stored
procedure.

Because of the architectural differences between SAP IQ and SAP ASE, the types of objects supported by and
the syntax of SAP IQ sp_iqhelp are different from the supported objects and syntax of SAP ASE sp_help;
however, the type of information about database objects that is displayed by both stored procedures is similar.

SAP IQ SQL Reference


668 INTERNAL System Procedures
7.5.31 sp_iqindex and sp_iqindex_alt Procedures

Lists information about indexes.

 Syntax

Syntax 1

sp_iqindex ( [ <table_name> ],[ <column_name> ],[ <table_owner> ] )

Syntax 2

sp_iqindex [ table_name='<tablename>' ],
[ column_name='<columnname>' ],[ table_owner='<tableowner>' ]

Syntax 3

sp_iqindex_alt ( [ <table_name> ],[ <column_name> ],[ <table_owner> ] )

Syntax 4

sp_iqindex_alt [ table_name='<tablename>' ],
[ column_name='<columnname>' ],[ table_owner='<tableowner>' ]

Go to:

● Remarks
● Privileges
● Side Effects
● Examples

Returns

(back to top)

Column Name Description

table_name The name of the table

table_owner The owner of the table

column_name The name of the column; multiple names can appear in a multicolumn index

index_type The abbreviated index type (for example, HG, LF)

index_name The name of the index

unique_index 'U' indicates the index is a unique index; otherwise, 'N'

location TEMP = IQ temporary store, MAIN = IQ store, SYSTEM = catalog store

remarks User comments added with the COMMENT statement

SAP IQ SQL Reference


System Procedures INTERNAL 669
Remarks

(back to top)

Displays information about indexes in the database. Specifying one of the parameters returns the indexes from
only that table, column, or tables owned by the specified user. Specifying more than one parameter filters the
results by all of the parameters specified. Specifying no parameters returns all indexes for all tables in the
database.

sp_iqindex always produces one line per index. sp_iqindex_alt produces one line per index per column if
there is a multicolumn index.

Syntax 1

If you do not specify either of the first two parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example, sp_iqindex NULL,NULL,DBA and
sp_iqindex Departments,NULL,DBA.

Syntax 2

You can specify the parameters in any order. Enclose them in single quotes.

Syntax 3 and 4

Produces slightly different output when a multicolumn index is present. Allows the same options as Syntax 1
and 2.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

(back to top)

None

Examples

(back to top)

SAP IQ SQL Reference


670 INTERNAL System Procedures
● The following variations in syntax both return all indexes on columns with the name DepartmentID:

call sp_iqindex (NULL,'DepartmentID')

sp_iqindex column_name='DepartmentID'

table_ name table_ owner column_ name index_ type

Departments GROUPO DepartmentID FP

Departments GROUPO DepartmentID HG

Employees GROUPO DepartmentID FP

(Continued)

index_name unique_ index location dbspace_id remarks

ASIQ_IDX_T201_C1_FP N Main 16387 (NULL)

ASIQ_IDX_T201_C1_HG U Main 16387 (NULL)

ASIQ_IDX_T202_C5_FP N Main 16387 (NULL)

● The following variations in syntax both return all indexes in the table Departments that is owned by table
owner GROUPO:

sp_iqindex Departments,NULL,GROUPO

sp_iqindex table_name='Departments',table_owner='DBA'

table_ name table_ owner column_ name index_ type

Departments GROUPO DepartmentHeadID FP

Departments GROUPO DepartmentID FP

Departments GROUPO DepartmentID HG

Departments GROUPO DepartmentName FP

(Continued)

index_name unique_ index location dbspace_id remarks

ASIQ_IDX_T201_C3_FP N Main 16387 (NULL)

ASIQ_IDX_T201_C1_FP N Main 16387 (NULL)

ASIQ_IDX_T201_C1_HG U Main 16387 (NULL)

ASIQ_IDX_T201_C2_FP N Main 16387 (NULL)

● The following variations in syntax for sp_iqindex_alt both return indexes on the table Employees that
contain the column City. The index emp_loc is a multicolumn index on the columns City and State.
sp_iqindex_alt displays one row per column for a multicolumn index:

sp_iqindex_alt Employees,City

SAP IQ SQL Reference


System Procedures INTERNAL 671
sp_iqindex_alt table_name='Employees',
column_name='City'

table_ name table_ owner column_ name index_ type

Employees GROUPO City FP

Employees GROUPO City HG

Employees GROUPO State HG

(Continued)

index_name unique_ index dbspace_id remarks

ASIQ_IDX_T452_C7_FP N 16387 (NULL)

emp_loc N 16387 (NULL)

emp_loc N 16387 (NULL)

● The output from sp_iqindex for the same table and column is slightly different:

sp_iqindex Employees,City

sp_iqindex table_name='Employee',column_name='City'

table_ name table_ owner column_ name index_ type

Employees GROUPO City FP

Employees GROUPO City,State HG

(Continued)

index_name unique_ index dbspace_id location remarks

ASIQ_IDX_T452_C7_FP N 16387 Main (NULL)

emp_loc N 16387 Main (NULL)

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]

SAP IQ SQL Reference


672 INTERNAL System Procedures
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.32 sp_iqindexadvice Procedure

Displays stored index advice messages. Optionally clears advice storage.

 Syntax

sp_iqindexadvice ( [ <resetflag> ] )

Parameters

resetflag

Lets the caller clear the index advice storage. If <resetflag> is nonzero, all advice is removed after the
last row has been retrieved.

Remarks

Allows users to query aggregated index advisor messages using SQL. Information can be used to help decide
which indexes or schema changes will affect the most queries.

INDEX_ADVISOR columns are:

● Advice – unique advice message


● NInst – number of instances of message
● LastDT – last date/time advice was generated

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● ALTER ANY INDEX System privilege GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT

SAP IQ SQL Reference


System Procedures INTERNAL 673
Side Effects

None

Example

The following shows sample output from the sp_iqindexadvice procedure:

Advice NInst LastDT

Add a CMP index on DBA.tb (c2, c3) Predicate: (tb.c2 = 2073 2009-04-07 16:37:31.000
tb.c3)

Convert HG index on DBA.tb.c4 to a unique HG 812 2009-04-06 10:01:15.000

Join Key Columns DBA.ta.c1 and DBA.tb.c1 have mis­ 911 2009-02-25 20:59:01.000
matched data types

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

7.5.33 sp_iqindexfragmentation Procedure

Reports information about the percentage of page space taken up within the B-trees, garrays, and bitmap
structures in SAP IQ indexes.

 Syntax

dbo.sp_iqindexfragmentation ( '<target>' )

'<target>' ::=
table <table-name> | index <index-name> [...]

SAP IQ SQL Reference


674 INTERNAL System Procedures
Parameter

table-name

Target table <table-name> reports on all nondefault indexes in the named table.
index-name

Target index <index-name> reports on the named index. Each <index-name> is a qualified index name.
You can specify multiple indexes within the table, but you must repeat the index keyword with each index
specified.

Remarks

For garrays, the fill percentage calculation does not take into account the reserved space within the garray
groups, which is controlled by the GARRAY_FILL_FACTOR_PERCENT option.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBASPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

Reports the internal index fragmentation for the unique HG index DBA.prop_nu.prop_nu_a table:

Index IndexType Btree_Node_pages GARRAY_FILL_FAC­


TOR_PERCENT

DBA.prop_nu.prop_nu_a HG 8 25

SQLCODE: 0

SAP IQ SQL Reference


System Procedures INTERNAL 675
Index IndexType Btree_Node_pages GARRAY_FILL_FAC­
TOR_PERCENT

Fill Percent btree pages garray pages bitmap pages

0-10% 13 2 8

11-20% 1 8 0

21-30% 0 4 0

31-40% 3 20 0

41-50% 4 116 0

51-60% 6 4 0

61-70% 3 3 0

71-80% 4 1 0

81-90% 1 1 0

91-100% 192 276 0

 Note

All percentages are truncated to the nearest percentage point. HG indexes also display the value of option
GARRAY_FILL_FACTOR_PERCENT. Index types that use a B-tree also display the number of node (nonleaf)
pages. These are HG, WD, DATE, and DTTM.

If an error occurs during execution of this stored procedure, the SQLCODE would be nonzero.

Related Information

sp_iqindexmetadata Procedure [page 679]


sp_iqindexinfo Procedure [page 676]
sp_iqindexsize Procedure [page 685]
sp_iqrebuildindex Procedure [page 737]
sp_iqrowdensity Procedure [page 752]
Determining the Security Model Used by a Database [page 576]

7.5.34 sp_iqindexinfo Procedure

Displays the number of blocks used per index per main dbspace for a given object. If the object resides on
several dbspaces, sp_iqindexinfo returns the space used in all dbspaces, as shown in the example.

 Syntax

sp_iqindexinfo '{ database | [ table <table-name> | index <index-name> ]


[...] }

SAP IQ SQL Reference


676 INTERNAL System Procedures
[ resources <resource-percent> ]'

Parameters

table-name

The name of the table.

index-name

The name of the index.

resource-percent

The resources percentage allows you to limit the CPU utilization of the sp_iqindexinfo procedure by
specifying the percent of total CPUs to use. <resource-percent> must be an integer greater than 0.

Returns

Column Name Description

Object Table or index name.

Dbspace_name Name of the dbspace.

ObjSize Size of data for this object on this dbspace.

DBSpPct Percent of dbspace used by this object.

MinBlk First block used by this object on this dbspace.

MaxBlk Last block used by this object on this dbspace; useful for determining which objects must be relo­
cated before the dbspace is resized to a smaller size.

Remarks

You can request index information for the entire database, or you can specify any number of table or index
parameters. If a table name is specified, sp_iqindexinfo returns information on all indexes in the table. If an
index name is specified, only the information on that index is returned.

If the specified <table-name> or <index-name> is ambiguous or the object cannot be found, an error is
returned.

By default in a multiplex database, sp_iqindexinfo displays information about the shared IQ store on a
secondary node. If individual tables or indexes are specified, the store to display is automatically selected.

sp_iqindexinfo shows the DBA on which dbspaces a given object resides. The DBA can use this information
to determine which dbspaces must be given relocate mode to relocate the object.

SAP IQ SQL Reference


System Procedures INTERNAL 677
The results of sp_iqindexinfo are from the point of view of the version seen by the transaction running the
command. Blocks used by other versions are not shown. shows the DBA on which dbspaces a given object
resides. The DBA can use this information to determine which dbspaces must be given

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBSPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

shows the DBA on which dbspaces a given object resides.Displays information about indexes in the
Departments table:

sp_iqindexinfo 'table GROUPO.Departments';

Object DbspaceName ObjSize DBSpPct MinBlk MaxBlk

GROUPO.Depart­ iq_main 288 K 1 1,045,496.00 1,048,891.00


ments

GROUPO.Depart­ iq_main 176 K 1 1,047,197.00 1,047,328.00


ments.ASIQ_IDX_
T779_C1_FP

GROUPO.Depart­ iq_main 160 K 1 1,047,213.00 1,047,324.00


ments.ASIQ_IDX_
T779_C2_FP

GROUPO.Depart­ iq_main 184 K 1 1,047,229.00 1,047,317.00


ments.ASIQ_IDX_
T779_C3_FP

GROUPO.Depart­ iq_main 440 K 1 1,048,421.00 1,048,796.00


ments.ASIQ_IDX_
T779_C3_HG

SAP IQ SQL Reference


678 INTERNAL System Procedures
Object DbspaceName ObjSize DBSpPct MinBlk MaxBlk

GROUPO.Depart­ iq_main 288 K 1 1,047,261.00 1,047,306.00


ments.ASIQ_IDX_
T779_I4_HG

Related Information

sp_iqdbspace Procedure [page 636]


sp_iqdbspaceinfo Procedure [page 639]
sp_iqspaceinfo Procedure [page 760]
sp_iqindexmetadata Procedure [page 679]
sp_iqindexfragmentation Procedure [page 674]
sp_iqindexsize Procedure [page 685]
Determining the Security Model Used by a Database [page 576]

7.5.35 sp_iqindexmetadata Procedure

Displays index metadata for a given index.

 Syntax

dbo.sp_iqindexmetadata '<index-name>'
[ , '<table-name>' [ , '<owner-name>' ] ]

Parameter

index-name

For all indexes except FP, use the text name defined for the index. For FP indexes, use the name of the index
as defined in the iname column of the sysindex table. Run SELECT * FROM SYS.SYSINDEXES WHERE
TNAME=<table_name> to display the value.

Remarks

You can optionally restrict the output to only those indexes on a specified table, and to only those indexes
belonging to a specified owner.

SAP IQ SQL Reference


System Procedures INTERNAL 679
Specifying a table name limits output to those indexes belonging to that table. Specifying an owner name limits
output to indexes owned by that owner. Omitted parameters default to NULL. You can specify only one index
per procedure.

User supplier IQ UNIQUE value for the column is available through sp_iqindexmetadata. It reports exact
cardinality if Unique HG are present. It reports 0 as cardinality if (only) non-unique HG is present.

The first row of output for all index types is the owner name, table name, and index name for the index.
Additional output is index type specific.

Index Type Metadata Returned

CMP, DATE, DTTM, TIME Type, Version

FP Type, Style, Version, DBType, Maximum Width, EstUnique, TokenCount, NBit, CountSize,
DictSize, CountLen, MaxKeyToken, MinKey Token, MinCount, MaxCount, DistinctKey, BAr­
ray Version, RidMap Version, IQ Unique

HG Type, Version, Maintains Exact Distinct, Level 0 Threshold, Force Physical Delete, Maximum
Level Count, Tier ratio, Auto sizing, Average Load Size (records), Active Subindex count,
Cardinality Range Min - Max, Estimated Cardinality, Accuracy of Cardinality

HNG Type, Version, BitsPerBlockmap, NumberOfBits

LF Type, Version, IndexStatus, NumberOfBlockmaps, BitsPerBlockmap, Distinct Keys

WD Type, Version, KeySize, Delimiters, DelimiterCount, MaxKeyWordLength, PermitEmptyWord

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● ALTER ANY INDEX System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT

REFERENCES privilege on Object-level privilege GRANT Object-Level Privilege Statement [page 1502]
the table

Side Effects

None

SAP IQ SQL Reference


680 INTERNAL System Procedures
Example

This example determines the name of the FP index for column C1 on table table1 and then displays the
metadata of the index. First, determine the iname value for the FP index.

SELECT * FROM SYS.SYSINDEXES WHERE tname='table1'

icreator iname fname creator tname

dbo table1 IQ_SYSTEM_MAIN dbo table1

dbo ASIQ_ID_T1707_C1_FP IQ_SYSTEM_MAIN dbo table1

dbo ASIQ_ID_T1707_C2_FP IQ_SYSTEM_MAIN dbo table1

dbo ASIQ_ID_T1707_C3_FP IQ_SYSTEM_MAIN dbo table1

dbo ASIQ_ID_T1707_I4_HG IQ_SYSTEM_MAIN dbo table1

Then, display the metadata for the FP index on the table.

 Sample Code

sp_iqindexmetadata 'ASIQ_IDX_T1707_C1_FP','table1','dbo'

Value1 Value2 Value3

dbo table1 ASIQ_IDX_T1707_C1_FP

–––––––––––––––––––-- –––––––––––––––––––-- –––––––––––––––––––--

Type FP

Style NBit FP

Version 4

DBType 11

Maximum Width 0

EstUnique 0

TokenCount 0

NBit 1

CountSize 0

DictSize 0

CountLen 4

MaxKey Token 0

MinKey Token 0

MinCount 0

MaxCount 0

DistinctKey 0

SAP IQ SQL Reference


System Procedures INTERNAL 681
Value1 Value2 Value3

BArray Version 2

RidMap Version 1

IQ Unique 0

=======================... =======================... =======================...

This example displays the metadata for the non high group index nonhg on column C1 on table table1.

 Sample Code

sp_iqindexmetadata 'nonhg','table1','dbo'

Value1 Value2 Value3

DBA table1 nonhg

Type HG

Version 3

Maintains Exact Distinct No

Level 0 Threshold 3000000

Force Physical Delete Yes

Maximum Level Count 10

Tier ratio 30

Auto sizing On

Avarage Load Size (records) 58622

Active Subindex count 3

Cardinality Range Min - Max 5-5

Estimated Cardinality 5

Accuracy of Cardinality 100

Level: 0 Main Index Total Row Count 1

Level: 0 Main Index Deleted Row Count 0

Level: 0 Main Index # of Btree Pages in Main btree 1

Level: 0 Main Index # of Garray Pages 1

Level: 0 Main Index # of Keys in Main Btree 1

Level: 0 Main Index # of Keys Probed in Btree 0

Level: 0 Main Index # of Keys Found Duplicate in Btree 0

Level: 0 Main Index # of Keys Possible Distinct in Btree 0

Level: 1 Main Index Total Row Count 3145747

Level: 1 Main Index Deleted Row Count 0

SAP IQ SQL Reference


682 INTERNAL System Procedures
Value1 Value2 Value3

Level: 1 Main Index # of Btree Pages in Main btree 1

Level: 1 Main Index # of Btree Pages in Conjugate btree 1

Level: 1 Main Index # of Garray Pages 2

Level: 1 Main Index # of Keys in Main Btree 8

Level: 1 Main Index # of Keys in Conjugate Btree 3

Level: 1 Main Index # rows in Conjugate Btree 2949127

Level: 1 Main Index # of Keys Probed in Btree 0

Level: 1 Main Index # of Keys Found Duplicate in Btree 0

Level: 1 Main Index # of Keys Possible Distinct in Btree 0

Level: 1 Incremental Index Total Row Count 1

Level: 1 Incremental Index Deleted Row Count 0

Level: 1 Incremental Index # of Btree Pages 1

Level: 1 Incremental Index # of Garray Pages 1

Level: 1 Incremental Index #of Keys in Btree 1

Level: 1 Incremental Index # of Keys Probed in Btree 0

Level: 1 Incremental Index # of Keys Found Duplicate in Btree 0

Level: 1 Incremental Index # of Keys Possible Distinct in Btree 0

Related Information

sp_iqindexfragmentation Procedure [page 674]


sp_iqindexinfo Procedure [page 676]
sp_iqindexsize Procedure [page 685]
Determining the Security Model Used by a Database [page 576]

7.5.36 sp_iqindexrebuildwidedata Procedure

Identifies wide columns in migrated databases that you must rebuild before they are available for read/write
activities.

 Syntax

sp_iqindexrebuildwidedata [<table.name>]

SAP IQ SQL Reference


System Procedures INTERNAL 683
Parameters

table.name

Include the optional <table.name> parameter to generate a list of wide columns for that table. Omit the
<table.name> parameter to generate a list of wide columns for all tables in the database.

Remarks

CHAR, VARCHAR, BINARY, and VARBINARY columns wider than 255 characters, as well as all LONG VARCHAR
and LONG BINARY columns in databases migrated to SAP IQ 16.1 must be rebuilt before the database engine
can perform read/write activities on them. sp_iqindexrebuildwidedata identifies these columns and
generates a list of statements that you can use to rebuild the columns with the sp_iqrebuildindex
procedure.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

INSERT ANY TABLE System privilege GRANT System Privilege Statement [page 1511]

INSERT privilege on the table Object-level privilege GRANT Object-Level Privilege Statement [page 1502]

Side Effects

None

Example

This example generates wide-column rebuild statements for table T2:

sp_iqindexrebuildwidedata T2

Owner Table Column Domain Width IndexType sp_iqrebuild


DBA T2 C1 char 1020 Long varchar FP sp_iqrebuildindex '"DBA.T2"' 'column "C1" 0';

SAP IQ SQL Reference


684 INTERNAL System Procedures
Related Information

sp_iqrebuildindex Procedure [page 737]

7.5.37 sp_iqindexsize Procedure

Gives the size of the specified index.

 Syntax

sp_iqindexsize [ [ <owner>.] <table>.] <index_name>

Returns

Column Name Description

Username Index owner.

Indexname Index for which results are returned, including the table name.

Type Index type.

Info Component of the IQ index for which the KBytes, Pages, and Compressed Pages are being re­
ported. The components vary by index type. For example, the default (FP) index includes BARRAY
(barray) and Bitmap (bm) components.

KBytes Physical object size in KB.

Pages Number of IQ pages needed to hold the object in memory.

Compressed Number of IQ pages when the object is compressed (on disk).


Pages

Remarks

Returns the total size of the index in bytes and kilobytes, and an Info column that describes the component of
the IQ index for which the KBytes, Pages, and Compressed Pages are reported. The components described
vary by index type. For example, the default (FP) index includes BARRAY (barray) and Bitmap (bm)
components.

Also returns the number of pages required to hold the object in memory and the number of IQ pages when the
index is compressed (on disk).

You must specify the <index_name> parameter with this procedure. To restrict results to this index name in a
single table, include <owner.table.> when specifying the index.

SAP IQ SQL Reference


System Procedures INTERNAL 685
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● ALTER ANY TABLE System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY INDEX

Side Effects

None

Example

sp_iqindexsize ASIQ_IDX_T780_I4_HG

Username Indexname Type Info Kbytes Pages Compressed Pa­


ges

GROUPO GROUPO.Depart­ HG Total 288 4 2


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG vdo 0 0 0


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG bt 152 2 1


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG garray 0 0 0


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG bm 136 2 1


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG barray 0 0 0


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG dpstore 0 0 0


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG largelob 0 0 0


ments.ASIQ_IDX_T780_I4_HG

GROUPO GROUPO.Depart­ HG txtPst 0 0 0


ments.ASIQ_IDX_T780_I4_HG

CREATE TEXT INDEX ti ON Employees( Street ) IMMEDIATE REFRESH;sp_iqindexsize


'ti';

SAP IQ SQL Reference


686 INTERNAL System Procedures
Compressed
Username Indexname Type Info KBytes Pages Pages

GROUPO GROUPO.Employees.ti TEXT Total 896 12 6

GROUPO GROUPO.Employees.ti TEXT vdo 0 0 0

GROUPO GROUPO.Employees.ti TEXT bt 304 4 2

GROUPO GROUPO.Employees.ti TEXT garray 152 2 1

GROUPO GROUPO.Employees.ti TEXT bm 136 2 1

GROUPO GROUPO.Employees.ti TEXT barray 152 2 1

GROUPO GROUPO.Employees.ti TEXT dpstore 0 0 0

GROUPO GROUPO.Employees.ti TEXT largelob 0 0 0

GROUPO GROUPO.Employees.ti TEXT txtPst 304 4 2

Related Information

sp_iqindexmetadata Procedure [page 679]


sp_iqindexfragmentation Procedure [page 674]
sp_iqindexinfo Procedure [page 676]
Determining the Security Model Used by a Database [page 576]

7.5.38 sp_iqindexuse Procedure

Reports detailed usage information for secondary (non-FP) indexes accessed by the workload.

 Syntax

sp_iqindexuse

Returns

Column Name Description

IndexName Index name

TableName Table name

Owner User name of index owner

UID Index unique identifier. UID is a number assigned by the system that uniquely identifies the in­
stance of the index (where instance is defined when an object is created).

SAP IQ SQL Reference


System Procedures INTERNAL 687
Column Name Description

Type Index type

LastDT Date/time of last access

NOpt Number of metadata or uniqueness accesses

NQry Number of query accesses

NConstraint Number of accesses for unique or referential integrity checks

Remarks

Each secondary index accessed by the workload displays a row. Indexes that have not been accessed do not
appear. Index usage is broken down by optimizer, constraint, and query usage.

Indexes from tables created in SYSTEM are not reported.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following shows sample output from the sp_iqindexuse procedure:

IndexName TableName Owner UID Type LastDT NOpt NQry NConstr


aint
n_nationkey_hg nation DBA 29 HG 20070917 22:08:06~ 12 0 12
n_regionkey_hg nation DBA 31 HG 20070917 22:08:06~ 12 0 0
r_regionkey_hg region DBA 47 HG 20070917 22:08:06~ 12 0 12
s_suppkey_hg supplier DBA 64 HG 20070917 22:08:06~ 12 0 12
p_partkey_hg part DBA 87 HG 20070917 22:08:06~ 6 0 6
s_suppkey_hg supplier DBA 64 HG 20070917 22:08:06~ 12 0 12

SAP IQ SQL Reference


688 INTERNAL System Procedures
...

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

7.5.39 sp_iqlmconfig Procedure

Controls license management configuration, properties, and authorizations.

 Syntax

sp_iqlmconfig
[ { 'allow' | 'disallow' } , {
'ALL'
| '<specific_license_name>'
| 'IQ_VLDBMGMT' , '<quantity>' } ]
| [ 'edition' [, <edition_type> ]]
| [ 'license type' [, <license_type_name> ]]
| [ 'smtp host' [, <smtp_host_name> ]]
| [ 'smtp port' [, <smtp_port_number> ]]
| [ 'email sender' [, <sender_email_address> ]]
| [ 'email recipients' [, <email_recipients> ]]
| [ 'email severity' [, <email_severity> ]] ]

Parameters

'allow' | 'disallow'

Enables or disables optional licenses:

sp_iqlmconfig 'allow', 'ALL' // enable all, except IQ_VLDBMGT


sp_iqlmconfig 'disallow', 'IQ_SECURITY' // disable IQ_SECURITY

The ALL keyword enables or disables all optional licenses, except IQ_VLDBMGMT. To enable or disable a
specific license, specify the license by name.

SAP IQ SQL Reference


System Procedures INTERNAL 689
Use the IQ_VLDBMGMT and <quantity> parameters to change the number of available IQ_VLDBMGT
licenses:

sp_iqlmconfig 'allow', 'IQ_VLDBMGMT' , '8' // increase by 8


sp_iqlmconfig 'disallow', 'IQ_VLDBMGMT' // sets the quantity to 0

<quantity> is an integer value from 0 to 4294967295 that sets the number of available IQ_VLDBMGMT
licenses.

 Note

The disallow parameter can only disable an unlicensed option if the option is not in use. If the server
checks out an unlicensed option, the option cannot be unauthorized and the server may fall into grace
mode.

specific_license_name

A specific license. To allow or disallow a specific license, specify the license by name:

● 'IQ_CORE'
● 'IQ_LOB'
● 'IQ_VLDBMGMT'
● 'IQ_SECURITY'
● 'IQ_MPXNODE'
● 'IQ_UDF'
● 'IQ_IDA'
● 'IQ_UDA'
edition, edition_type

The edition. The value for <edition_type> is 'EE' (Enterprise Edition).


license type, license_type_name

The current license type. The valid values for <license_type_name> are:

● 'CH' (CPU License Chip)


● 'DH' (Development and Testing License Chip)
● 'DT' (Development and Testing)
● 'EV' (Evaluation)
● 'SF' (Standby CPU License)
● 'SH' (Standby CPU License Chip)
smtp host, smtp host name

The SMTP host used to send e-mail for license event notifications.
smtp port, smtp port number

The SMTP port used to send e-mail for license event notifications.
email sender, sender email address

The e-mail address used as the sender's address on license event email notifications.
email recipients, email recipients

A comma-separated list of e-mail recipients who receive license event email notifications.
email severity, email severity

SAP IQ SQL Reference


690 INTERNAL System Procedures
The minimum severity of an error that causes an e-mail notification to be sent. The default is ERROR, and
the other possibilities are warning and informational. Values:

● 'ERROR' (default)
● 'WARNING'
● 'INFORMATIONAL'
● 'NONE'

Remarks

Executing sp_iqlmconfig without parameters displays current license information.

At startup, sp_iqlmconfig checks the edition type and license type. If a specified license is not found, the
server falls to grace mode. A specified license type becomes valid only when you specify a non-null edition
value.

Using an unlicensed option on a licensed server can throw the server into grace mode, which can cause the
server to shutdown when the grace period expires. The database administrator must explicitly "allow" access
to an optionally licensed feature, or the feature will not be available:

● You see the following message when you try to use an "unauthorized" optional feature:
Authorization required to attempt checkout
<specific_license_name> license.
● You see the following message when you try to create a dbspace that increases the IQ main store size
beyond the "authorized" size:
Insufficient quantity authorization
available for IQ_VLDBMGMT license.

The DBA can "disallow" any unused optional feature, but once a feature is in use and the license is checked out,
revoking access to that feature is no longer possible. Authorizing an IQ_MPXNODE optional license is not
required. For multiplex, authorization is required only on one node (any one), and is propagated to all other
nodes and enforced everywhere.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

SERVER OPERATOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 691
Examples

● The following example displays the current license configuration:

sp_iqlmconfig // execute sp_iqlmconfig without


parameters displays
//
current license properties and values
//
sample output below
Property Value
-----------------------------------------------------
Edition EE
License Type DT
Application Type IQ
IQ_CORE License Count in use 2 (CPU core based)
Optional license in use : IQ_UDA No
Optional license in use : IQ_LOB No
Optional license in use: IQ_SECURITY No
Optional license in use: IQ_MPXNODE No
Optional license in use: IQ_VLDBMGMT No
IQ_VLDBMGMT License Count in use 0
Optional license in use: IQ_UDF No
Optional license in use: IQ_IDA No
Optional license in use: IQ_URIDA No
Optional license in use: IQ_TS_FSF No
Email Severity NONE
SMTP Host smtp
SMTP Port 25
Email Sender
Email Recipients

● The following example configures licenses:

sp_iqlmconfig 'edition', 'EE' // configure enterprise edition


sp_iqlmconfig 'license type', 'DT' // configure DT license

● The following example enables optional features:

sp_iqlmconfig 'allow', 'ALL' // enable all, except IQ_VLDBMGMT


sp_iqlmconfig 'allow', 'IQ_SECURITY' // enable IQ_SECURITY license

● The following example disables optional features:

sp_iqlmconfig 'disallow', 'ALL' // disable all except IQ_VLDBMGMT


sp_iqlmconfig 'disallow', 'IQ_SECURITY' // disable IQ_SECURITY license
sp_iqlmconfig 'disallow', 'IQ_VLDBMGMT' // disable IQ_VLDBMGMT license

● The following example changes the number of IQ_VLDBMGT licenses:

sp_iqlmconfig 'allow', 'IQ_VLDBMGMT', '8' // increase to 8


sp_iqlmconfig 'disallow', 'IQ_VLDBMGMT', '2' // reduce by 2

● The following example configures email notifications:

sp_iqlmconfig 'smtp host', 'smtp' // set the smtp host to 'smtp'


sp_iqlmconfig smtp port, '25' // set the smtp port number to
'25'
sp_iqlmconfig ’email severity’, ’ERROR’ // set the email severity
alert to 'error'

SAP IQ SQL Reference


692 INTERNAL System Procedures
Related Information

Properties Available for the Server [page 213]


Determining the Security Model Used by a Database [page 576]

7.5.40 sp_iqlocks Procedure

Shows information about locks in the database, for both the IQ main store and the IQ catalog store.

 Syntax

sp_iqlocks ( [ <connection>,] [ [ <owner>.]<table_name>,]


<max_locks>,] [ <sort_order> ] )

Parameter

All parameters are optional to restrict results:

connection

(Optional) An INTEGER parameter that specifies the connection ID. With this option, the procedure returns
information about locks for the specified connection only. Default is zero, which returns information about
all connections.
owner.table_name

(Optional) A CHAR(128) parameter that specifies the table name. With this option, the procedure returns
information about locks for the specified table only. Default is NULL, which returns information about all
tables in the database. If you do not specify owner, it is assumed that the caller of the procedure owns the
table.
max_locks

(Optional) An INTEGER parameter that specifies the maximum number of locks for which to return
information. Default is 0, which returns all lock information.
sort_order

(Optional) A CHAR(1) parameter that specifies the order in which to return information:

● C sorts by connection (default)


● T sorts by table_name

SAP IQ SQL Reference


System Procedures INTERNAL 693
Returns

sp_iqlocks displays the following information, sorted as specified in the <sort_order> parameter:

Column Data Type Description

conn_name VARCHAR(128) The name of the current connection.

conn_id INTEGER Connection ID that has the lock.

user_id CHAR(128) User associated with this connection ID.

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 materialized view. Materialized views are
only supported for SAP SQL Anywhere tables in the IQ catalog store.

creator VARCHAR(128) The owner of the table.

table_name VARCHAR(128) Table on which the lock is held.

index_id INTEGER The index ID or NULL

lock_class CHAR(8) The lock class. One of Schema, Row, Table, or Position.

lock_duration CHAR(11) The duration of the lock. One of Transaction, Position, or Connection.

lock_type CHAR(9) The lock type (this is dependent on the lock class).

row_identifier UNSIGNED BIGINT The identifier for the row the lock starts on, or NULL.

row_range BIGINT The number of contiguous rows that are locked. Row locks in the RLV
store can either be a single row, or a range of rows.

Remarks

Displays information about current locks in the database. Depending on the options you specify, you can
restrict results to show locks for a single connection, a single table, or a specified number of locks.

If sp_iqlocks cannot find the connection ID or user name of the user who has a lock on a table, it displays a 0
(zero) for the connection ID and User unavailable for the user name.

The value in the lock_type column depends on the lock classification in the lock_class column. The following
values can be returned:

Lock Class Lock Types Comments

Schema ● Shared – shared schema lock For schema locks, the row_identifier and index ID values
● Exclusive – (IQ catalog store tables are NULL.
only) exclusive schema lock

SAP IQ SQL Reference


694 INTERNAL System Procedures
Lock Class Lock Types Comments

Row ● Read – read lock Row read locks can be short-term locks (scans at isolation
● Intent – intent lock level 1) or long-term locks at higher isolation levels. The
● ReadPK – read lock lock_duration column indicates whether the read lock is of
● Write – write lock short duration because of cursor stability (Position) or
● WriteNoPK – write lock long duration, held until COMMIT/ROLLBACK (Transac­
● Surrogate – surrogate lock tion). Row locks are always held on a specific row that has
an 8-byte row identifier that is reported as a 64-bit integer
value in the row_identifier column.

A surrogate lock is a special case of a row lock. Surrogate


locks are held on surrogate entries, which are created
when referential integrity checking is delayed. 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
connection. The row_identifier value is unique for the table
and connection associated with the surrogate lock.

If required, key and non-key portions of a row can be


locked independently. A connection can obtain a read lock
on the key portion of a row for shared (read) access so
that other connections can still obtain write locks on other
non-key columns of a row. Updating non-key columns of a
row does not interfere with the insertion and deletion of
foreign rows referencing that row.

Table ● Shared – shared table lock None


● Intent – intent to update table lock
● Exclusive – (IQ catalog store tables
only) exclusive table lock

Position ● Phantom – (IQ catalog store tables Usually a position lock is also held on a specific row, and
only) phantom lock that row's 64-bit row identifier appears in the row_identi­
● Insert – insert lock fier column in the result set. However, Position locks can
be held on entire scans (index or sequential), in which
case the row_identifier column is NULL.

 Note

Exclusive, phantom, or anti-phantom locks can be placed on IQ catalog store tables, but not on SAP IQ
tables in the IQ main store. Unless you have explicitly taken out locks on a table in the catalog store, you
never see these types of locks in an SAP IQ database.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


System Procedures INTERNAL 695
You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The example shows the sp_iqlocks procedure call and its output in the SAP IQ database. The procedure is
called with all default options, so that the output shows all locks, sorted by connection:

call sp_iqlocks()

conn_name conn_id user_id table_type creator table_name


========= ======= ======= ========== ======= ==========
SQL_DBC_13cd6038 3 DBA BASE DBA rv_locks2
SQL_DBC_13cd6038 3 DBA BASE DBA rv_locks2
SQL_DBC_13cd6038 3 DBA BASE DBA rv_locks2
RVL_CONN_T775 1000000407 BASE DBA rv_locks2
index_id lock_class lock_duration lock_type row_identifier row_range
======== ========== ============= ========= ============== =========
Schema Transaction Shared
Row Transaction Row 1 4
Row Transaction Row 281474976710656 1
Table Transaction Intent

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.41 sp_iqmergerlvstore Procedure

Triggers a merge of a single row-level versioned (RLV) table store into the IQ main store.

 Syntax

sp_iqmergerlvstore '<merge_type>', '<table_name>', [ '<table_owner>' ]

SAP IQ SQL Reference


696 INTERNAL System Procedures
Parameters

merge_type

The type of merge to perform. Valid entries are BLOCKING (default) and NON-BLOCKING.
table_name

The name of the table to merge.


table_owner

The owner of the table to merge.

Remarks

After performing the merge, the stored procedure automatically commits the merge transaction.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

7.5.42 sp_iqmergerlvtables Procedure

Triggers a merge of a group of row-level version (RLV) table stores into the IQ main store.

 Syntax

sp_iqmergerlvtables [ '<merge_type>', ] [ '<table_name_exp>', ]


[ '<table_owner_exp>' ]

Parameters

merge_type

The type of merge to perform. Valid entries are BLOCKING (default) and NON-BLOCKING.

SAP IQ SQL Reference


System Procedures INTERNAL 697
table_name_exp

The expression to identify tables to merge. Defaults to all tables if not specified.
table_owner_exp

The expression to identify the owner of tables to merge. Defaults to all owners if not specified

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Remarks

● After performing the merge, the stored procedure automatically commits the merge transaction.
● <table_name> and <table_owner> accept the REGEXP wildcard characters: [ ] * . ? - | ( ) { } \ ^ $ : +

 Note

Some wildcard characters are also allowed in database identifiers. These characters are interpreted as
wildcards unless escaped with the "\" character.

Side Effects

None

Examples

You have the following RLV-enabled tables: T1, C1, C4, C18, C19, C2G, and C2Great:

● This command merges any table name that matches any single character ( the . ), one or more times ( the
* ). Therefore, all seven tables are merged:

call sp_iqmergerlvtables( 'BLOCKING', '.*' );

● This command merges any table name that starts with T followed by a single character that has a value of
1-9 or starts with C followed by a single character that has a value of 1-9. Based on the available tables, only
tables T1, C1, and C4 are merged:

call sp_iqmergerlvtables( 'BLOCKING', 'T[1-9] | C[1-9]' );

● This command merges any table name that starts with T followed by a single character that has a value of
1-9, or any table name that starts with C followed by a single character that has a value of 1-9 followed by

SAP IQ SQL Reference


698 INTERNAL System Procedures
zero or more characters that have a value of 1-9. Based on the available tables, tables T1, C1, C4, C18, and
C19 are merged, but not table C2G:

call sp_iqmergerlvtables( 'BLOCKING', 'T[1-9]|C[1-9]([1-9])?' );

In this section:

Metacharacters Within Regular Expressions [page 699]


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

7.5.42.1 Metacharacters Within Regular Expressions

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

The treatment of metacharacters can vary depending on:

● Whether the regular expression is being used with the SIMILAR TO or REGEXP search conditions, or the
REGEXP_SUBSTR function.
● Whether the metacharacter is inside of a character class in the regular expression.

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

For SIMILAR TO (only), the metacharacters *, ?, +, _, |, (, ), and { 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.

This table lists the supported regular expression metacharacters. Almost all metacharacters are treated the
same when used by SIMILAR TO, REGEXP, and REGEXP_SUBSTR:

Character Additional information

[ ] 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 evalu­
ated as actual characters.

Subcharacter classes such as POSIX character classes are also supported.

* 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, xyzabc, 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, 'colou?r'
matches color and colour.

SAP IQ SQL Reference


System Procedures INTERNAL 699
Character Additional information

+ 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 REGEXP_SUBSTR. When
specified, it matches a percent sign (%).

_ The underscore can be used with SIMILAR TO to match a single character.

The underscore is not considered a metacharacter for REGEXP and REGEXP_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 de­
scending order of preference. You can specify an unlimited number of alternative patterns.

( ) Left and right parenthesis are metacharacters when used for grouping parts of the regular expres­
sion. For example, (ab)* matches zero or more repetitions of ab. As with mathematical expres­
sions, you use grouping to control the order in which the parts of a regular expression are evalu­
ated.

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

● {<m>}
Matches a character exactly <m> times. For example, '519-[0-9]{3}-[0-9]{4}'
matches a phone number in the 519 area code (providing the data is formatted in the manner
defined in the syntax).
● {<m>,}
Matches a character at least <m> times. For example, '[0-9]{5,}' matches any string of
five or more digits.
● {<m>,<n>}
Matches a character at least <m> times, but not more than <n> times. For example, SIMILAR
TO '_{5,10}' matches any string with between 5 and 10 (inclusive) characters.

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

SAP IQ SQL Reference


700 INTERNAL System Procedures
Character Additional information

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

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

● REGEXP and REGEXP_SUBSTR


When the caret is the first character in a character class, it matches anything other than the
characters in the character set. For example, 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 exam­
ple, 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 example,
REGEXP 'cat$' matches cat, but not catfish.

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

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

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

7.5.43 sp_iqmodifyadmin Procedure

Sets an option on a named login policy to a certain value. If no login policy is specified, the option is set on the
root policy. In a multiplex, sp_iqmodifyadmin takes an optional parameter that is the multiplex server name.

 Syntax

Syntax 1

call sp_iqmodifyadmin ( '<policy_option_name>', '<value_in>',


[ '<login_policy_name>' ] )

Syntax 2

sp_iqmodifyadmin '<policy_option_name>', '<value_in>',


'<login_policy_name>'

Syntax 3

sp_iqmodifyadmin <policy_option_name>, <value_in>,


<login_policy_name>

SAP IQ SQL Reference


System Procedures INTERNAL 701
Syntax 4

sp_iqmodifyadmin '<policy_option_name>', '<value_in>',


'<login_policy_name >', '<server_name>'

Parameters

policy_option_name

The login policy option to be changed.


value_in

New value for the login policy option.


login_policy_name

Policy for which the login policy option is to be changed.


server_name

The server name.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY LOGIN POL­ System privileges GRANT System Privilege Statement [page 1511]
ICY

Side Effects

None

Examples

● The following option sets the login option locked to ON for the policy named lockeduser:

call sp_iqmodifyadmin ('locked', 'on', 'lockeduser')

SAP IQ SQL Reference


702 INTERNAL System Procedures
● The following option sets the login option locked to ON for the policy named <lockeduser> on the
multiplex server named Writer1:

call sp_iqmodifyadmin ('locked', 'on', 'lockeduser', 'Writer1')

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.44 sp_iqmodifylogin Procedure

Assigns a user to a login policy.

 Syntax

Syntax 1

call sp_iqmodifylogin '<user_id>', [ '<login_policy_name>' ]

Syntax 2

sp_iqmodifylogin '<user_id>', [ '<login_policy_name>' ]

Parameters

user_id

Variable that holds the name of the account to modify.


login_policy_name

(Optional) The name of the login policy to which the user will be assigned. If no login policy name is
specified, the user is assigned to the root login policy.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

SAP IQ SQL Reference


System Procedures INTERNAL 703
Privilege Name Privilege Type Grant Statement

MANAGE ANY USER System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Examples

● The following example assigns user joe to a login policy named expired_password:

sp_iqmodifylogin 'joe', 'expired_password'

● The following example assigns user joe to the root login policy:

call sp_iqmodifylogin ('joe')

Related Information

sp_expireallpasswords System Procedure [page 920]


(Deprecated) sp_iqaddlogin Procedure [page 585]
sp_iqcopyloginpolicy Procedure [page 627]
(Deprecated) sp_iqpassword Procedure [page 725]
Determining the Security Model Used by a Database [page 576]

7.5.45 sp_iqmovetablefromfile Procedure

Moves the table from all read-only dbfiles to read-write dbfiles of the same dbspace. It can move multiple tables
in the same dbspace in parallel via multiple concurrent connections to the server.

 Syntax

sp_iqmovetablefromfile '<table name>'

SAP IQ SQL Reference


704 INTERNAL System Procedures
Parameters

table name

The name of the table.

Remarks

sp_iqmovetablefromfile has the following restrictions:

● The table to be moved must be an IQ base table.


● If all objects of the table (that is, the table itself, its columns, indexes, partitions and column partitions) are
not in the same single dbspace, sp_iqmovetablefromfile returns an error message identifying what
object is in a different dbspace, such as Table has index(es) in other dbspace(s) – not
supported.

sp_iqmovetablefromfile returns an error under these conditions:

● If the dbspace where the table to be moved resides is not online, or not set to readwrite.
● If there are no read-only dbfiles in the dbspace where the table to be moved resides.
● If there are no read-write dbfiles in the dbspace where the table to be moved resides.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● BACKUP DATABASE System privileges GRANT System Privilege Statement [page 1511]
● SERVER OPERATOR
● ALTER DATABASE

As well as one of the following:

Privilege Name Privilege Type Grant Statement

● INSERT ANY TABLE System privileges GRANT System Privilege Statement [page 1511]
● UPDATE ANY TABLE
● DELETE ANY TABLE
● ALTER ANY TABLE
● LOAD ANY TABLE
● TRUNCATE ANY TABLE
● ALTER ANY OBJECT

SAP IQ SQL Reference


System Procedures INTERNAL 705
Side Effects

None

Example

Moves a table called "lineitem_partitioned":

sp_iqmovetablefromfile 'lineitem_partitioned';

Object_Name Bytes_Moved
DBA.lineitem_partitioned 2850816
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C1_FP 376832
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C10_FP 212992
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C11_FP 385024
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C12_FP 385024
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C13_FP 385024
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C14_FP 229376
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C15_FP 229376
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C16_FP 344064
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C2_FP 385024
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C3_FP 335872
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C4_FP 303104
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C5_FP 327680
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C6_FP 401408
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C7_FP 327680
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C8_FP 327680
DBA.lineitem_partitioned.ASIQ_IDX_T1682_C9_FP 221184
DBA.lineitem_partitioned.ASIQ_IDX_T1682_I17_HG 1024000
DBA.lineitem_partitioned.l_p_commitdate_hng 1269760
DBA.lineitem_partitioned.l_p_orderkey_hg 1179648
DBA.lineitem_partitioned.l_p_part_ord_hg 1998848
DBA.lineitem_partitioned.l_p_partkey_hg 917504
DBA.lineitem_partitioned.l_p_quantity_hng 483328
DBA.lineitem_partitioned.l_p_receiptdate_hng 1269760
DBA.lineitem_partitioned.l_p_shipdate_hng 1269760
DBA.lineitem_partitioned.l_p_supp_ord_hg 1998848
DBA.lineitem_partitioned.l_p_supp_part_hg 1024000
DBA.lineitem_partitioned.l_p_supp_part_ord_hg 1998848
DBA.lineitem_partitioned.l_p_suppkey_hg 876544

Upon success, sp_iqmovetablefromfile generates a message similar to the following in the IQ message
file:
sp_iqmovetablefromfile for table <owner name>.<table name>
started sp_iqmovetablefromfile completed for table <owner name>.<table name>.
Relocated ... bytes in ... milliseconds at ... bytes/millisecond.

SAP IQ SQL Reference


706 INTERNAL System Procedures
7.5.46 sp_iqmpxcheckdqpconfig Procedure

sp_iqmpxcheckdqpconfig is a diagnostic tool that checks the DQP configuration for the current connection.
If DQP fails, run sp_iqmpxcheckdqpconfig to determine if DQP configuration issues are causing the query
distribution failure.

 Syntax

sp_iqmpxcheckdqpconfig

Returns

Column Name Description

DiagMsgID Uniquely identifies a diagnostic message.

Description Diagnostic message describing the issue found with DQP configuration

Remarks

Applies to multiplex only.

Diagnostic information:

● 0 – No issues found with DQP configuration


● 1 – Database is an SAP IQ server
● 2 – Multiplex is running in single-node configuration mode
● 3 – Logical server policy option dqp_enabled is set to 0
● 4 – Temporary dqp_enabled connection option is set to OFF
● 5 – Logical server context has only one member node
● 6 – Coordinator does not participate in DQP since its named membership in the logical server is currently
ineffective
● 7 – Coordinator does not participate in DQP since its logical membership in the logical server is currently
ineffective because ALLOW_COORDINATOR_AS_MEMBER option in Root Logical server policy set to OFF
● 8 – There is no dbfile in IQ_SHARED_TEMP dbspace
● 9 – All dbfiles in IQ_SHARED_TEMP dbspace are READ ONLY
● 10 – IQ_SHARED_TEMP dbspace is dynamically offline

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


System Procedures INTERNAL 707
Side Effects

None

Example

The following shows sample output from the sp_iqmpxcheckdqpconfig procedure:

diagmsgid description
3 Logical server policy option dqp_enabled is set to 0
5 Logical server context has only one member node
6 Coordinator does not participate in DQP since its
named membership in the logical server is
currently ineffective
7 Coordinator does not participate in DQP since
its logical membership in the logical server
is currently ineffective because
ALLOW_COORDINATOR_AS_MEMBER option in Root
Logical server policy set to OFF
8 There is no dbfile in IQ_SHARED_TEMP dbspace

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.47 sp_iqmpxdumptlvlog Procedure

Returns the contents of the table version log in a readable format.

 Syntax

sp_iqmpxdumptlvlog [main], [asc | desc]

Remarks

Applies to multiplex only.

sp_iqmpxdumptlvlog returns the contents of the queue through which the coordinator propagates DML and
DDL commands to secondary nodes.

SAP IQ SQL Reference


708 INTERNAL System Procedures
The asc or desc arguments specify the row order. These arguments require the main argument. The default
options are:

'main', 'asc'

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE MULTIPLEX System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following shows sample output from sp_iqmpxdumptlvlog:

RowID Contents
--------------------------------------------------------------
1 Txn CatId:196 CmtId:196 TxnId:195 Last Rec:1
UpdateTime: 2011-08-08 15:41:43.621
2 Txn CatId:243 CmtId:243 TxnId:242 Last Rec:5
UpdateTime: 2011-08-08 15:42:25.070
3 DDL: Type=34, CatID=0, IdxID=0,
Object=IQ_SYSTEM_TEMP, Owner=mpx4022_w1
4 CONN: CatID=0, ConnUser=
5 SQL: ALTER DBSPACE "IQ_SYSTEM_TEMP" ADD FILE
"w1_temp1" '/dev/raw/raw25' FILE ID 16391 PREFIX 65536
FINISH 0 FIRST BLOCK
1 BLOCK COUNT 3276792 RESERVE 0 MULTIPLEX SERVER
"mpx4022_w1" COMMITID 242 CREATETIME
'2011-08-08 15:42:24.860'
6 Txn CatId:283 CmtId:283 TxnId:282 Last Rec:7
UpdateTime: 2011-08-08 15:42:50.827
7 RFRB TxnID: 242 CmtID:243 ServerID 0 BlkmapID:
0d00000000000000d2000a000000000002000000000000000000
0000000000000000000008003501010000000c38000000000000
010000000000000000000000RFID:01000501000000001300000
0000000000100000000000100RBID:010005010000000013000

SAP IQ SQL Reference


System Procedures INTERNAL 709
7.5.48 sp_iqmpxfilestatus Procedure

If run on the coordinator node, displays file status for coordinator and for every shared dbspace file on every
included secondary node. If executed on a secondary node, displays file status for only the current node.

 Syntax

sp_iqmpxfilestatus

Returns

Column Name Data Type Description

server_id UNSIGNED INT Identifier for the multiplex server, from SYSIQMPXINFO

server_name CHAR(128) Name of the multiplex node where the dbspace file resides

dbspace_name CHAR(128) Dbspace from which the space is reserved

dbfile_name CHAR(128) Logical file name of the dbspace file

FileStatus CHAR(2) Dbspace file status:

● VALID – file path and privileges are correct


● INVALID_PATH – cannot access path name
● INVALID_PERM – file privileges are incorrect

Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE MULTIPLEX System privilege GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


710 INTERNAL System Procedures
Side Effects

None

Example

The following shows sample output from sp_iqmpxfilestatus:

server_id,server_name,DBSpace_name,FileName,FileStatus
1,'mpx2422_m','IQ_SYSTEM_MAIN','IQ_SYSTEM_MAIN','VALID'
1,'mpx2422_m','mpx_main1','mpx_main1','VALID'
1,'mpx2422_m','IQ_SHARED_TEMP','sharedfile_dba','VALID'
1,'mpx2422_m','IQ_SHARED_TEMP','sharedfile_dba1','VALID'
2,'mpx2422_w1','IQ_SYSTEM_MAIN','IQ_SYSTEM_MAIN','VALID'
2,'mpx2422_w1','mpx_main1','mpx_main1','VALID'
2,'mpx2422_w1','IQ_SHARED_TEMP','sharedfile_dba','VALID'
2,'mpx2422_w1','IQ_SHARED_TEMP','sharedfile_dba1','VALID'
3,'mpx2422_r1','IQ_SYSTEM_MAIN','IQ_SYSTEM_MAIN','VALID'
3,'mpx2422_r1','mpx_main1','mpx_main1','VALID'
3,'mpx2422_r1','IQ_SHARED_TEMP','sharedfile_dba','VALID'
3,'mpx2422_r1','IQ_SHARED_TEMP','sharedfile_dba1','VALID'

7.5.49 sp_iqmpxincconnpoolinfo Procedure

If run on the coordinator node, displays INC connection pool status for every node. If executed on a secondary
node, displays INC connection pool status for only the current node.

 Syntax

sp_iqmpxincconnpoolinfo

Returns

Column Name Data Type Description

server_id UNSIGNED INT Identifier for the server

server_name CHAR(128) Name of the server

current_pool_size UNSIGNED INT Current size of connection pool

idle_connection_cou UNSIGNED INT Number of idle connections in the pool


nt

connections_in_use UNSIGNED INT Number of connections in use

SAP IQ SQL Reference


System Procedures INTERNAL 711
Remarks

If the procedure is run on the coordinator and a secondary node is not responding or has timed out, the result
set omits the row for that node, because this data cannot be accessed unless that node is running.

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE MULTIPLEX System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following shows sample output from sp_iqmpxincconnpoolinfo:

server_id,server_name,current_pool_size,
idle_connection_count,connections_in_use
2,'r2_dbsrv90210',0,0,0
3,'w3_dbsrv90210',0,0,0

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


712 INTERNAL System Procedures
7.5.50 sp_iqmpxincheartbeatinfo Procedure

If run on the coordinator node, displays INC heartbeat status for every node. If executed on a secondary node,
displays INC heartbeat status for just the current node.

 Syntax

sp_iqmpxincheartbeatinfo

Returns

Column Name Data Type Description

server_id UNSIGNED INT Identifier for the server

server_name CHAR(128) Name of the server

last_positive_hb TIMESTAMP Date/time of last successful heartbeat ping, in the following format:
DD:MM:YYYY:HH:MM:SS

time_not_responding TIME Time since last successful heartbeat ping, in the following format:
HH:MM:SS

time_until_timeout TIME If a node is not responding, the time left until node is declared offline.

Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE MULTIPLEX System privileges GRANT System Privilege Statement [page 1511]

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 713
Example

● Sample output of sp_iqmpxincheartbeatinfo:

server_id,server_name,last_positive_hb,
time_not_responding,time_until_timeout
2,'r2_dbsrv90210',2012-11-17
15:48:42.0,00:00:00,00:00:00
3,'w3_dbsrv90210',2012-11-17
15:48:42.0,00:00:00,00:00:00

● If the elapsed time exceeds 24 hours, SAP IQ returns sp_iqmpxincheartbeatinfo output like the
following:

server_id,server_name,last_positive_hb,
time_not_responding,time_until_timeout
2,'r2_mpx_cr_srv',Jan 14 2013 11:57AM,11:59PM,11:59PM
3,'w4_mpx_cr_srv',Jan 14 2013
11:57AM,11:59PM,11:59PM
(2 rows affected)
(return status = 0)

A value of 11:59PM in the time_not_responding and time_until_timeout columns means that the
time has crossed the 24-hour limit.

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.51 sp_iqmpxincstatistics Procedure

Displays a snapshot of the aggregate statistics of internode communication (INC) status since server startup
as of the moment of execution.

 Syntax

sp_iqmpxincstatistics

SAP IQ SQL Reference


714 INTERNAL System Procedures
Returns

Column Name Data Type Description

stat_name CHAR(128) INC statistics name. Valid stat_name values are:

● NumSuspendedINC – Number of suspended INC connections


since server startup
● NumResumedINC – Number of resumed INC connections since
server startup
● NumDroppedSuspendedINC – Number of dropped INC connec­
tions that have been suspended (on coordinator only)
● NumSuspendedTxnRollbackINC – Number of rolled back global
DML transactions due to INC failure (on writer only)

stat_value UNSIGNED INTEGER INC statistics value.

Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY STATISTICS System privileges GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example shows one suspended and one resumed transaction:

sp_iqmpxincstatistics

stat_name stat_value

SAP IQ SQL Reference


System Procedures INTERNAL 715
NumSuspendedINC 1
NumResumedINC 1
NumSuspendedTXNRollBackINC 0

7.5.52 sp_iqmpxinfo Procedure

Returns a row for every node in the multiplex. Can be run from any multiplex node.

 Syntax

sp_iqmpxinfo

Returns

Column Name Data Type Description

server_id UNSIGNED INT Identifier for the server for which information appears

server_name CHAR(128) Name of the server

connection_info LONG VARCHAR A formatted string containing the host/port portion of the connec­
tion string used for TCP/IP connections between multiplex servers.

db_path LONG VARCHAR Full database path

role CHAR(16) Values:

● 'coordinator'
● 'writer'
● 'reader'

status CHAR(8) Values:

● 'included'
● 'excluded'

mpx_mode CHAR(16) Values:

● 'single'
● 'coordinator'
● 'writer'
● 'reader'
● 'unknown'

inc_state CHAR(16) Values:

● 'active'
● 'not responding'
● 'timed out'

SAP IQ SQL Reference


716 INTERNAL System Procedures
Column Name Data Type Description

coordinator_failove CHAR(128) Name of the failover server


r

current_version UNSIGNED BIGINT Decimal-formatted version ID

active_versions LONG VARCHAR Comma-separated list of decimal formatted version IDs.

private_connection_ LONG VARCHAR A formatted string containing the host/port portion of the connec­
info tion string used for private TCP/IP connections between multiplex
servers

mipc_priv_state CHAR(16) Values:

● 'active' – MIPC connection to this node is active over the private


interconnect
● 'not responding' – MIPC connection to this node is not respond­
ing over private interconnect

mipc_public_state CHAR(16) Values:

● 'active' – MIPC connection to this node is active over the public


interconnect
● 'not responding' – MIPC connection to this node is not respond­
ing over public interconnect

rlvstore CHAR(8) Indicator of existence of RLV store on multiplex. Values are enabled
and disabled.

Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● MANAGE MULTIPLEX System privileges GRANT System Privilege Statement [page 1511]
● MONITOR

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 717
Example

The following shows sample output from sp_iqmpxinfo:

server_id,server_name,connection_info,db_path,role,
status,mpx_mode,inc_state,coordinator_failover,
current_version,active_versions,private_connection_
info,mipc_priv_state,mipc_public_state

1,'my_mpx1','host=(fe80::214:4fff:fe45:be26%2):1362
0,(fd77:55d:59d9:329:214:4fff:fe45:be2
6%2):13620,10.18.41.196:13620','/system3/users
/devices/s16900269/iqmpx1/mpx1.db',
'coordinator','included','coordinator','N/A',
'my_mpx2',0,,,'active','active'

2,'IQ_mpx2','host=system3:13625',
'/system3/users/devices/s16900269
/iqmpx_2/wk0001.db','writer','included',
'writer','active','IQ_mpx20', 'not responding','active'

3,'IQ_mpx3,'host=system3:13630/system3/users/devi
ces/s16900269/iqmpx_3/mpx1.db','reader','included',
'unknown',timed out',
'IQ_mpx20','not responding',
'not responding'

7.5.53 sp_iqmpxsuspendedconninfo Procedure

Shows details about currently suspended connections and transactions on the coordinator node.

 Syntax

sp_iqmpxsuspendedconninfo

Returns

Column Name Data Type Description

ConnName CHAR(128) Connection name

ConnHandle UNSIGNED INT Connection identifier

GlobalTxnID UNSIGNED INT Global transaction identifier of active transaction on this connection

MPXServerName CHAR(128) Name of the multiplex server where the INC connection originates

TimeInSuspended INT Total time, in seconds, spent by the connection in suspended state
State

SuspendTimeout INT Suspend timeout, in seconds (2*MPX_LIVENESS_TIMEOUT)

SAP IQ SQL Reference


718 INTERNAL System Procedures
Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. No system privilege is needed to see your own suspended connections.

To see all suspended connections in the database, you need one of the following:

Privilege Name Privilege Type Grant Statement

● DROP CONNECTION System privileges GRANT System Privilege Statement [page 1511]
● MONITOR
● SERVER OPERATOR

Side Effects

None

Example

The following shows sample output from sp_iqmpxsuspendedconninfo:

sp_iqmpxsuspendedconninfo

ConnName ConnHandle GlobalTxnId


=================== ============= =============
'IQ_MPX_SERVER_P54' 14 112753
MPXServerName TimeInSuspendedState
================== =======================
'HP1_12356_IQ_mpx2' 37
SuspendTimeout
===============
360

SAP IQ SQL Reference


System Procedures INTERNAL 719
7.5.54 sp_iqmpxvalidate Procedure

Checks multiplex configuration for inconsistencies.

 Syntax

call dbo.sp_iqmpxvalidate( 'Y' )

Returns

Returns a severity result to the caller; values are:

● 0 – No errors detected
● 1 – Dynamic state is not as expected.
● 2 – Nonfatal configuration error; for example, multiplex operation impaired
● 3 – Fatal configuration problem; for example, one or more servers might not start

Remarks

Applies to multiplex only.

Executes multiple checks on tables SYS.SYSIQDBFILE and other multiplex events and stored procedures. May
run on any server.

Returns rows listing all errors and their severity. If called interactively, with the optional calling parameter 'N',
returns only the severity status.

Each error indicates its severity. If there are no errors, the procedure returns No errors detected.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

SAP IQ SQL Reference


720 INTERNAL System Procedures
7.5.55 sp_iqmpxversioninfo Procedure

Shows the current version information for this server, including server type (write server, query server, single-
node mode) and synchronization status.

 Syntax

sp_iqmpxversioninfo

Returns

Column Data Type Description

CatalogID UNSIGNED BIGINT Catalog version on this server.

VersionID UNSIGNED BIGINT Latest version available on this server.

OAVID UNSIGNED BIGINT Oldest active version on this server.

ServerType CHAR(1) Type of server:

● "C" – Coordinator
● "W" – Write Server
● "Q" – Query Server

CatalogSync CHAR(1) Catalog synchronization:

● "T" – synchronized
● "F" – not synchronized

WCatalogID UNSIGNED BIGINT Catalog version on the write server.

WVersionID UNSIGNED BIGINT Latest version available on the write server.

Remarks

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


System Procedures INTERNAL 721
Side Effects

None

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.56 sp_iqobjectinfo Procedure

Returns partitions and dbspace assignments of database objects and subobjects.

 Syntax

sp_iqobjectinfo [ <owner_name> ] [ , <object_name> ] [ , <object-type> ]

Parameter

owner_name

(Optional) Owner of the object. If specified, sp_iqobjectinfo displays output only for tables with the
specified owner. If not specified, sp_iqobjectinfo displays information on tables for all users in the
database.
object_name

(Optional) Name of the table. If not specified, sp_iqobjectinfo displays information on all tables in the
database.
object-type

(Optional) Valid table object types. If <object-type> is a table, enclose it in quotation marks.

Returns

Returns all the partitions and the dbspace assignments of a particular or all database objects (of type table)
and its subobjects. The subobjects are columns, indexes, primary key, unique constraints, and foreign keys.

Column Name Description

owner Name of the owner of the object.

SAP IQ SQL Reference


722 INTERNAL System Procedures
Column Name Description

object_name Name of the object (of type table) located on the dbspace.

sub_object_name Name of the object located on the dbspace.

object_type Type of the object (column, index, primary key, unique constraint, foreign key, partition, or table).

object_id Global object ID of the object.

id Table ID of the object.

dbspace_name Name of the dbspace on which the object resides. The string "[multiple]" appears in a special
meta row for partitioned objects. The [multiple] row indicates that multiple rows follow in the out­
put to describe the table or column.

partition_name Name of the partition for the given object.

Remarks

All parameters are optional, and any parameter may be supplied independent of the value of another
parameter.

Use input parameters with sp_iqobjectinfo; you can query the results of the sp_iqobjectinfo and it
performs better if you use input parameters rather than using predicates in the WHERE clause of the query. For
example, Query A is written as:

SELECT COUNT(*) FROM sp_iqobjectinfo()


WHERE owner = 'DBA'
AND object_name = 'tab_case510'
AND object_type = 'table'
AND sub_object_name is NULL
AND dbspace_name = 'iqmain7'
AND partition_name = 'P1'

Query B is Query A rewritten to use sp_iqobjectinfo input parameters:

SELECT COUNT(*) FROM sp_iqobjectinfo('DBA','tab_case510','table')


WHERE sub_object_name is NULL
AND dbspace_name = 'iqmain7'
AND PARTITION_NAME = 'P1'

Query B returns results faster than Query A. When the input parameters are passed to sp_iqobjectinfo, the
procedure compares and joins fewer records in the system tables, thus doing less work compared to Query A.
In Query B, the predicates are applied in the procedure itself, which returns a smaller result set, so a smaller
number of predicates is applied in the query.

The sp_iqobjectinfo stored procedure supports wildcard characters for interpreting <owner_name>,
<object_name>, and <object_type>. It shows information for all dbspaces that match the given pattern in
the same way the LIKE clause matches patterns inside queries.

SAP IQ SQL Reference


System Procedures INTERNAL 723
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

 Note

These examples show objects in the iqdemo database to better illustrate output. iqdemo includes a
sample user dbspace named iq_main that may not be present in your own databases.

● The following example displays information about partitions and dbspace assignments of a specific
database object and subobjects owned by a specific user:

sp_iqobjectinfo GROUPO,Departments

owner object_name sub_object_name object_type object_id id


GROUPO Departments (NULL) table 3632 73
8
GROUPO Departments DepartmentID column 3633 73
8
GROUPO Departments DepartmentName column 3634 73
8
GROUPO Departments DepartmentHeadID column 3635 73
8
GROUPO Departments DepartmentsKey primary
key 83 738
GROUPO Departments FK_DepartmentHeadID_EmployeeID foreign
key 92 738
dbspace_name partition_name
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)

● The following example displays information about partitions and dbspace assignments of a specific
database object and subobjects owned by a specific user for <object-type> table:

sp_iqobjectinfo DBA,sale,'table'

owner object_name sub_object_name object_type object_id id


DBA sale (NULL) table 3698 742
DBA sale prod_id column 3699 742
DBA sale month_num column 3700 742
DBA sale rep_id column 3701 742

SAP IQ SQL Reference


724 INTERNAL System Procedures
DBA sale sales column 3702 742
dbspace_name partition_name
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)
iq_main (NULL)

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.57 (Deprecated) sp_iqpassword Procedure

Changes a user’s password.

 Note

Though sp_iqpassword is still supported for backwards compatibility, use ALTER USER to change a user
password.

 Syntax

Syntax 1

call sp_iqpassword ('<caller_password>', '<new_password>' [,


'<user_name>'])

Syntax 2

sp_iqpassword '<caller_password>', '<new_password>' [, '<user_name>']

Parameters

caller_password

Your password. When you are changing your own password, this is your old password. When a user with the
CHANGE PASSWORD system privilege is changing another user’s password, caller_password is the
password of the user making the change.
new_password

New password for the user, or for <loginname>.


user_name

(Optional) Login name of the user whose password is being changed by another user with CHANGE
PASSWORD system privilege. Do not specify user_name when changing your own password.

SAP IQ SQL Reference


System Procedures INTERNAL 725
Remarks

A user password is an identifier. Any user can change his or her own password using sp_iqpassword. The
CHANGE PASSWORD system privilege is required to change the password of any existing user.

Identifiers have a maximum length of 128 bytes. They must be enclosed in double quotes or square brackets if
any of these conditions are true:

● The identifier contains spaces.


● The first character of the identifier is not an alphabetic character (as defined below).
● The identifier contains a reserved word.
● The identifier contains characters other than alphabetic characters and digits.
Alphabetic characters include the alphabet, as well as the underscore character (_), at sign (@), number
sign (#), and dollar sign ($). The database collation sequence dictates which characters are considered
alphabetic or digit characters.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. No additional system privilege is need to set your own password.

To set the password of another, you need:

Privilege Name Privilege Type Grant Statement

CHANGE PASSWORD System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Examples

● The following example changes the password of the logged-in user from irk103 to exP984:

sp_iqpassword 'irk103', 'exP984'

● In the following example, if the logged-in user has the CHANGE PASSWORD system privilege or joe, the
password of user joe from eprr45 to pdi032:

call sp_iqpassword ('eprr45', 'pdi932', 'joe')

SAP IQ SQL Reference


726 INTERNAL System Procedures
Related Information

sp_expireallpasswords System Procedure [page 920]


(Deprecated) sp_iqaddlogin Procedure [page 585]
sp_iqcopyloginpolicy Procedure [page 627]
sp_iqmodifylogin Procedure [page 703]
ALTER USER Statement [page 1203]

7.5.58 sp_iqpkeys Procedure

Displays information about primary keys and primary key constraints by table, column, table owner, or for all
SAP IQ tables in the database.

 Syntax

sp_iqpkeys { [ <table-name> ], [ <column-name> ], [ <table-owner> ] }

Parameter

table-name

(Optional) The name of a base or global temporary table. If specified, the procedure returns information
about primary keys defined on the specified table only.
column-name

(Optional) The name of a column. If specified, the procedure returns information about primary keys on
the specified column only.
table-owner

(Optional) The owner of a table or table. If specified, the procedure returns information about primary keys
on tables owned by the specified owner only.

Returns

The sp_iqpkeys stored procedure displays the following information about primary keys on base and global
temporary tables in a database:

Column Name Description

table_name The name of the table.

table_owner The owner of the table.

SAP IQ SQL Reference


System Procedures INTERNAL 727
Column Name Description

column_name The name of the column(s) on which the primary key is defined.

column_id The column ID.

constraint_name The name of the primary key constraint.

constraint_id The primary key constraint ID.

Remarks

One or more of the parameters can be specified. If you do not specify either of the first two parameters, but
specify the next parameter in the sequence, you must substitute NULL for the omitted parameters. If none of
the parameters are specified, a description of all primary keys on all tables in the database is displayed. If any
of the specified parameters is invalid, no rows are displayed in the output.

Syntax Output

sp_iqpkeys sales Displays information about primary keys defined on table sales.

sp_iqpkeys sales, NULL, Displays information about primary keys defined on table sales owned by DBA.
DBA

sp_iqpkeys sales, Displays information about primary key defined on column store_id of table
store_id, DBA sales owned by DBA.

sp_iqpkeys NULL, NULL, Displays information about primary keys defined on all tables owned by DBA.
DBA

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● The following example displays the primary keys defined on columns of table sales1:

sp_iqpkeys sales1

SAP IQ SQL Reference


728 INTERNAL System Procedures
table_name table_owner column_name column_id constraint_name constraint_id
sales1 DBA store_id 1 MA114 114

● The following example displays the primary keys defined on columns of table sales2:

sp_iqpkeys sales2
table_name table_owner column_name column_id constraint_name constraint_id
sales2 DBA store_id, 1,2 MA115 115
order_num

● The following example displays the primary keys defined on the column store_id of table sales2:

sp_iqpkeys sales2, store_id


table_name table_owner column_name column_id constraint_name constraint_id
sales2 DBA store_id 1 MA115 115

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.59 sp_iqprocedure Procedure

Displays information about system and user-defined procedures.

 Syntax

sp_iqprocedure [ <proc-name> ], [ <proc-owner> ], [ <proc-type> ]

Parameters

proc-name

(Optional) The name of the procedure.


proc-owner

SAP IQ SQL Reference


System Procedures INTERNAL 729
(Optional) The owner of the procedure.
proc-type

(Optional) The type of procedure. Allowed values are:

● SYSTEM – displays information about system procedures (procedures owned by user SYS or dbo) only
● ALL – displays information about user and system procedures
● Any other value – displays information about user procedures

Returns

Column Name Description

proc_name The name of the procedure.

proc_owner The owner of the procedure.

proc_defn The command used to create the procedure. For hidden procedures, the keyword 'HIDDEN' is dis­
played.

replicate Displays Y if the procedure is a primary data source in a Replication Server installation; N if not.

srvid Indicates the remote server, if the procedure is on a remote database server.

remarks A comment string

Remarks

The sp_iqprocedure procedure can be invoked without any parameters. If no parameters are specified, only
information about user-defined procedures (procedures not owned by dbo or SYS) is displayed by default.

If you do not specify either of the first two parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example, sp_iqprocedure NULL, NULL, SYSTEM
and sp_iqprocedure NULL, user1.

Syntax Output

sp_iqprocedure Displays information about all procedures in the database not owned by dbo or SYS.

sp_iqprocedure sp_test Displays information about the procedure sp_test.

sp_iqprocedure No rows returned, as the procedure non_existing_proc does not exist.


non_existing_proc

sp_iqprocedure NULL, DBA Displays information about all procedures owned by DBA.

sp_iqprocedure sp_test, Displays information about the procedure sp_test owned by DBA.
DBA

sp_iqprocedure The procedure sp_iqtable is not a system procedure. If there is no user-defined


sp_iqtable procedure also named sp_iqtable, no rows are returned (by default only user-de­
fined procedures are returned).

SAP IQ SQL Reference


730 INTERNAL System Procedures
Syntax Output

sp_iqprocedure No rows returned, as the procedure sp_iqtable is not a user procedure (by default
sp_iqtable, dbo only user procedures returned).

sp_iqprocedure NULL, Displays information about all system procedures (owned by dbo or SYS).
NULL, SYSTEM

sp_iqprocedure Displays information about the system procedure sp_iqtable.


sp_iqtable, NULL, SYSTEM

sp_iqprocedure Displays information about the system procedure sp_iqtable owned by dbo.
sp_iqtable, dbo, ALL

The sp_iqprocedure stored procedure displays information about procedures in a database. If you specify
one or more parameters, the result is filtered by the specified parameters. For example, if <proc-name> is
specified, only information about the specified procedure is displayed. If <proc-owner> is specified,
sp_iqprocedure returns only information about procedures owned by the specified owner. If no parameters
are specified, sp_iqprocedure displays information about all the user-defined procedures in the database.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Example

● Displays information about the user-defined procedure sp_test:

sp_iqprocedure sp_test

proc_name proc_owner proc_defn replicate srvid remarks


sp_test DBA create procedure N (NULL) (NULL)
DBA.sp_test(in n1
integer)
begin message'sp_test'end

● Displays information about all procedures owned by user DBA:

sp_iqprocedure NULL, DBA

proc_name proc_owner proc_defn replicate srvid remarks

SAP IQ SQL Reference


System Procedures INTERNAL 731
sp_test DBA create procedure N (NULL) (NULL)
DBA.sp_test(in n1
integer)
begin message'sp_test'end
sp_dept DBA create procedure N (NULL) (NULL)
DBA.sp_dept() begin end

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.60 sp_iqprocparm Procedure

Displays information about stored procedure parameters, including result set variables and SQLSTATE/
SQLCODE error values.

 Syntax

sp_iqprocparm [ <proc-name> ], [ <proc-owner> ], [ <proc-type> ]

Parameters

proc-name

(Optional) The name of the procedure.


proc-owner

(Optional) The owner of the procedure.


proc-owner

(Optional) The type of procedure. Allowed values are:

● SYSTEM – displays information about system procedures (procedures owned by user SYS or dbo) only
● ALL – displays information about user and system procedures
● Any other value – displays information about user procedures

Returns

Column name Description

proc_name The name of the procedure

SAP IQ SQL Reference


732 INTERNAL System Procedures
Column name Description

proc_owner The owner of the procedure

parm_name The name of the parameter

parm_type The type of parameter is one of the following values:

● Normal parameter (variable)


● Result variable – used with procedures that return result sets
● SQLSTATE error value
● SQLCODE error value

parm_mode The mode of the parameter: whether a parameter supplies a value to the procedure, returns a
value, does both, or does neither. Parameter mode is one of the following:

● in – parameter supplies a value to the procedure


● out – parameter returns a value
● inout – parameter supplies as well as returns a value
● NULL – parameter neither supplies nor returns a value

domain_name The name of the data type of the parameter as listed in the SYSDOMAIN system table

width The length of string parameters, the precision of numeric parameters, and the number of bytes of
storage for all other data types

scale The number of digits after the decimal point for numeric data type parameters and zero for all
other data types

default The default value of the parameter, held as a string

Remarks

You can invoke sp_iqprocparm without parameters. If you do not specify any parameters, input/output and
result parameters of user-defined procedures (procedures not owned by dbo or SYS) appear.

If you do not specify either of the first two parameters, but specify the next parameter in the sequence, you
must substitute NULL for the omitted parameters. For example, sp_iqprocparm NULL, NULL, SYSTEM and
sp_iqprocparm NULL, user1.

Syntax Output

sp_iqprocparm Displays parameters for all procedures in the database not owned by dbo
or SYS.

sp_iqprocparm sp_test Displays information about the procedure sp_test.

sp_iqprocparm non_existing_proc No rows returned, as the procedure non_existing_proc does not ex­
ist.

sp_iqprocparm NULL, DBA Displays parameters for all procedures owned by DBA.

sp_iqprocparm sp_test, DBA Displays parameters for the procedure sp_test owned by DBA.

SAP IQ SQL Reference


System Procedures INTERNAL 733
Syntax Output

sp_iqprocparm sp_iqtable sp_iqtable is a system procedure. If there is no user-defined proce­


dure also named sp_iqtable, no rows are returned (by default, only
user-defined procedures are returned).

sp_iqprocparm sp_iqtable, dbo No rows returned, as the procedure sp_iqtable is not a user procedure
(by default, only user procedures are returned).

sp_iqprocparm NULL, NULL, Displays parameters for all system procedures (owned by dbo or SYS).
SYSTEM

sp_iqprocparm sp_iqtable, NULL, Displays parameters of the system procedure sp_iqtable.


SYSTEM

sp_iqprocparm sp_iqtable, dbo, Displays parameters of the system procedure sp_iqtable owned by
ALL dbo.

The sp_iqprocparm stored procedure displays information about stored procedure parameters, including
result set variables and SQLSTATE/SQLCODE error values. If you specify one or more parameters, the result is
filtered by the specified parameters. For example, if <proc-name> is specified, only information about
parameters to the specified procedure displays. If <proc-owner> is specified, sp_iqprocparm only returns
information about parameters to procedures owned by the specified owner. If no parameters are specified,
sp_iqprocparm displays information about parameters to all the user-defined procedures in the database.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

● Display information about the parameters of the user-defined procedure sp_test:

sp_iqprocparm sp_test

proc_name proc_owner parm_name parm_type parm_mode domain_name width scale de


fault

SAP IQ SQL Reference


734 INTERNAL System Procedures
sp_test DBA ID
normal in integer 4 0 (NULL)

● Display information about the parameters of the system procedure sp_iqshowcompression:

sp_iqprocparm sp_iqshowcompression, dbo, system

proc_name proc_owner parm_name parm_type parm_mode


domain_name width scale default
sp_iqshowcompression dbo @owner_name normal in
char 128 0 (NULL)
sp_iqshowcompression dbo @table_name normal in
char 128 0 (NULL)
sp_iqshowcompression dbo @column_name normal in
char 128 0 (NULL)
sp_iqshowcompression dbo Column result out
char 128 0 (NULL)
sp_iqshowcompression dbo Compression result out
char 3 0 (NULL)

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.61 sp_iqpurgebackuphistory Procedure

Deletes rows from the SysIQBackupHistory and SysIQBackupHistoryDetail system tables.

 Syntax

sp_purgeiqbackuphistory (
[ bu_id='<value>' ], [ bu_time_low='<value>' ],
[ bu_time_high='<value>' ], [ bu_type=<value>' ]
)

SAP IQ SQL Reference


System Procedures INTERNAL 735
Parameters

bu_id='value'

(Optional) An UNSIGNED BIGINT parameter that deletes entries that match the bu_id.
bu_time_low='value'

(Optional) A TIMESTAMP parameter that deletes entries with timestamps (hh:mm:ss.ms) greater than or
equal to bu_id.
bu_time_high='value'

(Optional) A TIMESTAMP parameter that deletes entries with backup times less than or equal to bu_id.
bu_type=value

(Optional) A TINYINT parameter that deletes entries that match the bu_id:

● 0 = FULL
● 1 = INCREMENTAL
● 2 = INCREMENTAL SINCE FULL
● 5 = POINT IN TIME RECOVERY

Remarks

The selection parameters you provide determine which rows are deleted from the SysIQBackupHistory and
SysIQBackupHistoryDetail system tables. If no selection parameters are specified, all rows are deleted.

Since SysIQBackupHistory and SysIQBackupHistoryDetail are system tables, purging the tables entries is non-
transactional and cannot be rolled back.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

BACKUP DATABASE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

SAP IQ SQL Reference


736 INTERNAL System Procedures
Examples

● The following example deletes entries that match a bu_id of 9277:

sp_purgeiqbackuphistory(bu_id='9277')

● The following example deletes entries after January 1, 2013:

sp_purgeiqbackuphistory(bu_time_low='2013/01/01')

● The following example deletes entries with backup times before January 1, 2013:

sp_purgeiqbackuphistory(bu_time_high='2013/01/01')

● The following example shows miscellaneous sp_purgeiqbackuphistory commands:

sp_iqpurgebackuphistory( bu_id ='9277') // deletes backup '9277'


sp_iqpurgebackuphistory( bu_time_low='2012/12/31' ) // deletes backups after Dec 31,
2012
sp_iqpurgebackuphistory( bu_time_high='2013/01/01', bu_type=1 ) // deletes incrementals before
Jan 1, 2013

● The following example contrasts the SYSIQBACKUPHISOTRY table values before and after running
sp_purgeiqbackuphistory. Corresponding changes to the SYSIQABACKUPHISOTRYDETAIL table are
not shown.

//backup history before purge


bu_id bu_time type selective_type virtual_type dependson_id
cmd creator version
--------------------------------------------------------------------------------------------------
----------------------------------------
27 2015-03-14 15:45:35.000 0 0 0 0 backup database to
'mybak' DBA 8
70 2015-03-14 15:46:48.000 0 0 0 0 backup database to
'mybak1' DBA 8
119 2015-03-14 15:47:52.000 1 0 0 70 backup database
incremental to 'mybakinc' DBA 8
164 2015-03-14 15:48:53.000 1 0 0 119 backup database
incremental to 'mybakinc1' DBA 8
209 2015-03-14 15:49:54.000 2 0 0 70 backup database
incremental since full to 'mybakinc2' DBA 8
// sp_purgeiqbackuphistory( bu_type=1 ) purges incremental backups; post purge results appear
below.
bu_id bu_time type selective_type virtual_type dependson_id
cmd creator version
--------------------------------------------------------------------------------------------------
----------------------------------------
27 2015-03-14 15:45:35.000 0 0 0 0 backup database to
'mybak' DBA 8
70 2015-03-14 15:46:48.000 0 0 0 0 backup database to
'mybak1' DBA 8
209 2015-03-14 15:49:54.000 2 0 0 70 backup database
incremental since full to 'mybakinc2' DBA 8

7.5.62 sp_iqrebuildindex Procedure

Rebuilds column indexes.

 Syntax

sp_iqrebuildindex <table_name>, <index_clause>

SAP IQ SQL Reference


System Procedures INTERNAL 737
Parameter

table_name

Partial or fully qualified table name on which the index rebuild process takes place. If the user both owns
the table and executes the procedure, a partially qualified name may be used; otherwise, the table name
must be fully qualified.
index_clause

One or more of the following strings, separated by spaces:

column <column_name>[<count>]

index <index_name>

You must specify the keywords column and index. These keywords are not case-sensitive.

 Caution

A third-party reference document describes an unsupported sp_iqrebuildindex syntax. Specifying


the table name in the index clause, such as in the following example, results in an error:

sp_iqrebuildindex tb1, 'column tb1.c1'

Remarks

 Note

To rebuild an index other than the default FP index, specify the index name. sp_iqrebuildindex behavior
is the same regardless of the FP_NBIT_IQ15_COMPATIBILITY setting.

Each <column_name> or <index_name> must refer to a column or index on the specified table. If you specify
a <column_name> or <index_name> multiple times, the procedure returns an error and no index is rebuilt.

The <count> is a non-negative number that represents the IQ UNIQUE value. In a CREATE TABLE statement,
IQ UNIQUE (count) approximates how many distinct values can be in a given column. The number of
distinct values affects query speed and storage requirements.

MERGEALL and RETIER are keywords specific to HG index operations:

sp_iqrebuildindex ('<table name>', 'index <index name> [ MERGEALL | RETIER ]')

If MERGEALL or RETIER are omitted from an operation from an HG index , sp_iqrebuildindex truncates and
reconstructs the entire HG index from the column data.

MERGEALL merges all tiers of a tiered HG index and moves the contents into an appropriate tier:

sp_iqrebuildindex ('<table name>', 'index <index name> MERGEALL')

The merge ensures that there is only one active sub-index in a tiered HG index. MERGEALL operations may
improve query access time for a tiered index in cases where there are too many deleted records (as shown by

SAP IQ SQL Reference


738 INTERNAL System Procedures
sp_iqindexmetadata). MERGEALL will only be supported with an index clause and only if the index specified
is an HG index.

RETIER is a keyword specific to HG indexes that changes the format of an HG index from non-tiered HG to tiered
HG, or tiered HG to non-tiered HG:

sp_iqrebuildindex ('<table name>', 'index <index name> RETIER')

RETIER toggles the format of an HG index:

● RETIER converts a tiered HG index into a single non-tiered HG index. Tiering metadata is disabled and only
one sub-index is maintained.
● RETIER converts a non-tiered HG into a tiered HG index, and pushes the single sub-index, which contains all
the data into an appropriate tier.

MERGEALL and RETIER will only be supported with an index clause, and only if the index specified is an HG
index.

If you specify a column name, sp_iqrebuildindex rebuilds the default FP index for that column; no index
name is needed. If you specify the default FP index name assigned by SAP IQ in addition to the column name,
sp_iqrebuildindex returns an error.

sp_iqrebuildindex rebuilds a WD index on a column of data type LONG VARCHAR(CLOB) .

A column with IQ UNIQUE <n> value determines whether sp_iqrebuildindex rebuilds the column as Flat
FP or NBit. An IQ UNIQUE <n> value set to 0 rebuilds the index as a Flat FP. An <n> value greater than 0
but less than 2,147,483,647 rebuilds the index as NBit. NBit columns without an <n> value are rebuilt as NBit.
sp_iqrebuildindex rebuilds an NBit column as NBit, even if you do not specify a count. If you do specify a
count, the <n> value must be greater than the number of unique values already in the index.

If you rebuild a column with a Flat FP index, and the column does not include an IQ UNIQUE <n> value,
sp_iqrebuildindex rebuilds the index as N-Bit FP up to the limits defined in the
FP_NBIT_AUTOSIZE_LIMIT and FP_NBIT_LOOKUP_MB options. Specifying an <n> value for a flat column
throws an error if FP_NBIT_ENFORCE_LIMITS=ON and the cardinality exceeds the count.

The sp_iqrebuildindex default interface allows a user to re-create an entire HG index from an existing FP
index. sp_iqrebuildindex re-reads all FP index column values and creates the HG index. This will, however
retain all the metadata regarding tier sizes, continuous load size, etc.

 Note

This procedure does not support TEXT indexes. To rebuild a TEXT index you must drop and re-create the
index.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

SAP IQ SQL Reference


System Procedures INTERNAL 739
Privilege Name Privilege Type Grant Statement

● INSERT ANY TABLE System privilege GRANT System Privilege Statement [page 1511]

● INSERT privilege on the Object-level privilege GRANT Object-Level Privilege Statement [page 1502]
table

Side Effects

None

Examples

● The following two lines of syntax show the default FP index on column dept_id:

sp_iqrebuildindex 'emp1', 'column dept_id'


call sp_iqrebuildindex ('empl1', 'column dept_id')

● This creates a flat FP index on column c1:

CREATE TABLE mytable (c1 int IQ UNIQUE (0))

● The following two converts the default Flat FP index to an Nbit index with an estimated distinct count of
1024:

sp_iqrebuildindex 'mytable', 'column c1 1024'


call sp_iqrebuildindex ('mytable', 'column c1 1024')

 Note

Users can expect to see a temporary performance drop when sp_iqrebuildindex runs on a large HG
index.

Related Information

sp_iqindexfragmentation Procedure [page 674]


sp_iqrowdensity Procedure [page 752]
Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


740 INTERNAL System Procedures
7.5.63 sp_iqrebuildindexwide Procedure

Rebuilds pre-16.1 FP indexes wider than 255 bytes.

 Syntax

sp_iqrebuildindexwide <table_name> [, <table_owner> ] [, <level> ]

Parameters

table_name

Identifies the table. This parameter is required, but can include an empty string. Substituting an empty
string for the <table_name> rebuilds all wide-column tables in the database for the <table owner>
specified in the command. Substituting an empty string for the <table_name> and <table owner>
rebuilds all wide-column tables in the database.
table_owner

(Optional) Is the owner of the table. An explicit <table_owner> name is optional; the default is an empty
string. Substituting an empty string for the <table_name> rebuilds all wide-column tables in the database
for the <table_owner> specified in the command. Using an explicit <table_name> and an empty string
as the <table_owner> rebuilds the table for all users. Substituting an empty string for <table_owner>
and <table_owner> rebuilds all wide-column tables in the database.
level

(Optional) Determines how sp_iqrebuildindexwide rebuilds the table or tables. This parameter is
optional and includes four options:

● '1' – rebuilds all pre-16.1 columns wider than 255 bytes for a given user.
● '2' – rebuilds all tokenized FPs (i.e., pre-16.1 1/2/3 byte FPs, projectable 1 & 2 byte FP, and 16.1 NBit FP)
as well as VARCHAR or VARBINARY columns, and all pre-16.1 columns wider than 255 bytes.
● '3' – rebuilds all fixed Flat FPs, and all pre-16.1 columns wider than 255 bytes.
● '4' – applies levels 1, 2, 3, and rebuilds all pre- 16.0 columns wider than 255 bytes, all tokenized FPs, all
varchar and varbinary columns, and all FLAT fixed FPs.

Omitting the level parameter executes sp_iqrebuildindexwide at level '1'.

Remarks

CHAR, VARCHAR, BINARY, and VARBINARY columns wider than 255 characters, as well as all LONG VARCHAR
and LONG BINARY columns in databases migrated to SAP IQ 16.1 must be rebuilt before the database engine
can perform read/write activities on them

SAP IQ implicitly rebuilds these type of columns the first time a table is opened for read-write access.
sp_iqrebuildindexwide explicitly rebuilds these columns to the state defined by the level parameter.

sp_iqrebuildindexwide writes execution results to the SAP IQ message file (<dbname>.iqmsg)

SAP IQ SQL Reference


System Procedures INTERNAL 741
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● INSERT ANY TABLE System privilege GRANT System Privilege Statement [page 1511]

● INSERT privilege on the Object-level privilege GRANT Object-Level Privilege Statement [page 1502]
table

Side Effects

None

Examples

● In this example, the vartab table is owned by the DBA. Running this query returns the following:

select * from sp_iqrowdensity('table user1.vartab3')

DBA.vartab rid Flat style FP


DBA.vartab lvb1 Long varbinary FP
DBA.vartab blob2 Long binary FP
DBA.vartab blob1 Long binary FP
DBA.vartab vc1 Flat style FP
DBA.vartab lvc1 Long varchar FP
DBA.vartab clob2 Long binary FP
DBA.vartab clob1 Long binary FP
DBA.vartab part Flat style FP
DBA.vartab vb1 Flat style FP

Running sp_iqrebuildindexwide at level '1' with vartab as the <table_name> and DBA as the
<table_owner> rebuilds columns clob1, colb2, lvc1, lvb1, blob1, and blob2:

call sp_iqrebuildindexwide('vartab', 'DBA', 1)

It then writes the following message in .iqmsg:


Index Rebuild in progress for "DBA"."vartab" column "clob1" column "clob2"
column "lvc1" column "lvb1" column "blob1" column "blob2"
● In this example, the vartab3 table is owned by the user1. Running this query returns the following:

select * from sp_iqrowdensity('table user1.vartab3')

user1.vartab3 rid Flat style FP


user1.vartab3 part Flat style FP
user1.vartab3 vb1 Long varbinary FP

SAP IQ SQL Reference


742 INTERNAL System Procedures
user1.vartab3 tk5 Two Byte FP
user1.vartab3 tk4 One Byte FP
user1.vartab3 tk3 Three Byte FP
user1.vartab3 vc1 Long varchar FP
user1.vartab3 tk2 Projectable Two Byte FP
user1.vartab3 b1 Flat style FP
user1.vartab3 c1 Long varchar FP
user1.vartab3 tk1 Projectable One Byte FP

Running sp_iqrebuildindexwide at level '2' with vartab3 as the table_name and user1 as the
table_owner rebuilds columns vc1, vb1, c1, b1, tk1, tk2, tk3, tk4, and tk5:

sp_iqrebuildindexwide('vartab3', 'user1', 2)

The example then writes the following message in .iqmsg:


Index Rebuild in progress for "user1"."vartab3" column "vc1"
column "vb1" column "c1" column "b1" column "tk1" column "tk2" column "tk3"
column "tk4" column "tk5"
● In this example, the vartab3 table is owned by the user1. Running this query returns the following:

select * from sp_iqrowdensity('table user1.vartab3')

user1.vartab3 part Flat style FP


user1.vartab3 c1 2 Bit FP
user1.vartab3 tk4 2 Bit FP
user1.vartab3 tk5 2 Bit FP
user1.vartab3 vb1 2 Bit FP
user1.vartab3 tk3 2 Bit FP
user1.vartab3 tk2 2 Bit FP
user1.vartab3 tk1 2 Bit FP
user1.vartab3 b1 2 Bit FP
user1.vartab3 rid Flat style FP
user1.vartab3 vc1 2 Bit FP

Running sp_iqrebuildindexwide at level '3' with vartab3 as the table_name and user1 as the
table_owner rebuilds columns rid and part:

call sp_iqrebuildindexwide('vartab3', 'user1', 3)

It then writes the following message in .iqmsg:


Index Rebuild in progress for "user1"."vartab3" column "rid" column "part"
Running this statement against the rebuilt table returns the following results:

select * from sp_iqrowdensity('table user1.vartab3')

user1.vartab3 rid 2 Bit FP


user1.vartab3 vc1 2 Bit FP
user1.vartab3 vb1 2 Bit FP
user1.vartab3 b1 2 Bit FP
user1.vartab3 tk1 2 Bit FP
user1.vartab3 tk4 2 Bit FP
user1.vartab3 tk5 2 Bit FP
user1.vartab3 tk3 2 Bit FP
user1.vartab3 c1 2 Bit FP
user1.vartab3 part 2 Bit FP
user1.vartab3 tk2 2 Bit FP

SAP IQ SQL Reference


System Procedures INTERNAL 743
Related Information

sp_iqindexrebuildwidedata Procedure [page 683]


sp_iqrebuildindex Procedure [page 737]

7.5.64 sp_iqrename Procedure

Renames user-created tables, columns, indexes, constraints (unique, primary key, foreign key, and check),
stored procedures, and functions.

 Syntax

sp_iqrename <object-name>, <new-name> [, <object-type> ]

Parameters

object-name

The original name of the user-created object.

Optionally, <owner-name> can be specified as part of <object-name> as <owner-name.object-


name>, where <owner-name> is the name of the owner of the object being renamed. If <owner-name> is
not specified, the user calling sp_iqrename is assumed to be the owner of the object. The object is
successfully renamed only if the user calling sp_iqrename has the required privileges to rename the
object.

If the object to be renamed is a column, index, or constraint, you must specify the name of the table with
which the object is associated. For a column, index, or constraint, <object-name> can be of the form
<table-name.object-name> or <owner-name.table-name.object-name>.
new-name

The new name of the object. The name must conform to the rules for identifiers and must be unique for the
type of object being renamed.
object-type

(Optional) A parameter that specifies the type of the user-created object being renamed, that is, the type
of the object <object-name>. The <object-type> parameter can be specified in either upper or
lowercase.

Valid values are:

● column – object being renamed is a column.


● index – object being renamed is an index.
● constraint – object being renamed is a unique, primary key, check, or referential (foreign key)
constraint.
● procedure – object being renamed is a function.

SAP IQ SQL Reference


744 INTERNAL System Procedures
● object-type not specified – object being renamed is a table.

 Caution

The sp_iqrename procedure does not automatically update the definitions of dependent objects. You
must change these definitions manually.

Remarks

The sp_iqrename stored procedure renames user-created tables, columns, indexes, constraints (unique,
primary key, foreign key, and check), and functions.

If you attempt to rename an object with a name that is not unique for that type of object, sp_iqrename returns
the message Item already exists.

sp_iqrename does not support renaming a view, a procedure, an event or a data type, and returns the
message Feature not supported if you specify event or datatype as the <object-type> parameter.

You can also rename using the RENAME clause of the ALTER TABLE statement and ALTER INDEX statement.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure and exclusive access to any object
referenced by the procedure. See GRANT EXECUTE Privilege Statement [page 1499]. If you own the object
referenced by the procedure, no additional privilege is required.

For objects owned by others, additional privileges are needed, depending on the object type.

Privilege Name Task Allowed Privilege Type Grant Statement

ALTER ANY OBJECT Rename any object. System privileges GRANT System Privi­
lege Statement [page
ALTER ANY TABLE Rename any table, col­
1511]
umn or constraint.

ALTER ANY INDEX Rename any index, but


not tables or columns.

REFERENCES privilege Rename indexes of Object-level privileges GRANT Object-Level


on the table that table only. Privilege Statement
[page 1502]
ALTER privilege on the Rename that table, its
table columns, and con­
straints only.

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 745
Examples

● The following example renames the table titles owned by user shweta to books:

sp_iqrename shweta.titles, books

● The following example renames the column id of the table books to isbn:

sp_iqrename shweta.books.id, isbn, column

● The following example renames the index idindex on the table books to isbnindex:

sp_iqrename books.idindex, isbnindex, index

● The following example renames the primary key constraint prim_id on the table books to prim_isbn:

sp_iqrename books.prim_id, prim_isbn, constraint

Related Information

ALTER INDEX Statement [page 1147]


ALTER TABLE Statement [page 1181]
Determining the Security Model Used by a Database [page 576]

7.5.65 sp_iq_reset_identity Procedure

Sets the seed of the Identity/Autoincrement column associated with the specified table to the specified value.

 Syntax

sp_iq_reset_identity ( <table_name>, <table_owner>, <value> )

Parameters

table_name

The name of the table.

table owner

The name of the table owner.


value

The seed value you specify to replace the default seed value.

SAP IQ SQL Reference


746 INTERNAL System Procedures
Remarks

The Identity/Autoincrement column stores a number that is automatically generated. The values generated are
unique identifiers for incoming data. The values are sequential, are generated automatically, and are never
reused, even when rows are deleted from the table. The seed value specified replaces the default seed value
and persists across database shutdowns and failures.

You must specify <table_name>, <table owner>, and <value>.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● ALTER ANY TABLE System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT

● ALTER privilege on the Object-level privilege GRANT Object-Level Privilege Statement [page 1502]
table

Side Effects

None

Example

The following example creates an Identity column with a starting seed of 50:

CREATE TABLE mytable(c1 INT identity)


call sp_iq_reset_identity('mytable', 'dba', 50)

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]

SAP IQ SQL Reference


System Procedures INTERNAL 747
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iqtable Procedure [page 790]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.66 sp_iqrestoreaction Procedure

Identifies actions required to bring the database to a state consistent with a given date.

Parameters

timestamp Specifies the past date target.

Returns

Column Name Description

sequence_number Orders the steps to be taken.

backup_id Identifier for the backup transaction.

backup_archive_ List of archive files in the backup.


list

backup_time Time of the backup taken.

virtual_type Type of virtual backup:

● "Non-virtual"
● "Decoupled"
● "Encapsulated"

restore_dbspace Can be empty. Indicates that all dbspaces are to be restored from the backup archive.

restore_dbfile Could be empty. Indicates that all dbfiles in the given dbspace are to be restored from the backup
archive.

backup_comment User comment.

SAP IQ SQL Reference


748 INTERNAL System Procedures
Remarks

sp_iqrestoreaction returns an error if the database cannot be brought to a consistent state for the
timestamp. Otherwise, suggests restore actions that will return the database to a consistent state.

The common point to which the database can be restored coincides with the last backup time that backed up
read-write files just before the specified timestamp. The backup may be all-inclusive or read-write files only.

Output may not be in exact ascending order based on backup time. If a backup archive consists of multiple
read-only dbfiles, it may contain multiple rows (with the same backup time and backup id).

If you back up a read-only dbfile or dbspace multiple times, the restore uses the last backup. The
corresponding backup time could be after the specified timestamp, as long as the dbspace/dbfile alter ID
matches the dbspace/dbfile alter ID recorded in the last read-write backup that is restored.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Example

Running the procedure along with the specified timestamp returns the following output:

sp_iqrestoreaction ' 2014-03-19 14:46:50.000 '


sequence_number backup_id backup_archive_list backup_time virtual_type
restore_dbspace restore_dbfile backup_comment
--------------- --------- --------------------- ---------------------- --------------
---------------- ------------------ ---------------
1 817 //rm/db/log/bakup.dat 2014-03-19 14:44:11.0 Non virtual
(NULL) (NULL) (NULL)
2 971 //rm/db/log/bakup.dat 2014-03-19 14:46:21.0 Non virtual
(NULL) (NULL) (NULL)
3 990 //rm/db/log/bakup.dat 2014-03-19 14:46:33.0 Non virtual
(NULL) (NULL) (NULL)
4 999 //rm/db/log/bakup.dat 2014-03-19 14:46:34.0 Non virtual
(NULL) (NULL) (NULL)

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 749
7.5.67 sp_iqrlvmemory Procedure

Monitors RLV store memory usage per table.

 Syntax

sp_iqrlvmemory ( [ <table_name> [ ,<table_owner> ] ] )

Parameters

table_name

(Optional) The name of the table. If you do not specify this parameter,sp_iqrlvmemory returns
information on all RLV tables consuming memory.
table_owner

(Optional) The table owner. If you do not specify this parameter, it defaults to the current user.

Returns

sp_iqrlvmemory displays one row per table consuming RLV store memory, with the following output
columns:

Column Name Description

table_id ID of the table this row represents.

fragments Number of store fragments for this table.

total Total RLV store memory, in MB, used by this table.

data Amount of RLV store memory, in MB, used for the column fragments for this table.

dictionary Amount of RLV store memory, in MB, used for the dictionaries for this table.

bitmap Amount of RLV store memory, in MB, used to store table-level bitmaps.

ridspace_index The ridspace of the table using the RLV store memory.

transaction_id ID of the active transaction using the RLV memory.

Remarks

Version-specific data, such as version bitmaps and on-demand indexes, are not included in RLV memory
accounting. They do not count against the RLV memory limit, and are not reported in sp_iqrlvmemory.

SAP IQ SQL Reference


750 INTERNAL System Procedures
If no parameters are specified, information on all RLV tables consuming memory is returned. <table_name>,
with the additional option of <table_owner>, can be provided to restrict the output to one table. If
<table_owner> is not specified, it defaults to the current user.

Uncommitted transactions consume memory for the table. A transaction ID of 0 indicates there are no
uncommitted transaction for the table. A nonzero transaction ID indicates uncommitted transactions. In case
of large memory consumption, even after a merge, use this stored procedure in conjunction with the
sp_iqtransaction stored procedure to cross reference transaction ids to identify problematic transactions.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

This example returns the current RLV memory usage for the table rlv_table1 owned by user DBA. Note that
only the last entry contains no uncommitted transactions (transaction ID of 0):

sp_iqrlvmemory 'rlv_table1', 'DBA'

table_id fragments total data

1 778 1 1 0

2 779 1 48 48

3 785 2 1596 1584

4 791 1 48 48

dictionary bitmap ridspace_index transaction_id

1 1 0 164

0 1 1 189

SAP IQ SQL Reference


System Procedures INTERNAL 751
dictionary bitmap ridspace_index transaction_id

0 12 0 250

1 1 1 0

7.5.68 sp_iqrowdensity Procedure

Reports information about the internal row fragmentation for a table at the FP index level.

 Syntax

dbo.sp_iqrowdensity ( '<target>' )

'<target>' ::=
( table <table-name> | ( column <column-name> ( … ) )

Parameter

table-name

Reports on all columns in the named table.


column-name

Reports on the named column in the target table. You may specify multiple target columns, but must
repeat the keyword each time.

Remarks

You must specify the keywords table and column. These keywords are not case-sensitive.

sp_iqrowdensity measures row fragmentation at the default index level. Density is the ratio of the minimum
number of pages required by an index for existing table rows to the number of pages actually used by the index.
This procedure returns density as a number such that 0 < <density> < 1. For example, if an index that
requires 8 pages minimum storage occupies 10 pages, its density is .8.

The density reported does not indicate the number of disk pages that may be reclaimed by re-creating or
reorganizing the default index.

This procedure displays information about the row density of a column, but does not recommend further
action. You must determine whether or not to re-create, reorganize, or rebuild an index.

The sp_iqrowdensity IndexType column always returns the maximum number of bits required to encode the
column.

SAP IQ SQL Reference


752 INTERNAL System Procedures
Unlike the FP(1), FP(2), FP(3) dictionary compression in previous releases, which uses the same number of bits
for each page, NBit encodes each page dynamically. sp_iqrowdensity always returns the largest number of
bits used among all of the pages

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. If you own the object referenced by the procedure, no additional privilege is required.

For objects owned by others, you need one of the following privileges:

Privilege Name Privilege Type Grant Statement

● ALTER ANY INDEX System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT
● CREATE ANY INDEX
● CREATE ANY OBJECT
● MANAGE ANY DBSPACE
● MONITOR

Side Effects

None

Example

Reports the row density on column <ID> in table <SalesOrders>:

sp_iqrowdensity('column groupo.SalesOrders.ID')

Tablename ColumnName IndexType Density

GROUPO.SalesOrders ID NBit FP 1.0

Related Information

sp_iqindexfragmentation Procedure [page 674]


sp_iqrebuildindex Procedure [page 737]
Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 753
7.5.69 sp_iqsetcompression Procedure

Sets compression of data in columns of LONG BINARY (BLOB) and LONG VARCHAR (CLOB) data types.

 Syntax

sp_iqsetcompression ( <owner>, <table>, <column>, <on_off_flag> )

Parameters

owner

The owner of the table for which you are setting compression
table

The table for which you are setting compression


column

The column for which you are setting compression


on_off_flag

A compression setting:

● ON – enables compression
● OFF – disables compression

Remarks

sp_iqsetcompression provides control of compression of LONG BINARY (BLOB) and LONG VARCHAR
(CLOB) data type columns. The compression setting applies only to base tables.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● ALTER ANY TABLE System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT

SAP IQ SQL Reference


754 INTERNAL System Procedures
Side Effects

A side effect of sp_iqsetcompression is that a COMMIT occurs after you change the compression setting.

Example

Assume this table definition:

CREATE TABLE USR.pixTable (picID INT NOT NULL,


picJPG LONG BINARY NOT NULL);

To turn off compression on the LOB column picJPG, call sp_iqsetcompression:

CALL sp_iqsetcompression('USR', 'pixTable', 'picJPG',


'OFF') ;

This command returns no rows.

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.70 sp_iqsharedtempdistrib Procedure

Shows the current shared temp space usage distribution. If run from the coordinator,
sp_iqsharedtempdistrib displays shared temp space distribution for all nodes. If run from a secondary
node, displays shared temp space usage for only that node.

 Syntax

sp_iqsharedtempdistrib

Returns

Column Data Type Description

Server_id UNSIGNED BIGINT Server ID of the multiplex server, from SYSIQMPXINFO.

DBSpace_name CHAR(128) Name of the dbspace from which space is reserved.

SAP IQ SQL Reference


System Procedures INTERNAL 755
Column Data Type Description

Unit_type CHAR(10) Type of allocation unit. Valid values are:

● Active – currently reserved and in use by the node.


● Expired – reserved for the node but in transition back to the
global space pool.
● Quarantined – reserved for the node but quarantined due to
node failure.

VersionID UNSIGNED BIGINT Version ID of the unit. For active units, the version when the unit was
reserved for the node. For expired units, the version when the unit
was expired. For quarantined units, the version when the unit was
quarantined.

NBlocks UNSIGNED BIGINT Number of outstanding blocks in the unit.

Remarks

Shared temporary space is reserved for each node in the multiplex on demand. Space is reserved for a node in
an allocation unit. Nodes can have multiple allocation units reserved based on their dynamic space demands.
Allocation units are leased to allow nodes to use more space as needed and return the space to a global pool
when not needed. Allocation units expire when space usage decreases and their lease time ends, or when a
server shuts down.

Applies to multiplex only.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBSPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


756 INTERNAL System Procedures
7.5.71 sp_iqshowcompression Procedure

Displays compression settings for columns of LONG BINARY (BLOB) and LONG VARCHAR (CLOB) data types.

 Syntax

sp_iqshowcompression ( <owner>, <table>, <column> )

Parameters

owner

The owner of the table for which you are setting compression.
table

The table for which you are setting compression.


column

The column for which you are setting compression.

Returns

Returns the column name and compression setting. Compression setting values are 'ON' (compression
enabled) and 'OFF' (compression disabled).

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● ALTER ANY TABLE System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY OBJECT

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 757
Example

Assume this table definition:

CREATE TABLE USR.pixTable (picID INT NOT NULL,


picJPG LONG BINARY NOT NULL);

To check the compression status of the columns in the pixTable table, call sp_iqshowcompression:

CALL sp_iqshowcompression('USR', 'pixTable',


'picJPG') ;

This command returns one row:

'picJPG','ON'

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.72 sp_iqshowpsexe Procedure

Displays information about the settings of database options that control the priority of tasks and resource
usage for connections.

 Syntax

sp_iqshowpsexe [ <connection-id> ]

Parameters

connection-id

(Optional) An integer representing the connection ID.

If <connection-id> is specified, sp_iqshowpsexe returns information only about the specified


connection. If <connection-id> is not specified, sp_iqshowpsexe returns information about all
connections.

If the specified connection-id does not exist, sp_iqshowpsexe returns no rows.

SAP IQ SQL Reference


758 INTERNAL System Procedures
Returns

Column Name Description

connectionid The connection ID

application Information about the client application that opened the connection. Includes the AppInfo con­
nection property information:

● HOST – the host name of the client machine


● EXE – (Windows only) the name of the client executable
● APPINFO – the APPINFO in the client connection string, if specified

userid Login name of the user that opened the connection

iqgovern_priori Value of the database option IQGOVERN_PRIORITY that assigns a priority to each query wait­
ty ing in the -iqgovern queue. By default, this option has a value of 2 (MEDIUM). The values 1, 2, and 3
are shown as HIGH, MEDIUM, and LOW, respectively.

max_query_time Value of the database option MAX_QUERY_TIME that sets a limit, so that the optimizer can disal­
low very long queries. By default, this option is disabled and has a value of 0.

query_row_limit Value if the database option QUERY_ROWS_RETURNED_LIMIT that sets the row threshold for
rejecting queries based on the estimated size of the result set. The default is 0, which means there
is no limit.

query_temp_spac Value of the database option QUERY_TEMP_SPACE_LIMIT (in MB) that constrains the use of
e_limit temporary IQ dbspace by user queries. The default value is 2000 MB.

max_cursors Value of the database option MAX_CURSOR_COUNT that specifies a resource governor to limit
the maximum number of cursors a connection can use at once. The default value is 50. A value of
0 implies no limit.

max_statements Value of the database option MAX_STATEMENT_COUNT that specifies a resource governor to
limit the maximum number of prepared statements that a connection can use at once. The default
value is 100. A value of 0 implies no limit.

Remarks

The sp_iqshowpsexe stored procedure displays information about the settings of database options that
control the priority of tasks and resource usage for connections, which is useful to database administrators for
performance tuning.

 Note

The AppInfo property may not be available from Open Client or jConnect applications such as Interactive
SQL. If the AppInfo property is not available, the application column is blank.

SAP IQ SQL Reference


System Procedures INTERNAL 759
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● DROP CONNECTION System privileges GRANT System Privilege Statement [page 1511]
● MONITOR
● SERVER OPERATOR

Side Effects

None

Example

The following example displays information about the settings of database options that control the priority of
tasks and resource usage for connection ID 1:

connectionid application userid iqgovern_priority max_query_time query_row_limit


query_temp_space max_statements max_cursors
1 HOST=usia... DBA MEDIUM 0 0
0 50 100
1000000009 dbo MEDIUM 0 0
0 50 100

Related Information

CONNECTION_PROPERTY Function [System] [page 302]


sp_iqcontext Procedure [page 624]
Determining the Security Model Used by a Database [page 576]

7.5.73 sp_iqspaceinfo Procedure

Displays the number of blocks used by each object in the current database and the name of the dbspace in
which the object is located.

 Syntax

sp_iqspaceinfo ['main | [table <table-name> | index <index-name>] [...] ']

SAP IQ SQL Reference


760 INTERNAL System Procedures
Parameters

table-name

The name of the table.


index-name

The name of the index.

Remarks

For the current database, displays the object name, number of blocks used by each object, and the name of the
dbspace. sp_iqspaceinfo requires no parameters.

The information returned by sp_iqspaceinfo is helpful in managing dbspaces.

If run on a multiplex database, the default parameter is main, which returns the size of the shared IQ store.

If you supply no parameter, you must have at least one user-created object, such as a table, to receive results.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY DBSPACE System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

This output is from the sp_iqspaceinfo stored procedure run on the iqdemo database. Output for some
tables and indexes are removed from this example:

Name NBlocks dbspace_name

Contacts 19 IQ_SYSTEM_MAIN

SAP IQ SQL Reference


System Procedures INTERNAL 761
SalesOrderItems.DBA.ASIQ_IDX_T205_C5_FP 56 IQ_SYSTEM_MAIN
Contacts.DBA.ASIQ_IDX_T206_C10_FP 55 IQ_SYSTEM_MAIN
Contacts.DBA.ASIQ_IDX_T206_C1_FP 61 IQ_SYSTEM_MAIN
...
Contacts.DBA.ASIQ_IDX_T206_C9_FP 55 IQ_SYSTEM_MAIN
Contacts.DBA.ASIQ_IDX_T206_I11_HG 19 IQ_SYSTEM_MAIN
Customers 20 IQ_SYSTEM_MAIN
Customers.DBA.ASIQ_IDX_T207_C1_FP 61 IQ_SYSTEM_MAIN
Customers.DBA.ASIQ_IDX_T207_C2_FP 55 IQ_SYSTEM_MAIN
...
Customers.DBA.ASIQ_IDX_T207_I10_HG 19 IQ_SYSTEM_MAIN
...

Related Information

sp_iqindexinfo Procedure [page 676]


sp_iqdbspace Procedure [page 636]
sp_iqdbspaceinfo Procedure [page 639]
Determining the Security Model Used by a Database [page 576]

7.5.74 sp_iqspaceused Procedure

Shows information about space available and space used in the IQ store, IQ temporary store, RLV store, and IQ
global and local shared temporary stores.

 Syntax

sp_iqspaceused (out mainKB unsigned bigint,


out mainKBUsed unsigned bigint,
out tempKB unsigned bigint,
out tempKBUsed unsigned bigint,
out shTempTotalKB unsigned bigint,
out shTempTotalKBUsed unsigned bigint,
out shTempLocalKB unsigned bigint,
out shTempLocalKBUsed unsigned bigint,
out rlvLogKB unsigned bigint,
out rlvLogKBUsed unsigned bigint)

Returns

Column Name Description

mainKB The total IQ main store space, in kilobytes.

mainKBUsed The number of kilobytes of IQ main store space used by the database. Secondary multiplex nodes
return '(Null)'.

SAP IQ SQL Reference


762 INTERNAL System Procedures
Column Name Description

tempKB The total IQ temporary store space, in kilobytes.

tempKBUsed The number of kilobytes of total IQ temporary store space in use by the database.

shTempTotalKB The total IQ global shared temporary store space, in kilobytes.

shTempLocalKB The total IQ local shared temporary store space, in kilobytes.

shTempLocalKBUs The number of kilobytes of IQ local shared temporary store space in use by the database.
ed

rlvLogKB The total RLV store space, in kilobytes.

rlvLogKBUsed The number of kilobytes of RLV store space in use by the database.

Remarks

sp_iqspaceused returns several values as unsigned bigint out parameters. This system stored procedure can
be called by user-defined stored procedures to determine the amount of main, temporary, and RLV store space
in use.

sp_iqspaceused returns a subset of the information provided by sp_iqstatus, but allows the user to return
the information in SQL variables to be used in calculations.

If run on a multiplex database, this procedure applies to the server on which it runs. Also returns space used on
IQ_SHARED_TEMP.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● ALTER DATABASE System privileges GRANT System Privilege Statement [page 1511]
● MANAGE ANY DBSPACE
● MONITOR

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 763
Example

sp_iqspaceused requires seven output parameters. This example creates a user-defined stored procedure
myspace that declares the seven output parameters, then calls sp_iqspaceused:

create or replace procedure dbo.myspace()


begin
declare mt unsigned bigint;
declare mu unsigned bigint;
declare tt unsigned bigint;
declare tu unsigned bigint;
declare gt unsigned bigint;
declare gu unsigned bigint;
declare lt unsigned bigint;
declare lu unsigned bigint;
declare tt_t unsigned bigint;
declare mt_t unsigned bigint;
declare gt_t unsigned bigint;
declare lt_t unsigned bigint;
call sp_iqspaceused(mt,mu,tt,tu,gt,gu,lt,lu);
if (tt = 0) then
set tt_t = 0;
else
set tt_t = tu*100/tt;
end if;
if (mt = 0) then
set mt_t = 0;
else
set mt_t = mu*100/mt;
end if;
if (gt = 0) then
set gt_t = 0;
else
set gt_t = gu*100/gt;
end if;
if (lt = 0) then
set lt_t = 0;
else
set lt_t = lu*100/lt;
end if;
select cast(mt/1024 as unsigned bigint) as mainMB,
cast(mu/1024 as unsigned bigint) as mainusedMB, mt_t as mainPerCent,
cast(tt/1024 as unsigned bigint) as tempMB,
cast(tu/1024 as unsigned bigint) as tempusedMB, tt_t as tempPerCent,
cast(gt/1024 as unsigned bigint) as shTempTotalKB,
cast(gu/1024 as unsigned bigint) as shTempTotalKBUsed, gt_t as
globalshtempPerCent,
cast(lt/1024 as unsigned bigint) as shTempLocalMB,
cast(lu/1024 as unsigned bigint) as shTempLocalKBUsed, lt_t as
localshtempPerCent;
end

To display the output of sp_iqspaceused, execute myspace:

myspace

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


764 INTERNAL System Procedures
7.5.75 sp_iqstatistics Procedure

Returns serial number, name, description, value, and unit specifier for each available statistic, or a specified
statistic.

 Syntax

sp_iqstatistics [ <stat_name> ]

Parameter

stat_name

(Optional) A VARCHAR parameter that specifies the name of a statistic.

Returns

Column Name Data Type Description

stat_num UNSIGNED INTEGER Serial number of a statistic

stat_name VARCHAR(255) Name of statistic

stat_desc VARCHAR(255) Description of statistic

stat_value LONG VARCHAR Value of statistic

stat_unit VARCHAR(128) Unit specifier

The following statistics may be returned:

stat_num stat_name stat_desc stat_unit

0 CpuTotalTime Total CPU time in seconds consumed by the Second


SAP IQ server since last server startup

1 CpuUserTime CPU user time in seconds consumed by the SAP Second


IQ server since last server startup

2 CpuSystemTime CPU system time in seconds consumed by the Second


SAP IQ server since last server startup

3 ThreadsFree Number of SAP IQ threads free N/A

4 ThreadsInUse Number of SAP IQ threads in use N/A

5 MemoryAllocated Allocated memory in megabytes MB

6 MemoryMaxAllocated Max allocated memory in megabytes MB

7 MainCacheCurrentSize Main buffer cache current size in megabytes MB

SAP IQ SQL Reference


System Procedures INTERNAL 765
stat_num stat_name stat_desc stat_unit

8 MainCacheFinds Main buffer cache total number of lookup re­ N/A


quests

9 MainCacheHits Main buffer cache total number of hits N/A

10 MainCachePagesPinned Main buffer cache number of pages pinned Page

11 MainCachePagesPinnedPer­ Percentage of main buffer cache pages pinned %


centage

12 MainCachePagesDirtyPer­ Percentage of main buffer cache pages dirtied %


centage

13 MainCachePagesInUsePer­ Percentage of main buffer cache pages in use %


centage

14 TempCacheCurrentSize Temporary cache current size in megabytes MB

15 TempCacheFinds Temporary cache total number of lookup re­ N/A


quests

16 TempCacheHits Temporary cache total number of hits N/A

17 TempCachePagesPinned Temporary cache number of pages pinned Page

18 TempCachePagesPinnedPer­ Percentage of temporary cache pages pinned %


centage

19 TempCachePagesDirtyPer­ Percentage of temporary cache pages dirtied %


centage

20 TempCachePagesInUsePer­ Percentage of temporary cache pages in use %


centage

21 MainStoreDiskReads Number of kilobytes read from main store KB

22 MainStoreDiskWrites Number of kilobytes written to main store KB

23 TempStoreDiskReads Number of kilobytes read from main store KB

24 TempStoreDiskWrites Number of kilobytes written to main store KB

25 ConnectionsTotalConnec­ Total number of connections since server N/A


tions startup

26 ConnectionsTotalDisonnec­ Total number of disconnections since server N/A


tions startup

27 ConnectionsActive Number of active connections N/A

28 OperationsWaiting Number of operations waiting for SAP IQ re­ N/A


source governor

29 OperationsActive Number of active concurrent operations admit­ N/A


ted by SAP IQ resource governor

30 OperationsActiveLoadTa­ Number of active LOAD TABLE statements N/A


bleStatements

SAP IQ SQL Reference


766 INTERNAL System Procedures
Remarks

When stat_name is provided, sp_iqstatistics returns one row for the given statistic, or zero rows if the
name is invalid. When invoked without any parameter, sp_iqstatistics returns all statistics.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MANAGE ANY STATISTICS System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

● The following example displays a single statistic, the total CPU time:

sp_iqstatistics 'CpuTotalTime'

● The following example diplays all statistics for MainCache%:

SELECT * from sp_iqstatistics() WHERE stat_name LIKE 'MainCache%'

stat_num stat_name stat_desc stat_value stat_unit

7 MainCacheCurrentSize Cache dbspace current size in mega­ 64 mb


bytes

8 MainCacheFinds Cache dbspace total number of lookup 95303


requests

9 MainCacheHits Cache dbspace total number of hits 95283

10 MainCachePagesPinned Cache dbspace number of pages pin­ 0 page


ned

11 MainCachePagesPinnedPer­ Percentage of cache dbspace pages 0 %


centage pinned

SAP IQ SQL Reference


System Procedures INTERNAL 767
stat_num stat_name stat_desc stat_value stat_unit

12 MainCachePagesDirtyPer­ Percentage of cache dbspace pages 0.39 %


centage dirtied

13 MainCachePagesInUsePer­ Percentage of cache dbspace pages in 4.44 %


centage use

7.5.76 sp_iqstatus Procedure

Displays a variety of SAP IQ status information about the current database.

 Syntax

sp_iqstatus

Remarks

Shows status information about the current database, including the database name, creation date, page size,
number of dbspace segments, block usage, buffer usage, I/O, backup information, and so on.

sp_iqstatus displays an out-of-space status for main and temporary stores. If a store runs into an out-of-
space condition, sp_iqstatus shows Y in the store’s out-of-space status display value.

Memory used by the row-level versioning (RLV) store can be monitored with sp_iqstatus. The RLV memory
limit row displays the memory limit as specified by the -iqrlvmem server option, or the sa_server_option
rlv_memory_mb. The RLV memory used row displays the amount of memory used by the RLV store.

Memory used by direct-attached storage devices in the cache dbspace can be monitored with sp_iqstatus:

Measurement Description

Number of Cache Dbspace Files The number of cache dbspace dbfiles in the database.

Cache Dbspace Block Identifies the cache dbspace blocks and the corresponding storage device dbfile
name.

Cache Dbspace IQ Blocks Used The number of IQ blocks used, compared to the total number of IQ blocks. Usage is
also shown as a percentage. If the percentage is high, consider adding more storage.

sp_iqspaceused returns a subset of the same information as provided by sp_iqstatus, but allows the user
to return the information in SQL variables to be used in calculations.

To display space that can be reclaimed by dropping connections, use sp_iqstatus and add the results from
the two returned rows:

(DBA)> select * from sp_iqstatus() where name like '%Versions:%'


Execution time: 6.25 seconds
Name Value
----------------------------
Other Versions: 2 = 1968Mb

SAP IQ SQL Reference


768 INTERNAL System Procedures
Active Txn Versions: 1 = C:2175Mb/D:2850Mb
(First 2 rows)

The above example output shows that one active write transaction created 2175 MB and destroyed 2850 MB of
data. The total data consumed in transactions and not yet released is 4818 MB, or 1968 MB + 2850 MB = 4818
MB.

sp_iqstatus omits blocks that will be deallocated at the next checkpoint. These blocks do however, appear in
sp_iqdbspace output as type X.

In a multiplex, this procedure also lists information about the shared IQ store and IQ temporary store. If
sp_iqstatus shows a high percentage of main blocks in use on a multiplex server, run sp_iqversionuse to
see which versions are being used and the amount of space that can be recovered by releasing versions.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● ALTER DATABASE System privileges GRANT System Privilege Statement [page 1511]
● MANAGE ANY DBSPACE
● MONITOR
● SERVER OPERATOR

Side Effects

None

Example

 Note

This example includes a sample user dbspace named iq_main, which may not be present in your own
databases.

The following output is from the sp_iqstatus stored procedure:

SAP IQ (TM) Copyright (c) 1992-2016 by SAP AG or an SAP affiliate company. All rights
reserved.

SAP IQ SQL Reference


System Procedures INTERNAL 769
Version: 16.1.010.844/10172/P/Mainline/Enterprise Linux64 - x86_64 -
2.6.18-194.el5/64bit/2016-12-22 02:31:33

Time Now: 2017-01-18 20:14:57.664

Build Time: 2016-12-22 02:31:33

File Format: 23 on 03/18/1999

Server mode: IQ Server

Catalog Format: 2

Stored Procedure Revision: 1

Page Size: 131072/8192blksz/16bpp

Number of Main DB Files: 2

Main Store Out Of Space: N

Number of Cache Dbspace Files: 0

Number of Shared Temp DB Files: 0

Shared Temp Store Out Of Space: N

Number of Local Temp DB Files: 1

Local Temp Store Out Of Space: N

DB Blocks: 1-12800 IQ_SYSTEM_MAIN

DB Blocks: 1045440-1058239 iq_main

Local Temp Blocks: 1-3200 IQ_SYSTEM_TEMP

Create Time: 2017-01-18 19:09:30.231

Update Time: 2017-01-18 19:09:34.000

Main IQ Buffers: 509

Temporary IQ Buffers: 509

Main IQ Blocks Used: 5944 of 19200

Cache Dbspace IQ Blocks Used: 0 of 0

Shared Temporary IQ Blocks Used: 0 of 0

Local Temporary IQ Blocks Used: 65 of 1600

Main Reserved Blocks Available: 6400 of 6400

Shared Temporary Reserved Blocks Available: 0 of 0

Local Temporary Reserved Blocks Available: 1600 of 1600

IQ Dynamic Memory: Current: 288mb

IQ Heap Memory: Current: 150mb

Main IQ Buffers: Used: 6

Temporary IQ Buffers: Used: 4

Main IQ I/O: I: L200/P6 O: C0/D22/P20 D:0 C:100.0

Temporary IQ I/O: I: L710/P0 O: C124/D134/P13 D:120 C:100.0

SAP IQ SQL Reference


770 INTERNAL System Procedures
Other Versions: 0 = 0Mb

Active Txn Versions: 0 = C:0Mb/D:0Mb

Last Full Backup ID: 0

Last Full Backup Time:

Last Backup ID: 0

Last Backup Type: None

Last Backup Time:

DB Updated: 1

Blocks in next ISF Backup: 0 Blocks: =0Mb

Blocks in next ISI Backup: 0 Blocks: =0Mb

IQ large memory space: 2048Mb

IQ large memory flexible percentage: 50

IQ large memory flexible used: 0Mb

IQ large memory inflexible percentage: 90

IQ large memory inflexible used: 0Mb

IQ large memory anti-starvation percentage: 50

DB File Encryption Status: OFF

RLV Status: RW

RLV memory limit (mb): 2048

RLV memory used (bytes): 0

RLV Log Buffers Allocated: 0

RLV Log Buffers Globally Free: 0

RLV Log Buffers Privately Free: 0

RLV Log Buffers In Use: 0

The following is a key to understanding the Main IQ I/O and Temporary IQ I/O output codes:

● I – Input
● L – Logical pages read (“Finds”)
● P – Physical pages read
● O – Output
● C – Pages created
● D – Pages dirtied
● P – Physically written
● D – Pages destroyed
● C – Compression ratio

SAP IQ SQL Reference


System Procedures INTERNAL 771
7.5.77 sp_iqsysmon Procedure

Monitors multiple components of SAP IQ, including the management of buffer cache, memory, threads, locks,
I/O functions, and CPU utilization.

 Syntax

Batch Mode Syntax 1

sp_iqsysmon start_monitor

Batch Mode Syntax 2

sp_iqsysmon stop_monitor [, 'section(s)' ]

Batch Mode Syntax 3

sp_iqsysmon '<time-period>' [, 'section(s)' ]

File Mode Syntax

sp_iqsysmon start_monitor, 'filemode' [, '<monitor-options>' ]


sp_iqsysmon stop_monitor

Batch Mode Parameters

start_monitor

Starts monitoring.
stop_monitor

Stops monitoring and displays the report.


time-period

The time period for monitoring, in the form HH:MM:SS.


section(s)

(Optional) The abbreviation for one or more sections to be shown by sp_iqsysmon.

See the Remarks [page 774] section for a complete list of abbreviations.

If you specify more than one section, separate the section abbreviations using spaces, and enclose the list
in single or double quotes. The default is to display all sections.

For sections related to the IQ main store, you can specify main or temporary store by prefixing the section
abbreviation with 'm' or 't', respectively. Without the prefix, both stores are monitored. For example, if you
specify 'mbufman', only the IQ main store buffer manager is monitored. If you specify 'mbufman tbufman'
or 'bufman', both the main and temporary store buffer managers are monitored.

SAP IQ SQL Reference


772 INTERNAL System Procedures
File Mode Parameters

start_monitor

Starts monitoring.
stop_monitor

Stops monitoring and writes the remaining output to the log file.
filemode

Specifies that sp_iqsysmon is running in file mode. In file mode, a sample of statistics appear for every
interval in the monitoring period. By default, the output is written to a log file named <dbname.connid-
iqmon>. Use the file_suffix option to change the suffix of the output file. See the
<monitor_options> parameter for a description of the file_suffix option.
monitor_options

(Optional) The monitor_options string can include one or more options:

● -interval seconds – specifies the reporting interval, in seconds. A sample of monitor statistics is
output to the log file after every interval. The default is every 60 seconds, if the -interval option is not
specified. The minimum reporting interval is 2 seconds. If the interval specified for this option is invalid
or less than 2 seconds, the interval is set to 2 seconds.
The first display shows the counters from the start of the server. Subsequent displays show the
difference from the previous display. You can usually obtain useful results by running the monitor at
the default interval of 60 seconds during a query with performance problems or during a time of day
that generally has performance problems. A very short interval may not provide meaningful results.
The interval should be proportional to the job time; 60 seconds is usually more than enough time.
● -file_suffix suffix – creates a monitor output file named dbname.connid-suffix. If you do
not specify the -file_suffix option, the suffix defaults to iqmon. If you specify the -file_suffix option
and do not provide a suffix or provide a blank string as a suffix, no suffix is used.
● -append or -truncate – directs sp_iqsysmon to append to the existing output file or truncate the
existing output file, respectively. Truncate is the default. If both options are specified, the option
specified later in the string takes precedence.
● -section section(s) – specifies the abbreviation of one or more sections to write to the monitor
log file.
See the Remarks [page 774] section for a complete list of abbreviations.
The default is to write all sections. The abbreviations specified in the sections list in file mode are the
same abbreviations used in batch mode. When more than one section is specified, spaces must
separate the section abbreviations.
If the -section option is specified with no sections, none of the sections are monitored. An invalid
section abbreviation is ignored and a warning is written to the IQ message file.

Remarks

 Note

sp_iqsysmon does not support the SAP IQ components Disk I/O and Lock Manager .

The sp_iqsysmon procedure supports two modes of monitoring:

SAP IQ SQL Reference


System Procedures INTERNAL 773
Batch mode sp_iqsysmon collects the monitor statistics for the period between starting and
stopping the monitor or for the time period specified in the <time-period> parameter. At
the end of the monitoring period, sp_iqsysmon displays a list of consolidated statistics.

sp_iqsysmon in batch mode is similar to the SAP Adaptive Server Enterprise procedure
sp_sysmon.

File mode sp_iqsysmon writes the sample statistics in a log file for every interval period between
starting and stopping the monitor.

The first display in file mode shows the counters from the start of the server. Subsequent
displays show the difference from the previous display.

sp_iqsysmon in file mode is similar to the IQ UTILITIES command START


MONITOR and STOP MONITOR interface.

Report Sections or IQ Components to be Reported On Abbreviation to Type

Buffer allocation (main) – mbufalloc

(temporary) – tbufalloc

Buffer manager (main) – mbufman

(temporary) – tbufman

Buffer pool (main) – mbufpool

(temporary) – tbufpool

Catalog statistics catalog

CPU utilization cpu

Free list management (main) – mfreelist

(temporary) – tfreelist

Memory management memory

Prefetch management (main) – mprefetch

(temporary) – tprefetch

IQ RLV In-Memory Store statistics rlv

Large Memory Allocator (LMA) statistics lma

Server context statistics server

Thread management threads

Transaction management txn

The sp_iqsysmon stored procedure monitors multiple components of SAP IQ, including the management of
buffer cache, memory, threads, locks, I/O functions, and CPU utilization.

SAP IQ SQL Reference


774 INTERNAL System Procedures
Large Memory Allocator (LMA) Statistics
Definitions for the STATS-NAME abbreviations displayed in sp_iqsysmon output for LMA are:

STATS-NAME Definition

Large Memory Space Maximum Large Memory configured size (-iqlm value from params.cfg).

Large Memory Max Flexible Maximum memory granted for flexible operators. Example: Load Engine (hash sort
merge for hash or hash-range partitioned table and hash sort merge cursor).

Large Memory Num Flex Alloca­ The count of memory chunks allocated as flex memory.
tions

Large Memory Flexible % Percentage of large memory used for flexible operators.

Large Memory Flexible used This is the total amount of memory allocated to flex users.

Large Memory Inflexible % Percentage of large memory used for inflexible operators (N-bit metadata structures,
data buffer of column vector in load ).

Large Memory Inflexible used Large memory used by inflexible operators.

Large Memory Anti-Starvation % Applies only to flexible operators.

Large Memory Num Connections (Internal use only)

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Examples

Batch Mode
● Starts the monitor in batch mode and displays all sections for the main and temporary stores:

sp_iqsysmon start_monitor
sp_iqsysmon stop_monitor

SAP IQ SQL Reference


System Procedures INTERNAL 775
● Starts the monitor in batch mode and displays the Buffer Manager and Buffer Pool statistics for the main
store:

sp_iqsysmon start_monitor
sp_iqsysmon stop_monitor 'mbufman mbufpool'

● Prints monitor information after 10 minutes:

sp_iqsysmon '00:10:00'

● Prints only the Memory Manager section of the sp_iqsysmon report after 5 minutes:

sp_iqsysmon '00:05:00', memory

● Starts the monitor, executes two procedures and a query, stops the monitor, then prints only the Buffer
Manager section of the report:

sp_iqsysmon start_monitor
go
execute proc1
go
execute proc2
go
select sum(total_sales) from titles
go
sp_iqsysmon stop_monitor, bufman
go

● Prints only the Main Buffer Manager and Main Buffer Pool sections of the report after 2 minutes:

sp_iqsysmon '00:02:00', 'mbufman mbufpool'

● Prints only the RLV sections of the report after 1 hour:

sp_iqsysmon '01:00:00','rlv'

● Prints only the LMA sections of the report after 5 seconds:

sp_iqsysmon '00:00:05', 'lma'

● Runs the monitor in batch mode for 10 seconds and displays the consolidated statistics at the end of the
time period:

sp_iqsysmon '00:00:10', 'mbufpool memory'

File Mode
● Truncates and writes information to the log file every 2 seconds between starting the monitor and stopping
the monitor:

sp_iqsysmon start_monitor, 'filemode', '-interval 2'


.
.
.
sp_iqsysmon stop_monitor

● Appends output for only the Main Buffer Manager and Memory Manager sections to an ASCII file with the
name dbname.connid-testmon. For the database iqdemo, writes results in the file iqdemo.2-testmon:

sp_iqsysmon start_monitor, 'filemode',


'-file_suffix testmon -append -section mbufman memory'
.

SAP IQ SQL Reference


776 INTERNAL System Procedures
.
.
sp_iqsysmon stop_monitor

● Prints only the RLV and LMA sections of the report:

sp_iqsysmon start_monitor,'filemode','-section rlv lma'


sp_iqsysmon stop_monitor

● Starts the monitor in file mode and writes statistics for Main Buffer Pool and Memory Manager to the log
file every 5 seconds:

sp_iqsysmon start_monitor, 'filemode', '-interval 5 -section mbufpool memory'


sp_iqsysmon stop_monitor

In this section:

sp_iqsysmon Procedure Examples With Output [page 777]


The sp_iqsysmon examples here show output information.

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.77.1 sp_iqsysmon Procedure Examples With Output

The sp_iqsysmon examples here show output information.

Example 1

The following example displays output for the Buffer Allocation (Main and Temporary) after 20 minutes:

sp_iqsysmon '00:20:00', 'mbufalloc tbufalloc'

==============================
Buffer Allocator (Main)"
==============================
STATS-NAME VALUE
NActiveCommands 2
BufAllocMaxBufs 2275( 81.6% )
BufAllocAvailBufs 2115( 93.0% )
BufAllocReserved 160( 7.0% )
BufAllocAvailPF 750( 33.0% )
BufAllocSlots 100
BufAllocNPinUsers 0
BufAllocNPFUsers 2
BufAllocNPostedUsrs 0
BufAllocNUnpostUsrs 0
BufAllocPinQuota 0

SAP IQ SQL Reference


System Procedures INTERNAL 777
BufAllocNPostEst 0
BufAllocNUnPostEst 0
BufAllocMutexLocks 0
BufAllocMutexWaits 0( 0.0% )
STATS-NAME VALUE
NActiveCommands 2
BufAllocMaxBufs 2275( 81.6% )
BufAllocAvailBufs 2115( 93.0% )
BufAllocReserved 160( 7.0% )
BufAllocAvailPF 750( 33.0% )
BufAllocSlots 100
BufAllocNPinUsers 0
BufAllocNPFUsers 2
BufAllocNPostedUsrs 0
BufAllocNUnpostUsrs 0
BufAllocPinQuota 0
BufAllocNPostEst 0
BufAllocNUnPostEst 0
BufAllocMutexLocks 0
BufAllocMutexWaits 0( 0.0% )
STATS-NAME TOTAL UNKNWN HASH CSORT ROW ROWCOL FP GARRAY LOB
BTREE BM BV STORE TEST
NumClients 2 0 0 0 2 0 0 0 0
0 0 0 0 0
PinUserQuota 0 0 0 0 0 0 0 0 0
0 0 0 0 0
PrefetchUserQuota 160 0 0 0 160 0 0 0 0
0 0 0 0 0
PinUserRegisters 2 2 0 0 0 0 0 0 0
0 0 0 0 0
PfUserRegisters 4697 0 0 0 382 2621 377 182 0
2 0 0 0 0
ClientCountOfPinners 0 1 3 6 10 33 66 100 333 666
1000 3333 6666 10000
Unknown 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Hash 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Sort 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Row 2 0 0 0 0 0 0 0 0
0 0 0 0 0
RowColumn 0 0 0 0 0 0 0 0 0
0 0 0 0 0
FP 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Garray 0 0 0 0 0 0 0 0 0
0 0 0 0 0
LOB 0 0 0 0 0 0 0 0 0
0 0 0 0 0
BTree 0 0 0 0 0 0 0 0 0
0 0 0 0 0
BM 0 0 0 0 0 0 0 0 0
0 0 0 0 0
BV 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Store 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Test 0 0 0 0 0 0 0 0 0
0 0 0 0 0
DBCC 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Run 0 0 0 0 0 0 0 0 0
0 0 0 0 0

SAP IQ SQL Reference


778 INTERNAL System Procedures
QCPRun 0 0 0 0 0 0 0 0 0
0 0 0 0 0
TextDoc 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0 0
0 0 0 0 0
VDO 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Load Pass 2 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME (cont'd DBCC BLKMAP IQUTIL
NumClients 0 0 0 0 0 0 0 0
0 0
PinUserQuota 0 0 0 0 0 0 0 0
0 0
PrefetchUserQuota 0 0 0 0 0 0 0 0
0 0
PinUserRegisters 0 0 0 0 0 0 0 0
0 0
PfUserRegisters 0 0 0 0 0 0 0 0
1133 0
ClientCountOfPinners 33333 66666 100000 4294967295
Unknown 0 0 0 0
Hash 0 0 0 0
Sort 0 0 0 0
Row 0 0 0 0
RowColumn 0 0 0 0
FP 0 0 0 0
Garray 0 0 0 0
LOB 0 0 0 0
BTree 0 0 0 0
BM 0 0 0 0
BV 0 0 0 0
Store 0 0 0 0
Test 0 0 0 0
DBCC 0 0 0 0
Unknown 0 0 0 0
Unknown 0 0 0 0
Run 0 0 0 0
QCPRun 0 0 0 0
TextDoc 0 0 0 0
Unknown 0 0 0 0
Unknown 0 0 0 0
VDO 0 0 0 0
Load 0 0 0 0 0 0
==============================
Buffer Allocator (Temporary)
==============================
STATS-NAME VALUE
NActiveCommands 2
BufAllocMaxBufs 2275( 81.6% )
BufAllocAvailBufs 2263( 99.5% )
BufAllocReserved 12( 0.5% )
BufAllocAvailPF 908( 39.9% )
BufAllocSlots 100
BufAllocNPinUsers 2
BufAllocNPFUsers 2
BufAllocNPostedUsrs 0
BufAllocNUnpostUsrs 0
BufAllocPinQuota 175
BufAllocNPostEst 2
BufAllocNUnPostEst 2
BufAllocMutexLocks 0
BufAllocMutexWaits 0( 0.0% )
STATS-NAME TOTAL UNKNWN HASH CSORT ROW ROWCOL FP GARRAY LOB
BTREE BM BV STORE TEST

SAP IQ SQL Reference


System Procedures INTERNAL 779
NumClients 4 0 0 4 0 0 0 0
0 0 0 0 0 0
PinUserQuota 10 0 0 10 0 0 0 0
0 0 0 0 0 0
PrefetchUserQuota 2 0 0 2 0 0 0 0
0 0 0 0 0 0
PinUserRegisters 668 0 300 247 0 0 0 0
0 0 0 0 0 0
PfUserRegisters 675 0 0 295 0 0 0 0
0 0 0 0 1 0
ClientCountOfPinners 0 1 3 6 10 33 66 100 333
666 1000 3333 6666 10000
Unknown 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Hash 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Sort 2 0 1 0 1 0 0 0
0 0 0 0 0 0
Row 0 0 0 0 0 0 0 0
0 0 0 0 0 0
RowColumn 0 0 0 0 0 0 0 0
0 0 0 0 0 0
FP 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Garray 0 0 0 0 0 0 0 0
0 0 0 0 0 0
LOB 0 0 0 0 0 0 0 0
0 0 0 0 0 0
BTree 0 0 0 0 0 0 0 0
0 0 0 0 0 0
BM 0 0 0 0 0 0 0 0
0 0 0 0 0 0
BV 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Store 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Test 0 0 0 0 0 0 0 0
0 0 0 0 0 0
DBCC 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Run 0 0 0 0 0 0 0 0
0 0 0 0 0 0
QCPRun 0 0 0 0 0 0 0 0
0 0 0 0 0 0
TextDoc 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Unknown 0 0 0 0 0 0 0 0
0 0 0 0 0 0
VDO 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Load Pass 2 0 0 0 0 0 0
0 0 0 0 0 0
STATS-NAME (cont'd) DBCC BLKMAP IQUTIL
NumClients 0 0 0 0 0 0 0 0
0 0
PinUserQuota 0 0 0 0 0 0 0 0
0 0
PrefetchUserQuota 0 0 0 0 0 0 0 0
0 0
PinUserRegisters 0 0 0 110 2 0 0 0
0 9

SAP IQ SQL Reference


780 INTERNAL System Procedures
PfUserRegisters 0 0 0 378 0 0 0 1
0 0
ClientCountOfPinners 33333 66666 100000 4294967295
Unknown 0 0 0 0
Hash 0 0 0 0
Sort 0 0 0 0
Row 0 0 0 0
RowColumn 0 0 0 0
FP 0 0 0 0
Garray 0 0 0 0
LOB 0 0 0 0
BTree 0 0 0 0
BM 0 0 0 0
BV 0 0 0 0
Store 0 0 0 0
Test 0 0 0 0
DBCC 0 0 0 0
Unknown 0 0 0 0
Unknown 0 0 0 0
Run 0 0 0 0
QCPRun 0 0 0 0
TextDoc 0 0 0 0
Unknown 0 0 0 0
Unknown 0 0 0 0
VDO 0 0 0 0
Load 0 0 0 0 0 0

Example 2

The following example displays output for the Buffer Manager (Main and Temporary) after 20 minutes:

sp_iqsysmon '00:20:00', 'mbufman tbufman'

==============================
Buffer Manager (Main)
==============================
STATS-NAME TOTAL NONE TXTPOS TXTDOC CMPACT BTREEV BTREEF BV VDO
DBEXT DBID SORT STORE GARRAY
Finds 80137 0 0 0 0 9046 3307 0
20829 0 0 0 0 275
Hits 80090 0 0 0 0 9015 3291 0
20829 0 0 0 0 275
Hit% 99.9 0 0 0 0 99.7 99.5 0
100 0 0 0 0 100
FalseMiss 26469 0 0 0 0 63 40 0
1097 0 0 0 0 0
UnOwnRR 48 0 0 0 0 31 16 0
1 0 0 0 0 0
Cloned 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Creates 1557 0 0 0 0 60 179 0
256 0 0 0 0 58
Destroys 546 0 0 0 0 12 21 0
6 0 0 0 0 29
Dirties 7554 0 0 0 0 1578 585 0
0 0 0 0 0 0
RealDirties 2254 0 0 0 0 117 180 0
542 0 0 0 0 58
PrefetchReqs 80 0 0 0 0 0 0 0
74 0 0 0 0 0
PrefetchNotInMem 1 0 0 0 0 0 0 0
1 0 0 0 0 0

SAP IQ SQL Reference


System Procedures INTERNAL 781
PrefetchInMem 1466 0 0 0 0 0 0 0
1466 0 0 0 0 0
Reads 48 0 0 0 0 31 16 0
1 0 0 0 0 0
PReadBlks 114 0 0 0 0 80 32 0
2 0 0 0 0 0
PReadKB 0 0 0 0 0 0 0 0
0 0 0 0 0 0
ReReads 0 0 0 0 0 0 0 0
0 0 0 0 0 0
Writes 2002 0 0 0 0 104 163 0
538 0 0 0 0 29
PWriteBlks 6506 0 0 0 0 210 326 0
1115 0 0 0 0 58
PWriteKB 0 0 0 0 0 0 0 0
0 0 0 0 0 0
GrabbedDirty 0 0 0 0 0 0 0 0
0 0 0 0 0 0
ReadRemoteRpc 0 0 0 0 0 0 0 0
0 0 0 0 0 0
ReadRemotePhyIO 0 0 0 0 0 0 0 0
0 0 0 0 0 0
STATS-NAME (cont'd) BARRAY BLKMAP HASH CKPT BM TEST CMID RIDCA
LOB LVCRID FILE RIDMAP RVLOG
Finds 2681 8329 0 0 35670 0 0 0
0 0 0 0 0
Hits 2681 8329 0 0 35670 0 0 0
0 0 0 0 0
Hit% 100 100 0 0 100 0 0 0
0 0 0 0 0
FalseMiss 84 8329 0 0 16856 0 0 0
0 0 0 0 0
UnOwnRR 0 0 0 0 0 0 0 0
0 0 0 0 0
Cloned 0 0 0 0 0 0 0 0
0 0 0 0 0
Creates 108 358 0 0 538 0 0 0
0 0 0 0 0
Destroys 0 126 0 0 59 0 0 0
0 0 0 0 0
Dirties 512 235 0 0 4644 0 0 0
0 0 0 0 0
RealDirties 128 593 0 0 636 0 0 0
0 0 0 0 0
PrefetchReqs 6 0 0 0 0 0 0 0
0 0 0 0 0
PrefetchNotInMem 0 0 0 0 0 0 0 0
0 0 0 0 0
PrefetchInMem 0 0 0 0 0 0 0 0
0 0 0 0 0
Reads 0 0 0 0 0 0 0 0
0 0 0 0 0
PReadBlks 0 0 0 0 0 0 0 0
0 0 0 0 0
PReadKB 0 0 0 0 0 0 0 0
0 0 0 0 0
ReReads 0 0 0 0 0 0 0 0
0 0 0 0 0
Writes 128 466 0 0 574 0 0 0
0 0 0 0 0
PWriteBlks 239 3728 0 0 830 0 0 0
0 0 0 0 0
PWriteKB 0 0 0 0 0 0 0 0
0 0 0 0 0
GrabbedDirty 0 0 0 0 0 0 0 0
0 0 0 0 0
ReadRemoteRpc 0 0 0 0 0 0 0 0
0 0 0 0 0

SAP IQ SQL Reference


782 INTERNAL System Procedures
ReadRemotePhyIO 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME VALUE
BusyWaits 98
LRUNumLocks 401784
LRUNumSpinsWoTO 0 0%
LRUNumSpinLoops 4315
LRUNumTimeOuts 4315 -1.10%
BmapHTNumLocks 0
BmapHTNumWaits 0 0%
CacheTeamTimesWoken 182
CacheTeamNumAsleep 10
BmapHTMaxEntries 4096
BmapHTNEntries 27
BmapHTNInserts 31954
BmapHTNCollisn 203
BmapHTNFinds 51419
BmapHTNHits 19576
BmapHTNHits1 19550
BmapHTNHits2 26
BmapHTNClears 31933
BmapHTNLChain 1
BmapHTNRehash 0
BlockmapMutexsNLocks 0
BlockmapMutexsNWaits 0
BlockmapUID 3659
BlockmapUIDnallocs 3652
BlockmapRegEver 31851
BlockmapRegisters 31844
BufHTNBuckets 4608
BufHTNEntries 1208
BufHTNw2orMore 158
BufHTMaxBucketSize 19
BufHTNFoiledOps 0
IONumLocks 0
IONumWaits 0 0%
==============================
Buffer Manager (Temporary)
==============================
STATS-NAME TOTAL NONE TXTPOS TXTDOC CMPACT BTREEV BTREEF BV VDO DBEXT
DBID SORT STORE GARRAY
Finds 31656 0 0 0 0 0 0 0 0
0 0 1022 0 0
Hits 31655 0 0 0 0 0 0 0 0
0 0 1022 0 0
Hit% 100 0 0 0 0 0 0 0 0
0 0 100 0 0
FalseMiss 23898 0 0 0 0 0 0 0 0
0 0 0 0 0
UnOwnRR 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Cloned 0 0 0 0 0 0 0 0 0
0 0 0 0 0
Creates 5682 0 0 0 0 0 0 0 0
0 0 1048 716 0
Destroys 5670 0 0 0 0 0 0 0 0
0 0 821 17 0
Dirties 6702 0 0 0 0 0 0 0 0
0 0 379 0 0
RealDirties 5692 0 0 0 0 0 0 0 0
0 0 1048 716 0
PrefetchReqs 1 0 0 0 0 0 0 0 0
0 0 0 0 0
PrefetchNotInMem 1 0 0 0 0 0 0 0 0
0 0 0 0 0
PrefetchInMem 446 0 0 0 0 0 0 0 0
0 0 446 0 0

SAP IQ SQL Reference


System Procedures INTERNAL 783
Reads 2 0 0 0 0 0 0 0 0
0 0 0 0 0
PReadBlks 4096 0 0 0 0 0 0 0 0
0 0 0 0 0
PReadKB 0 0 0 0 0 0 0 0 0
0 0 0 0 0
ReReads 2 0 0 0 0 0 0 0 0
0 0 0 0 0
Writes 10 0 0 0 0 0 0 0 0
0 0 0 0 0
PWriteBlks 80 0 0 0 0 0 0 0 0
0 0 0 0 0
PWriteKB 0 0 0 0 0 0 0 0 0
0 0 0 0 0
GrabbedDirty 0 0 0 0 0 0 0 0 0
0 0 0 0 0
ReadRemoteRpc 0 0 0 0 0 0 0 0 0
0 0 0 0 0
ReadRemotePhyIO 0 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME (cont'd) BARRAY BLKMAP HASH CKPT BM TEST CMID RIDCA LOB
LVCRID FILE RIDMAP RVLOG
Finds 0 8569 124 0 21939 0 0 0
0 0 2 0 0
Hits 0 8569 124 0 21939 0 0 0
0 0 1 0 0
Hit% 0 100 100 0 100 0 0 0
0 0 50 0 0
FalseMiss 0 8569 0 0 15328 0 0 0
0 0 1 0 0
UnOwnRR 0 0 0 0 0 0 0 0
0 0 0 0 0
Cloned 0 0 0 0 0 0 0 0
0 0 0 0 0
Creates 0 1440 777 0 1041 0 0 0
0 0 0 660 0
Destroys 0 1434 777 0 123 0 0 0
0 0 0 660 0
Dirties 0 0 0 0 6323 0 0 0
0 0 0 0 0
RealDirties 0 1440 777 0 1051 0 0 0
0 0 0 660 0
PrefetchReqs 0 0 0 0 0 0 0 0
0 0 1 0 0
PrefetchNotInMem 0 0 0 0 0 0 0 0
0 0 1 0 0
PrefetchInMem 0 0 0 0 0 0 0 0
0 0 0 0 0
Reads 0 0 0 0 0 0 0 0
0 0 2 0 0
PReadBlks 0 0 0 0 0 0 0 0
0 0 4096 0 0
PReadKB 0 0 0 0 0 0 0 0
0 0 0 0 0
ReReads 0 0 0 0 0 0 0 0
0 0 2 0 0
Writes 0 0 0 0 10 0 0 0
0 0 0 0 0
PWriteBlks 0 0 0 0 80 0 0 0
0 0 0 0 0
PWriteKB 0 0 0 0 0 0 0 0
0 0 0 0 0
GrabbedDirty 0 0 0 0 0 0 0 0
0 0 0 0 0
ReadRemoteRpc 0 0 0 0 0 0 0 0
0 0 0 0 0
ReadRemotePhyIO 0 0 0 0 0 0 0 0
0 0 0 0 0

SAP IQ SQL Reference


784 INTERNAL System Procedures
STATS-NAME VALUE
BusyWaits 0
LRUNumLocks 136253
LRUNumSpinsWoTO 0 0%
LRUNumSpinLoops 2780
LRUNumTimeOuts 2780 -0.02%
BmapHTNumLocks 0
BmapHTNumWaits 0 0%
CacheTeamTimesWoken 1
CacheTeamNumAsleep 10
BmapHTMaxEntries 4096
BmapHTNEntries 17
BmapHTNInserts 2334
BmapHTNCollisn 0
BmapHTNFinds 183
BmapHTNHits 0
BmapHTNHits1 0
BmapHTNHits2 0
BmapHTNClears 2327
BmapHTNLChain 0
BmapHTNRehash 0
BlockmapMutexsNLocks 0
BlockmapMutexsNWaits 0
BlockmapUID 2380
BlockmapUIDnallocs 2335
BlockmapRegEver 2344
BlockmapRegisters 2334
BufHTNBuckets 4608
BufHTNEntries 24
BufHTNw2orMore 0
BufHTMaxBucketSize 3
BufHTNFoiledOps 0
IONumLocks 0
IONumWaits 0 0%

Example 3

The following example displays output for the Buffer Pool (Main and Temporary) after 20 minutes:

sp_iqsysmon '00:20:00', 'mbufpool tbufpool'

==============================
Buffer Pool (Main)
==============================

STATS-NAME TOTAL NONE TXTPOS TXTDOC CMPACT BTREEV BTREEF BV VDO


DBEXT DBID SORT STORE GARRAY
MovedToMRU 68731 0 0 0 0 9094 2767 0 21083
0 0 0 0 303
MovedToWash 0 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromLRU 67564 0 0 0 0 9020 2597 0 20830
0 0 0 0 274
RemovedFromWash 11457 0 0 0 0 1559 356 0 2189
0 0 0 0 68
RemovedInScanMode 0 0 0 0 0 0 0 0 0
0 0 0 0 0
MovedToPSList 0 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromPSList 0 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME (cont'd) BARRAY BLKMAP HASH CKPT BM TEST CMID RIDCA LOB
LVCRID FILE RIDMAP RVLOG

SAP IQ SQL Reference


System Procedures INTERNAL 785
MovedToMRU 2169 8561 0 0 24754 0 0 0
0 0 0 0 0
MovedToWash 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromLRU 2065 8330 0 0 24448 0 0 0
0 0 0 0 0
RemovedFromWash 233 1437 0 0 5615 0 0 0
0 0 0 0 0
RemovedInScanMode 0 0 0 0 0 0 0 0
0 0 0 0 0
MovedToPSList 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromPSList 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME VALUE
Pages 2787
InUse 1208 ( 43.3% )
Dirty 11 ( 0.4% )
Pinned 19 ( 0.7% )
Flushes 0
FlushedBufferCount 0
GetPageFrame 1605
GetPageFrameFailure 0
GotEmptyFrame 1605
Washed 0
TimesSweepersWoken 0
PriorityWashed 0
NPrioritySweepersWoken 0
washTeamSize 10
WashMaxSize 455 ( 16.3% )
washNBuffers 455 ( 16.3% )
washNDirtyBuffers 0 ( 0.0% )
washSignalThreshold 46 ( 1.7% )
washNActiveSweepers 0
NPriorityWashBuffers 0
NActivePrioritySweepers 0
washIntensity 0
FlushAndEmpties 0
EmptiedBufferCount 0
EmptiedSkippedCount 0
EmptiedWriteCount 0
EmptiedErrorCount 0
nAffinityTotal 0 ( 0.0% )
nAffinityArea 0 ( 0.0% )
==============================
Buffer Pool (Temporary)
==============================

STATS-NAME TOTAL NONE TXTPOS TXTDOC CMPACT BTREEV BTREEF BV VDO DBEXT
DBID SORT STORE GARRAY
MovedToMRU 30514 0 0 0 0 0 0 0 0
0 0 1218 696 0
MovedToWash 258 0 0 0 0 0 0 0 0
0 0 0 256 0
RemovedFromLRU 30506 0 0 0 0 0 0 0 0
0 0 1218 694 0
RemovedFromWash 30503 0 0 0 0 0 0 0 0
0 0 1218 694 0
RemovedInScanMode 0 0 0 0 0 0 0 0 0
0 0 0 0 0
MovedToPSList 0 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromPSList 0 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME (cont'd) BARRAY BLKMAP HASH CKPT BM TEST CMID RIDCA LOB
LVCRID FILE RIDMAP RVLOG
MovedToMRU 0 8575 124 0 19898 0 0 0
0 0 3 0 0

SAP IQ SQL Reference


786 INTERNAL System Procedures
MovedToWash 0 0 0 0 0 0 0 0
0 0 2 0 0
RemovedFromLRU 0 8569 124 0 19898 0 0 0
0 0 3 0 0
RemovedFromWash 0 8569 124 0 19898 0 0 0
0 0 0 0 0
RemovedInScanMode 0 0 0 0 0 0 0 0
0 0 0 0 0
MovedToPSList 0 0 0 0 0 0 0 0
0 0 0 0 0
RemovedFromPSList 0 0 0 0 0 0 0 0
0 0 0 0 0
STATS-NAME VALUE
Pages 2787
InUse 24 ( 0.9% )
Dirty 17 ( 0.6% )
Pinned 4 ( 0.1% )
Flushes 0
FlushedBufferCount 0
GetPageFrame 5684
GetPageFrameFailure 0
GotEmptyFrame 5684
Washed 0
TimesSweepersWoken 0
PriorityWashed 0
NPrioritySweepersWoken 0
washTeamSize 10
WashMaxSize 455 ( 16.3% )
washNBuffers 20 ( 0.7% )
washNDirtyBuffers 13 ( 0.5% )
washSignalThreshold 46 ( 1.7% )
washNActiveSweepers 0
NPriorityWashBuffers 0
NActivePrioritySweepers 0
washIntensity 0
FlushAndEmpties 0
EmptiedBufferCount 0
EmptiedSkippedCount 0
EmptiedWriteCount 0
EmptiedErrorCount 0
nAffinityTotal 0 ( 0.0% )
nAffinityArea 0 ( 0.0% )

Example 4

The following example displays output for the Prefetch Manager (Main and Temporary) after 20 minutes:

sp_iqsysmon '00:20:00', 'mprefetch tprefetch'

==============================
Prefetch Manager (Main)
==============================
STATS-NAME VALUE
PFMgrNThreads 10
PFMgrNSubmitted 81
PFMgrNDropped 0
PFMgrNValid 0
PFMgrNRead 1
PFMgrNReading 0
PFMgrCondVar Locks 0 Lock-Waits 0 ( 0.0% ) Signals 0
Broadcasts 2 Waits 2
==============================

SAP IQ SQL Reference


System Procedures INTERNAL 787
Prefetch Manager (Temporary)
==============================
STATS-NAME VALUE
PFMgrNThreads 10
PFMgrNSubmitted 1
PFMgrNDropped 0
PFMgrNValid 0
PFMgrNRead 1
PFMgrNReading 0
PFMgrCondVar Locks 0 Lock-Waits 0 ( 0.0% ) Signals 0
Broadcasts 2 Waits 2

Example 5

The following example displays output for the IQ Store Free List (Main and Temporary) after 20 minutes:

sp_iqsysmon '00:20:00', 'mfreelist tfreelist'

==============================
IQ Store (Main) Free List
==============================
STATS-NAME VALUE
FLBitCount 74036
FLIsOutOfSpace NO
FLMutexLocks 0
FLMutexWaits 0 ( 0.0% )
==============================
IQ Store (Temporary) Free List
==============================
STATS-NAME VALUE
FLBitCount 4784
FLIsOutOfSpace NO
FLMutexLocks 0
FLMutexWaits 0 ( 0.0% )

Example 6

The following example displays output for Memory Manager, Thread Manager, CPU utilization, Transaction
Manager after 20 minutes:

sp_iqsysmon '00:20:00', 'memory threads cpu txn'

==============================
Memory Manager
==============================
STATS-NAME VALUE
MemAllocated 67599536 ( 66015 KB )
MemAllocatedMax 160044816 ( 156293 KB )
MemAllocatedEver 1009672456 ( 986008 KB )
MemNAllocated 77309
MemNAllocatedEver 914028
MemNTimesLocked 0
MemNTimesWaited 0 ( 0.0 %)
==============================
Thread Manager

SAP IQ SQL Reference


788 INTERNAL System Procedures
==============================

STATS-NAME VALUE
ThrNumOfCpus 4
ThreadLimit 99
ThrNumThreads 98 ( 99.0 %)
ThrReserved 15 ( 15.2 %)
ThrNumFree 55 ( 55.6 %)
NumThrUsed 44 ( 44.4 %)
UsedPerActiveCmd 22
ThrNTeamsInUse 5
ThrMaxTeams 7
NumTeamsAlloc 238
TeamThrAlloc 421
SingleThrAlloc 492
ThrMutexLocks 0
ThrMutexWaits 0 ( 0.0 %)
==============================
CPU time statistics
==============================
STATS-NAME VALUE
Elapsed Seconds 59.65 ( 25.0 %)
CPU User Seconds 37.79 ( 15.8 %)
CPU Sys Seconds 1.89 ( 0.8 %)
CPU Total Seconds 39.68 ( 16.6 %)
==============================
Transaction Manager
==============================
STATS-NAME VALUE
TxnMgrNPending 0
TxnMgrNBlocked 2
TxnMgrNWaiting 0
TxnMgrPCcondvar Locks 0 Lock-Wait 0 ( 0.0 %) Signals
0 Broadcasts 2 Waits 2
TxnMgrTxnIDseq 407
TxnMgrtxncblock Locks 0 Lock-Wait 0 ( 0.0 %)
TxnMgrVersionID 0
TxnMgrOAVI 0
TxnMgrVersionLock Locks 0 Lock-Wait 0 ( 0.0 %) Signals
0 Broadcasts 0 Waits 0

Example 7

The following example displays output for server context and catalog statistics after 20 minutes:

sp_iqsysmon '00:20:00', 'context catalog'

==============================
Context Server statistics
==============================
STATS-NAME VALUE
StCntxNumConns 1
StCntxNResource 16
StCntxNOrigResource 18
StCntxNWaiting 0
StCntxNWaited 0
StCntxNAdmitted 1116
StCntxLock Locks 0 Lock-Waits 0 ( 0.0 %)
StCntxCondVar Locks 0 Lock-Waits 0 ( 0.0 %)
==============================
Catalog, DB Log, and Repository statistics
==============================

SAP IQ SQL Reference


System Procedures INTERNAL 789
STATS-NAME VALUE
CatalogLock RdLocks 0 RdWaits 0 ( 0.0 %) RdTryFails 0
WrLocks 30037 WrWaits 0 ( 0.0 %) WrTryFail 0
DbLogMLock Locks 0 Lock-Waits 0 ( 0.0 %)
DbLogSLock Locks 0 Lock-Waits 0 ( 0.0 %)
RepositoryNList 0
RepositoryLock Locks 1 SpinsWoTO 0 ( 0.0 %) Spins 0
TimeOuts 0 ( 0.0 %)

Example 8

The following example displays output for IQ RLV In-Memory Store and Large Memory Allocator (LMA)
statistics after 20 minutes:

sp_iqsysmon '00:20:00', 'rlv lma'

==============================
IQ In-Memory Store
==============================
STATS-NAME VALUE
RLV Memory Limit 2048 MB
RLV Memory Used 0 MB
RLV Chunks Used 0
==============================
Large Memory Allocator
==============================
STATS-NAME VALUE
Large Memory Space 2048 MB
Large Memory Max Fle 512 MB
Large Memory Num Fle 0
Large Memory Flexibl 0.5
Large Memory Flexibl 0 MB
Large Memory Inflexi 0.9
Large Memory Inflexi 0 MB
Large Memory Anti-St 0.5
Large Memory Num Con 0

7.5.78 sp_iqtable Procedure

Displays information about tables in the database.

 Syntax

Syntax 1

sp_iqtable ( [ <table_name> ] ,[ <table_owner> ] , [ <table_type> ] )

<table_name> ::=
TEMP
| VIEW
| ALL
| <any_other_value>

SAP IQ SQL Reference


790 INTERNAL System Procedures
Syntax 2

sp_iqtable [ table_name='<tablename>' ],
[ table_owner='<tableowner>' ] , [ table_type='<tabletype>' ]

Go to:

● Returns
● Remarks
● Privileges
● Side Effects
● Examples

Parameters

(back to top)

table_name or tablename

(Optional) The name of the table.


table_owner or tableowner

(Optional) The table owner.


table_type or tabletype (Optional)

● TEMP – Global temporary tables


● VIEW – Views
● ALL – IQ tables, global temporary tables, and views
● any_other_value – IQ tables

Returns

(back to top)

Specifying one parameter returns only the tables that match that parameter. Specifying more than one
parameter filters the results by all of the parameters specified. Specifying no parameters returns all SAP IQ
tables in the database. There is no method for returning the names of local temporary tables.

Column Name Description

table_name The name of the table.

SAP IQ SQL Reference


System Procedures INTERNAL 791
Column Name Description

table_type The table type:

● BASE – a base table.


● MAT VIEW – a materialized view. (SA tables only)
● GBL TEM P– a global temporary table.
● PARTITION – a table partition (this table is for internal use only and cannot be used by SAP IQ
users).
● VIEW – a view.

table_owner The owner of the table.

server_type The server type:

● IQ – an object created in the IQ store.


● SA – an object created in the SA store.

All views are created in the SA store.

location The location:

● TEMP – IQ temporary store.


● MAIN – IQ store.
● SYSTEM – catalog store.

dbspace_id Number that identifies the dbspace.

isPartitioned Partition information:

● 'Y' – if the column belongs to a partitioned table and has one or more partitions whose
dbspace is different from the table partition's dbspace
● 'N' – if the column's table is not partitioned or each partition of the column resides in the
same dbspace as the table partition.

remarks User comments added with the COMMENT statement.

table_constrain Constraints against the table.


ts

PartitionType If partitioned, indicates the type of partition:

● Hash-range
● Range
● Hash
● None

isRLV Indicates if the table is RLV-enabled.

Remarks

(back to top)

For Syntax 1, if you do not specify either of the first two parameters, but specify the next parameter in the
sequence, you must substitute NULL for the omitted parameters. For example, sp_iqtable
NULL,NULL,TEMP and sp_iqtable NULL,dbo,SYSTEM.

SAP IQ SQL Reference


792 INTERNAL System Procedures
 Note

The <table_type> values ALL and VIEW must be enclosed in single quotes in Syntax1.

For Syntax 2, the parameters can be specified in any order. Enclose them in single quotes.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

(back to top)

None

Examples

(back to top)

● The following variations in syntax both return information about the table Departments:

sp_iqtable ('Departments')

sp_iqtable table_name='Departments'

Table_name Table_type Table_owner

Departments BASE GROUPO

Server_type Location dbspace_id

IQ Main 16387

isPartitioned Remarks table_constraints

N contains the names and heads of the various departments in the (NULL)
sporting goods company

PartitionType isRlv

None F

SAP IQ SQL Reference


System Procedures INTERNAL 793
● The following variations in syntax both return all tables that are owned by table owner GROUPO:

sp_iqtable NULL,GROUPO
sp_iqtable table_owner='GROUPO'

Table_name Table_type Table_owner Server_type Location

Contacts BASE GROUPO IQ Main

Customers BASE GROUPO IQ Main

Departments BASE GROUPO IQ Main

Employees BASE GROUPO IQ Main

FinancialCodes BASE GROUPO IQ Main

FinancialData BASE GROUPO IQ Main

Products BASE GROUPO IQ Main

SalesOrders BASE GROUPO IQ Main

SalesOrderItems BASE GROUPO IQ Main

dbspace_id isPartitioned Remarks table_constraints

16387 N names, addresses, and telephone numbers of all people (NULL)


with whom the company wishes to retain contact informa­
tion

16387 N customers of the sporting goods company (NULL)

16387 N contains the names and heads of the various departments (NULL)
in the sporting goods company

16387 N contains information such as names, salary, hire date and (NULL)
birthday

16387 N types of revenue and expenses that the sporting goods (NULL)
company has

16387 N revenues and expenses of the sporting goods company (NULL)

16387 N products sold by the sporting goods company (NULL)

16387 N individual items that make up the sales orders (NULL)

16387 N sales orders that customers have submitted to the sport­ (NULL)
ing goods company

PartitionType isRlvd

None F

None F

None F

None F

None F

None F

SAP IQ SQL Reference


794 INTERNAL System Procedures
PartitionType isRlvd

None F

None F

None F

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqview Procedure [page 809]
Determining the Security Model Used by a Database [page 576]

7.5.79 sp_iqtablesize Procedure

Returns the size of the specified table.

 Syntax

sp_iqtablesize ( <table_owner>.<table_name> )

Parameters

table_owner

The owner of the table.


table_name

The name of the table.

SAP IQ SQL Reference


System Procedures INTERNAL 795
Returns

Column Name Description

Ownername The name of owner.

Tablename The name of table.

Columns The number of columns in the table.

KBytes The physical table size, in kilobytes. If you divide the KBytes value by page size, you see the aver­
age on-disk page size.

Pages The number of IQ pages needed to hold the table in memory. Pages is the total number of IQ pa­
ges for the table. The unit of measurement for pages is IQ page size. All in-memory buffers (buf­
fers in the IQ buffer cache) are the same size.

CompressedPages The number of IQ pages that are compressed, when the table is compressed (on disk). IQ pages
on disk are compressed. For example, if Pages is 1000 and CompressedPages is 992, this
means that 992 of the 1000 pages are compressed. CompressedPages divided by Pages is
usually near 100%, because most pages compress. An empty page is not compressed, since SAP
IQ does not write empty pages. IQ pages compress well, regardless of the fullness of the page.

NBlocks The number of IQ blocks. NBlocks is Kbytes divided by IQ block size. Each IQ page on disk
uses 1 to 16 blocks. If the IQ page size is 128 KB, then the IQ block size is 8 KB. In this case, an
individual on-disk page could be 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, or 128
KB.

RlvLogPages The number of IQ pages needed to hold the RLV table log information on disk.

RlvLogKBytes The size of the RLV table log, in kilobytes.

Remarks

Returns the total size of the table in KBytes and NBlocks (IQ blocks). Also returns the number of pages
required to hold the table in memory, and the number of IQ pages that are compressed when the table is
compressed (on disk). You must specify the <table_name> parameter with this procedure. If you are the
owner of <table_name>, then you do not have to specify the <table_owner> parameter.

 Note

SAP IQ always reads and writes an entire page, not blocks. For example, if an individual page compresses to
88 KB, then IQ reads and writes the 88 KB in one I/O. The average page is compressed by a factor of 2 to 3.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

SAP IQ SQL Reference


796 INTERNAL System Procedures
Privilege Name Privilege Type Grant Statement

● MANAGE ANY DBSPACE System privileges GRANT System Privilege Statement [page 1511]
● ALTER ANY TABLE
● You own the table

Side Effects

None

Example

call sp_iqtablesize ('dba.t1')

Ownername Tablename Columns

DBA t1 3

(Continued)

KBytes Pages CompressedPages

192 5 4

(Continued)

NBlocs RlvLogPages RlvLogKBytes

24 96 12288

Related Information

Determining the Security Model Used by a Database [page 576]

7.5.80 sp_iqtableuse Procedure

Reports detailed usage information for tables accessed by the workload.

 Syntax

sp_iqtableuse

SAP IQ SQL Reference


System Procedures INTERNAL 797
Returns

Column Name Description

TableName Table name.

Owner User name of table owner.

UID Table unique identifier. UID is a number assigned by the system that uniquely identifies the in­
stance of the table (where instance is defined when an object is created).

LastDT Date/time of last access.

NRef Number of query references.

Remarks

Tables created in SYSTEM are not reported.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqindexuse Procedure [page 687]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]

SAP IQ SQL Reference


798 INTERNAL System Procedures
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

7.5.81 sp_iqtransaction Procedure

Shows information about transactions and versions.

 Syntax

sp_iqtransaction

Returns

Column Name Description

Name The name of the application.

Userid The user ID for the connection.

TxnID The transaction ID of this transaction control block. The transaction ID is assigned during begin
transaction. It appears in the .iqmsg file by the BeginTxn, CmtTxn, and PostCmtTxn mes­
sages, and is the same as the Txn ID Seq that is logged when the database is opened.

CmtID The ID assigned by the transaction manager when the transaction commits. For active transac­
tions, the CmtID is zero.

VersionID For an SAP IQ server and multiplex nodes, a value of 0 indicates that the transaction is unver­
sioned, and the VersionID has not been assigned.

For the multiplex coordinator, the VersionID is assigned after the transaction establishes table
locks. Multiplex secondary servers receive the VersionID from the coordinator. The VersionID is
used internally by the SAP IQ in-memory catalog and the IQ transaction manager to uniquely iden­
tify a database version to all nodes within a multiplex database.

State The state of the transaction control block. This variable reflects internal SAP IQ implementation
details and is subject to change in the future. Currently, transaction states are NONE, ACTIVE,
ROLLING_BACK, ROLLED_BACK, COMMITTING, COMMITTED, and APPLIED.

NONE, ROLLING_BACK, ROLLED_BACK, COMMITTING and APPLIED are transient states with
a very small life span.

ACTIVE indicates that the transaction is active.

COMMITTED indicates that the transaction has completed and is waiting to be APPLIED, at
which point a version that is invisible to any transaction is subject to garbage collection.

Once the transaction state is ROLLED_BACK, COMMITTED, or APPLIED, ceases to own any
locks other than those held by open cursors.

ConnHandle The ID number of the connection.

SAP IQ SQL Reference


System Procedures INTERNAL 799
Column Name Description

IQConnID The 10-digit connection ID that is included as part of all messages in the .iqmsg file. This is a
monotonically increasing integer unique within a server session.

MainTableKBCr The number of kilobytes of IQ store space created by this transaction.

MainTableKBDr The number of kilobytes of IQ store space dropped by this transaction, but which persist on disk in
the store because the space is visible in other database versions or other savepoints of this trans­
action.

TempTableKBCr The number of kilobytes of IQ temporary store space created by this transaction for storage of IQ
temporary table data.

TempTableKBDr The number of kilobytes of IQ temporary table space dropped by this transaction, but which per­
sist on disk in the IQ temporary store because the space is visible to IQ cursors or is owned by
other savepoints of this transaction.

TempWorkSpaceKB For ACTIVE transactions, a snapshot of the work space in use at this instant by this transaction,
such as sorts, hashes, and temporary bitmaps. The number varies depending on when you run
sp_iqtransaction. For example, the query engine might create 60 MB in the temporary
cache but release most of it quickly, even though query processing continues. If you run
sp_iqtransaction after the query finishes, this column shows a much smaller number. When
the transaction is no longer active, this column is zero.

For ACTIVE transactions, this column is the same as the TempWorkSpaceKB column of
sp_iqconnection.

TxnCreateTime The time the transaction began. All SAP IQ transactions begin implicitly as soon as an active con­
nection is established or when the previous transaction commits or rolls back.

CursorCount The number of open SAP IQ cursors that reference this transaction control block. If the transac­
tion is ACTIVE, it indicates the number of open cursors created within the transaction. If the trans­
action is COMMITTED, it indicates the number of hold cursors that reference a database version
owned by this transaction control block.

SpCount The number of savepoint structures that exist within the transaction control block. Savepoints
may be created and released implicitly. Therefore, this number does not indicate the number of
user-created savepoints within the transaction.

SpNumber The active savepoint number of the transaction. This is an implementation detail and might not
reflect a user-created savepoint.

MPXServerName Indicates if an active transaction is from an internode communication (INC) connection. If from
INC connection, the value is the name of the multiplex server where the transaction originates.
NULL if not from an INC connection. Always NULL if the transaction is not active.

GlobalTxnID The global transaction ID associated with the current transaction, 0 (zero) if none.

VersioningType The snapshot versioning type of the transaction; either table-level (the default), or row-level. Row-
level snapshot versioning (RLV) applies only to RLV-enabled tables. Once a transaction is started,
this value cannot change.

Blocking Indicates if connection blocking is enabled (True) or disabled (False). You set connection blocking
using the BLOCKING database option. If true, the transaction blocks, meaning it waits for a con­
flicting lock to release before it attempts to retry the lock request.

BlockingTimeout Indicates the time, in milliseconds, a transaction waits for a locking conflict to clear. You set the
timeout threshold using the BLOCKING_TIMEOUT database option. A value of 0 (default) indi­
cates that the transaction waits indefinitely.

SAP IQ SQL Reference


800 INTERNAL System Procedures
Remarks

sp_iqtransaction returns a row for each transaction control block in the SAP IQ transaction manager. The
columns Name, Userid, and ConnHandle are the connection properties Name, Userid, and Number,
respectively. Rows are ordered by TxnID.

sp_iqtransaction output does not include connections without transactions in progress. To include all
connections, use sp_iqconnection.

 Note

Although you can use sp_iqtransaction to identify users who are blocking other users from writing to a
table, sp_iqlocks is a better choice for this purpose.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following shows sample sp_iqtransaction output:

Name Userid TxnID CmtID VersionID State ConnHandle IQConnID


====== ====== ====== ====== ========= ========== =========== ========
red2 DBA 10058 10700 10058 Active 419740283 14
MainTableKBCr MainTableKBDr TempTableKBCr TempTableKBDr
============= ================== ================ =============
0 0 65824 0
TempWorkSpaceKB TxnCreateTime CursorCount SpCount SpNumber
============== ======================= =========== ======= ========
0 2013-03-26 13:17:27.612 1 3 2
MPXServerName GlobalTxnID VersioningType Blocking BlockingTimeout
============= =========== ============== ======== ===============
(NULL) 0 Row-level True 0

SAP IQ SQL Reference


System Procedures INTERNAL 801
Related Information

sp_iqstatus Procedure
sp_iqversionuse Procedure [page 807]
Determining the Security Model Used by a Database [page 576]

7.5.82 sp_iqunusedcolumn Procedure

Reports IQ columns that were not referenced by the workload.

 Syntax

sp_iqunusedcolumn

Returns

Column Name Description

TableName Table name

ColumnName Column name

Owner User name of column owner

Remarks

Columns from tables created in SYSTEM or local temporary tables are not reported.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


802 INTERNAL System Procedures
Side Effects

None

Example

The following shows sample output from sp_iqunusedcolumn:

TableName ColumnName Owner


SalesOrders ID GROUPO
SalesOrders CustomerID GROUPO
SalesOrders OrderDate GROUPO
SalesOrders FinancialCode GROUPO
SalesOrders Region GROUPO
SalesOrders SalesRepresentative GROUPO
SalesOrderItems ID GROUPO
SalesOrderItems LineID GROUPO
SalesOrderItems ProductID GROUPO
SalesOrderItems Quantity GROUPO
SalesOrderItems ShipDate GROUPO
Contacts ID GROUPO
Contacts Surname GROUPO
Contacts GivenName GROUPO ...

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

7.5.83 sp_iqunusedindex Procedure

Reports IQ secondary (non-FP) indexes that were not referenced by the workload.

 Syntax

sp_iqunusedindex

SAP IQ SQL Reference


System Procedures INTERNAL 803
Returns

Column Name Description

IndexName Index name

TableName Table name

Owner User name of index owner

IndexType Index type

Remarks

Indexes from tables created in SYSTEM or local temporary tables are not reported.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following shows sample output from sp_iqunusedindex:

IndexName TableName Owner IndexType


ASIQ_IDX_T450_I7_HG SalesOrders GROUPO HG
ASIQ_IDX_T450_C6_HG SalesOrders GROUPO HG
ASIQ_IDX_T450_C4_HG SalesOrders GROUPO HG
ASIQ_IDX_T450_C2_HG SalesOrders GROUPO HG
ASIQ_IDX_T451_I6_HG SalesOrderItems GROUPO HG
ASIQ_IDX_T451_C3_HG SalesOrderItems GROUPO HG
ASIQ_IDX_T451_C1_HG SalesOrderItems GROUPO HG
ASIQ_IDX_T452_I11_HG Contacts GROUPO HG
ASIQ_IDX_T453_I10_HG Contacts GROUPO HG

SAP IQ SQL Reference


804 INTERNAL System Procedures
ASIQ_IDX_T454_I4_HG FinancialCodes GROUPO HG
ASIQ_IDX_T455_I5_HG FinancialData GROUPO HG
ASIQ_IDX_T455_C3_HG FinancialData GROUPO HG
ASIQ_IDX_T456_I8_HG Products GROUPO HG
ASIQ_IDX_T457_I4_HG Departments GROUPO HG
ASIQ_IDX_T457_C3_HG Departments GROUPO HG
ASIQ_IDX_T458_I21_HG Departments GROUPO HG
ASIQ_IDX_T458_C5_HG Departments GROUPO HG

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedtable Procedure [page 805]
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

7.5.84 sp_iqunusedtable Procedure

Reports IQ tables that were not referenced by the workload.

 Syntax

sp_iqunusedtable

Returns

Column Name Description

TableName Table name

Owner User name of table owner

Remarks

Tables created in SYSTEM and local temporary tables are not reported.

SAP IQ SQL Reference


System Procedures INTERNAL 805
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following table illustrates sample output from the sp_iqunusedtable procedure:

TableName Owner FinancialCodes GROUPO


Contacts GROUPO Employees GROUPO
emp1 DBA SalesOrders GROUPO
FinancialData GROUPO Departments GROUPO
SalesOrderItems GROUPO Products GROUP
iq_dummy DBA Customers GROUPO
sale DBA

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqworkmon Procedure [page 815]
Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


806 INTERNAL System Procedures
7.5.85 sp_iqversionuse Procedure

Displays version usage for the IQ main store.

 Syntax

sp_iqversionuse

Returns

Column Name Description

VersionID In SAP IQ databases, the VersionID is displayed as zero. For the multiplex coordinator, the
VersionID is the same as the TxnID of the active transaction and VersionID is the same as
the CmtID of a committed transaction. In multiplex secondary servers, the VersionID is the
CmtID of the transaction that created the database version on the multiplex coordinator. It is
used internally by the SAP IQ in-memory catalog and the SAP IQ transaction manager to uniquely
identify a database version to all nodes within a multiplex database.

Server The server to which users of this version are connected.

IQConnID The connection ID using this version.

WasReported Indicates whether the server has received usage information for this version.

MinKBRelease The minimum amount of space returned once this version is no longer in use.

MaxKBRelease The maximum amount of space returned once this version is no longer in use.

Remarks

The sp_iqversionuse system stored procedure helps troubleshoot situations where the database uses
excessive storage space due to multiple table versions.

If out-of-space conditions occur or sp_iqstatus shows a high percentage of main blocks in use on a multiplex
server, run sp_iqversionuse to find out which versions are being used and the amount of space that can be
recovered by releasing versions.

The procedure produces a row for each user of a version. Run sp_iqversionuse first on the coordinator to
determine which versions should be released and the amount of space in KB to be released when the version is
no longer in use. Connection IDs are displayed in the IQConn column for users connected to the coordinator.
Version usage due to secondary servers is displayed as the secondary server name with connection ID 0.

The amount of space is expressed as a range because the actual amount typically depends on which other
versions are released. The actual amount of space released can be anywhere between the values of
MinKBRelease and MaxKBRelease. The oldest version always has MinKBRelease equal to MaxKBRelease.

The WasReported column is used in a multiplex setting. WasReported indicates whether version usage
information has been sent from the secondary server to the coordinator. WasReported is 0 initially on a

SAP IQ SQL Reference


System Procedures INTERNAL 807
coordinator for new versions. WasReported changes to 1 once the database server replicates version usage
information back to the coordinator.

Run sp_iqversionuse on multiplex secondary servers to determine individual connections to secondary


servers. Users from other servers are not displayed on a secondary server.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

● The following displays sample output from the sp_iqversionuse system procedure:

VersionID Server IQConnID WasReported


========= ====== ======== ===========
0 ab2ab_iqdemo 9 0

MinKBRelease MaxKBRelease
============ ============
0 0

The following examples show multiplex output. The oldest version 42648 is in use by connection 108 on the
coordinator (<mpxw>). Committing or rolling back the transaction on connection 108 releases 7.9 MB of space.
Version 42686 is in use by secondary server (<mpxq>) according to output from the coordinator. Using the
secondary server output, the actual connection is connection 31. The actual amount of space returned from
releasing version 42686 depends on whether 42648 is released first.

WasReported is 0 for versions 42715 and 42728 on the coordinator because these are new versions that have
not yet been replicated. Since version 42728 does not appear on the secondary server output, it has not yet
been used by the secondary server.

● Output returned when sp_iqversionuse executes on the coordinator mpxw:

call dbo.sp_iqversionuse

SAP IQ SQL Reference


808 INTERNAL System Procedures
VersionID Server IQConn WasReported MinKBRelease MaxKBRelease

42648 'mpxw' 108 1 7920 7920

42686 'mpxq' 0 1 7920 304

42702 'mpxq' 0 1 0 688

42715 ‘mpxq' 0 0 0 688

42728 'mpxq' 0 0 0 688

● Output returned when sp_iqversionuse executes on the secondary server (mpxq):

call dbo.sp_iqversionuse

VersionID Server IQConn WasReported MinKBRelease MaxKBRelease

42686 'mpxq' 31 1 0 0

42715 'mpxq' 00 1 0 0

Related Information

sp_iqstatus Procedure
sp_iqtransaction Procedure [page 799]
Determining the Security Model Used by a Database [page 576]

7.5.86 sp_iqview Procedure

Displays information about views in a database.

 Syntax

Syntax 1

sp_iqview ( [ <view_name> ] , [ <view_owner> ] , [ view_type ] )

Syntax 2

sp_iqview [ view_name='<viewname>' ],
[ view_owner='<viewowner>' ] , [ view_type='<viewtype>' ]

Parameters

view_name (Optional) The name of the view.


view_owner (Optional) The owner of the view.

SAP IQ SQL Reference


System Procedures INTERNAL 809
view_type (Optional) The view type. Valid values are:

● SYSTEM – system views


● ALL – user and system views
● Any other value – user views

Returns

Specifying one of the parameters returns only the views with the specified view name or views that are owned
by the specified user. Specifying more than one parameter filters the results by all of the parameters specified.
Specifying no parameters returns all user views in a database.

Column Name Description

view_name The name of the view

view_owner The owner of the view

view_def The view definition as specified in the CREATE VIEW statement

remarks User comments added with the COMMENT statement

Remarks

sp_iqview returns a view definition greater than 32K characters without truncation.

Syntax 1
For Syntax 1, sp_iqview NULL,NULL,SYSTEM, if you do not specify either of the first two parameters, but do
specify the next parameter in the sequence, you must substitute NULL for the omitted parameters.

For example: sp_iqview NULL,NULL,SYSTEM and sp_iqview deptview,NULL,'ALL'.

 Note

The <view_type> value ALL must be enclosed in single quotes in Syntax 1.

Syntax 2
For Syntax 2, the parameters can be specified in any order, enclosed in single quotes.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


810 INTERNAL System Procedures
Side Effects

None

Examples

● The following variations in syntax both return information about the view deptview:

call sp_iqview('ViewSalesOrders')

sp_iqview view_name='ViewSalesOrders'

● The following variations in syntax both return all views that are owned by view owner GROUPO:

sp_iqview NULL,GROUPO

sp_iqview view_owner='GROUPO'

view_name view_owner view_def remarks

ViewSalesOrders GROUPO Create views GROUPO , ViewSalesOrders( ID, (NULL)


LineID, ProductID, Quantity, OrderDate, ShipDate,
Region, SalesRepresentativeName

Related Information

sp_iqcolumn Procedure [page 612]


sp_iqconstraint Procedure [page 622]
sp_iqdatatype Procedure [page 631]
sp_iqevent Procedure [page 656]
sp_iqhelp Procedure [page 663]
sp_iqindex and sp_iqindex_alt Procedures [page 669]
sp_iqpkeys Procedure [page 727]
sp_iqprocparm Procedure [page 732]
sp_iq_reset_identity Procedure [page 746]
sp_iqtable Procedure [page 790]
Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 811
7.5.87 sp_iqwho Procedure

Displays information about all current users and connections, or about a particular user or connection.

 Syntax

sp_iqwho [ { <connhandle> | <user-name> } [, <arg-type> ] ]

Parameters

connhandle

An integer representing the connection ID. If this parameter is specified, sp_iqwho returns information
only about the specified connection. If the specified connection is not open, no rows are displayed in the
output.
user-name

A char(255) parameter representing a user login name. If this parameter is specified, sp_iqwho returns
information only about the specified user. If the specified user has not opened any connections, no rows
are displayed in the output. If the specified user name does not exist in the database, sp_iqwho returns
the error message "User <user-name> does not exist."
arg-type

(Optional) Can be specified only when the first parameter has been specified. The only value for <arg-
type> is "user". If the <arg-type> value is specified as "user", sp_iqwho interprets the first
parameter as a user name, even if the first parameter is numeric. If any value other than "user" is
specified for <arg-type>, sp_iqwho returns the error "Invalid parameter."

Enclose the <arg-type> value in double quotes.

Returns

Column Name Description

ConnHandle The SA connection handle

IQConnID The SAP IQ specific connection ID.

Userid The name of the user that opened the connection "ConnHandle".

BlockedOn The connection on which a particular connection is blocked; 0 if not blocked on any connection.

BlockUserid The owner of the blocking connection; NULL if there is no blocking connection.

ReqType The type of the request made through the connection; DO_NOTHING if no command is issued.

IQCmdType The type of SAP IQ command issued from the connection; NONE if no command is issued.

SAP IQ SQL Reference


812 INTERNAL System Procedures
Column Name Description

IQIdle The time in seconds since the last SAP IQ command was issued through the connection; in case of
no last SAP IQ command, the time since '01-01-2000' is displayed.

SAIdle The time in seconds since the last SA request was issued through the connection; in case of no
last SA command, the time since '01-01-2000' is displayed.

IQCursors The number of active cursors in the connection; 0 if no cursors.

IQThreads The number of threads with the connection. At least one thread is started as soon as the connec­
tion is opened, so the minimum value for IQThreads is 1.

TempTableSpaceK The size of temporary table space in kilobytes; 0 if no temporary table space is used
B

TempWorkSpaceKB The size of temporary workspace in kilobytes; 0 if no temporary workspace is used

Remarks

The sp_iqwho stored procedure displays information about all current users and connections, or about a
particular user or connection.

The following lists a mapping of sp_who and sp_iqwho columns:

sp_who Column sp_iqwho Column

fid Family to which a lock belongs; omitted, as not applicable to SAP IQ

spid ConnHandle, IQConnID

status IQIdle, SAIdle

loginame Userid

origname User alias; omitted, as not applicable to SAP IQ

hostname Name of the host on which the server is running; currently not supported

blk_spid BlockedOn

dbname Omitted, as there is one server and one database for SAP IQ and they are the same for every
connection

cmd ReqType, IQCmdType

block_xloid BlockUserid

If no parameters are specified, sp_iqwho displays information about all currently active connections and
users.

Either a connection handle or a user name can be specified as the first sp_iqwho parameter. The parameters
<connhandle> and <user-name> are exclusive and optional. Only one of these parameters can be specified
at a time. By default, if the first parameter is numeric, the parameter is assumed to be a connection handle. If
the first parameter is not numeric, it is assumed to be a user name.

SAP IQ SQL Reference


System Procedures INTERNAL 813
SAP IQ allows numeric user names. The <arg-type> parameter directs sp_iqwho to interpret a numeric
value in the first parameter as a user name. For example:

sp_iqwho 1, "user"

When the <arg-type> "user" is specified, sp_iqwho interprets the first parameter 1as a user name, not as a
connection ID. If a user named 1 exists in the database, sp_iqwho displays information about connections
opened by user 1.

Syntax Output

sp_iqwho Displays all active connections

sp_iqwho 3 Displays information about connection 3

sp_iqwho "DBA" Displays connections opened by user DBA

sp_iqwho 3, "user" Interprets 3 as a user name and displays connections opened by user 3. If
user 3 does not exist, returns the error "User 3 does not exist."

sp_iqwho non-existing-user Returns error "User non-existing-user does not exist."

sp_iqwho 3, "xyz" Returns the error "Invalid parameter: xyz."

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need one of the following:

Privilege Name Privilege Type Grant Statement

● DROP CONNECTION System privileges GRANT System Privilege Statement [page 1511]
● MONITOR
● SERVER OPERATOR

Side Effects

None

Standards

The SAP IQ sp_iqwho stored procedure incorporates the SAP IQ equivalents of columns displayed by the SAP
Adaptive Server Enterprise sp_who procedure.

Some SAP ASE columns are omitted, as they are not applicable to SAP IQ.

SAP IQ SQL Reference


814 INTERNAL System Procedures
Example

The following example displays all active connections:

ConnHandle IQConnID Userid ReqType IQCmdType BlockedOn BlockUseri


d IQCursors
12 118 DBA CURSOR_OPEN IQUTILITYOPENCURSOR 0 (NULL)
0
13 119 shweta DO_NOTHING NONE 0 (NULL)
0
IQThreads IQIdle SAIdle TempTableSpaceKB TempWorkSpaceKB
1 1 0 0 0
1 16238757 470 0 0

7.5.88 sp_iqworkmon Procedure

Controls collection of workload monitor usage information, and reports monitoring collection status.
sp_iqworkmon collects information for all SQL statements.

 Syntax

sp_iqworkmon [ '<action>' ] [ , '<mode>' ]

<action> ::=
'start' , 'stop' , 'status' , 'reset'

<mode> ::=
'index' , 'table' , 'column ' , 'all'

Parameters

action

Specifies the control action to apply by using one of the following values:

● start – starts monitoring for the specified mode immediately.


● stop – stops monitoring immediately.
● status – (default) displays the current status without changing state.
● reset – clears the statistics.

The statistics are persisted until they are cleared with the reset argument, or until the server is restarted.
Statistics collection does not automatically resume after a server restart, and it needs to be restarted using
start.
mode

Specifies the type of monitoring to control. The INDEX, TABLE, and COLUMN keywords individually control
monitoring of index usage, table usage, and column usage respectively. The default ALL keyword controls
monitoring of all usage monitoring features simultaneously.

SAP IQ SQL Reference


System Procedures INTERNAL 815
Returns

Column Name Description

MonMode Table, index, or column

Status Started or stopped

Rowcount Current number of rows collected

Remarks

There is always a result set when you execute sp_iqworkmon. If you specify a specific mode (such as index),
only the row for that mode appears.

If one argument is specified, it can only be <action>. For example:

sp_iqworkmon 'stop'

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

You also need:

Privilege Name Privilege Type Grant Statement

MONITOR System privilege GRANT System Privilege Statement [page 1511]

Side Effects

None

Example

The following example displays output from the sp_iqworkmon procedure:

sp_iqworkmon 'start' , 'all'

MonMode Status Rowcount


index started 15
table started 10

SAP IQ SQL Reference


816 INTERNAL System Procedures
column started 31

Related Information

sp_iqcolumnuse Procedure [page 616]


sp_iqindexadvice Procedure [page 673]
sp_iqindexuse Procedure [page 687]
sp_iqtableuse Procedure [page 797]
sp_iqunusedcolumn Procedure [page 802]
sp_iqunusedindex Procedure [page 803]
sp_iqunusedtable Procedure [page 805]

7.5.89 sp_iqzonemapenable Procedure

Identifies columns with a ridmap version of zero (0).

 Syntax

sp_iqzonemapenable '<table_name>', '<owner>'

Returns

tablename columname indexname rebuildcommand

t1 (NULL) (NULL) List of FP indexes to be rebuilt

Remarks

If no indexes are found with a ridmap version of 0, the message "No indexes require building" is returned.
Otherwise, the syntax to rebuild each identified column is returned.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


System Procedures INTERNAL 817
Example

In this example, columns a, c, d, and f on table t1 are identified as having a ridmap version of 0 and require an
FP index rebuild to use the zone map feature.

 Sample Code

dbo.sp_iqzonemapenable 't1', 'user1'

tablename columname indexname rebuildcommand

t1 (NULL) (NULL) List of FP indexes to be rebuilt

t1 a ASIQ_IDX_T1228_C1_FP call "sp_iqrebuildindex"('USER1.t1', column a')

t1 c ASIQ_IDX_T1228_C2_FP call "sp_iqrebuildindex"('USER1.t1', column c')

t1 d ASIQ_IDX_T1228_C7_FP call "sp_iqrebuildindex"('USER1.t1', column d')

t1 f ASIQ_IDX_T1228_C8_FP call "sp_iqrebuildindex"('USER1.t1', column f')

In this example, no columns on the table t2 are identified as having a ridmap version of 0.

 Sample Code

dbo.sp_iqzonemapenable 't2', 'user2'

tablename columname indexname rebuildcommand

t2 (NULL) (NULL) List of FP indexes to be rebuilt

t2 (NULL) (NULL) No indexes require rebuilding.

7.6 Alphabetical List of Catalog Stored Procedures

Catalog store stored procedures return result sets displaying database server, database, and connection
properties in tabular form.

These procedures are owned by the dbo user ID. The PUBLIC role has EXECUTE privilege on them.

In this section:

sa_ansi_standard_packages system procedure [page 823]


Returns information about the non-core SQL extensions used in a SQL statement.

sa_audit_string system procedure [page 824]


Adds a string to the transaction log.

sa_char_terms system procedure [page 825]


Breaks a CHAR string into terms and returns each term as a row along with its position.

sa_checkpoint_execute System Procedure [page 826]

SAP IQ SQL Reference


818 INTERNAL System Procedures
Allows the execution of shell commands during a checkpoint.

sa_conn_activity system procedure [page 828]


Returns the most recently prepared SQL statement for each connection to the indicated database on
the server.

sa_conn_info system procedure [page 830]


Reports connection property information.

sa_conn_list System Procedure [page 834]


Returns a result set containing connection IDs.

sa_conn_properties system procedure [page 835]


Reports connection property information.

sa_db_info system procedure [page 837]


Reports database property information.

sa_db_option system procedure [page 839]


Overrides a database option while the database is running.

sa_db_properties system procedure [page 841]


Reports database property information.

sa_dependent_views system procedure [page 843]


Returns the list of all dependent views for a given table or view.

sa_describe_shapefile System Procedure [page 845]


Describes the names and types of columns contained in an ESRI shapefile. This system feature is for
use with the spatial data features.

sa_disable_auditing_type system procedure [page 847]


Disables auditing of specific events.

sa_disk_free_space system procedure [page 849]


Reports information about space available for a transaction log, transaction log mirror, and/or
temporary file.

sa_enable_auditing_type system procedure [page 850]


Specifies which events to include in auditing.

sa_eng_properties system procedure [page 852]


Reports database server property information.

sa_external_library_unload System Procedure [page 854]


Unloads an external library.

sa_flush_cache system procedure [page 855]


Empties all pages for the current database in the database server cache.

sa_get_ldapserver_status System Procedure [page 856]


Determines the current status of the LDAP server configuration object.

sa_get_user_status system procedure [page 857]


Allows you to determine the current status of users.

sa_http_header_info system procedure [page 859]


Returns HTTP request header names and values.

sa_list_external_library System Procedure [page 860]


Lists the external libraries currently loaded in the server.

SAP IQ SQL Reference


System Procedures INTERNAL 819
sa_list_statements system procedure [page 861]
Returns the list of statements in use by the current connection.

sa_locks System Procedure [page 863]


Displays all locks (including mutexes) in the database.

sa_make_object system procedure (deprecated) [page 866]


Ensures that a skeletal instance of an object exists before executing an ALTER statement.

sa_nchar_terms System Procedure [page 868]


Breaks an NCHAR string into terms and returns each term as a row along with its position.

sa_performance_diagnostics System Procedure [page 869]


Returns a summary of request timing information for all connections when the database server has
request timing logging enabled.

sa_procedure_profile System Procedure [page 874]


Reports information about the execution time for each line within procedures, functions, events, or
triggers that have been executed in a database.

sa_procedure_profile_summary System Procedure [page 876]


Reports summary information about the execution times for all procedures, functions, events, or
triggers that have been executed in a database.

sa_report_deadlocks System Procedure [page 879]


Retrieves information about deadlocks from an internal buffer created by the database server.

sa_rowgenerator system procedure [page 880]


Returns a result set with rows between a specified start and end value.

sa_server_option System Procedure [page 882]


Overrides a server option while the server is running.

sa_set_http_header system procedure [page 895]


Permits a web service to set an HTTP response header.

sa_set_http_option system procedure [page 897]


Permits a web service to set an HTTP option for process control.

sa_stack_trace system procedure [page 901]


Returns the stack trace leading to the current call location.

sa_table_page_usage system procedure [page 904]


Reports information about the page usage of database tables.

sa_text_index_stats System Procedure [page 905]


Returns statistical information about the TEXT indexes in the database.

sa_text_index_vocab System Procedure [page 907]


Lists all terms that appear in a TEXT index, and the total number of indexed values in which each term
appears.

sa_validate system procedure [page 909]


Validates all or parts of a database.

sa_verify_password system procedure [page 911]


Validates the password of the current user.

sp_alter_secure_feature_key System Procedure [page 913]

SAP IQ SQL Reference


820 INTERNAL System Procedures
Alters a previously-defined secure feature key by modifying the authorization key and/or the feature
list.

sp_auth_sys_role_info System Procedure [page 914]


Generates a report which maps authorities to corresponding system roles and role id. This procedure
returns a row for each authority.

sp_create_secure_feature_key System Procedure [page 914]


Creates a new secure feature key.

sp_displayroles System Procedure [page 915]


Displays all roles granted to a user-defined role or a user, or displays the entire hierarchical tree of roles.

sp_drop_secure_feature_key System Procedure [page 919]


Deletes a secure feature key.

sp_expireallpasswords System Procedure [page 920]


Immediately expires all user passwords.

sp_find_top_statements system procedure [page 920]


Reports performance statistics for each logged statement/plan combination.

sp_http_listeners system procedure [page 923]


Lists the HTTP and HTTPS connection listeners used for the specified database.

sp_list_mutexes_semaphores system procedure [page 925]


Returns information about all temporary and permanent mutexes and semaphores, including which
connection is holding each mutex and whether a semaphore is being waited for.

sp_list_secure_feature_keys System Procedure [page 927]


Returns information about the contents of a directory.

sp_login_environment system procedure [page 928]


Sets connection options when users log in.

sp_objectpermission System Procedure [page 929]


Generates a report on object privileges granted to the specified role, or user name, or the object
privileges granted on the specified object or dbspace.

sp_proc_priv System Procedure [page 932]


Generates a report of the minimum system privileges required to run a stored procedure and pass the
privilege check for the procedure.

sp_property_history system procedure [page 934]


Returns values for all database server properties tracked by the database.

sp_remote_columns system procedure [page 936]


Produces a list of the columns in a remote table, and a description of their data types.

sp_remote_exported_keys system procedure [page 938]


Provides information about tables with foreign keys on a specified primary table.

sp_remote_imported_keys system procedure [page 940]


Provides information about remote tables with primary keys that correspond to a specified foreign key.

sp_remote_primary_keys system procedure [page 942]


Provides primary key information about remote tables using remote data access.

sp_remote_tables system procedure [page 944]


Returns a list of the tables on a server.

SAP IQ SQL Reference


System Procedures INTERNAL 821
sp_servercaps system procedure [page 946]
Displays information about a remote server's capabilities.

sp_start_listener system procedure [page 947]


Starts a new connection listener.

sp_stop_listener system procedure [page 949]


Stops an existing connection listener.

sp_sys_priv_role_info System Procedure [page 950]


Generates a report to map a system privilege to the corresponding system role. A single row is returned
for each system privilege.

sp_top_k_statements system procedure [page 951]


Returns a specified number of statement/plan combinations with the highest maximum runtimes.

sp_tsql_environment system procedure [page 954]


Sets connection options when users connect from jConnect or Open Client applications.

sp_use_secure_feature_key System Procedure [page 955]


Enables an existing secure feature key.

xp_cmdshell system procedure [page 956]


Carries out an operating system command from a procedure.

xp_get_mail_error_code system procedure [page 957]


Returns information about the most recent SMTP or MAPI error.

xp_get_mail_error_text system procedure [page 958]


Returns the most recent SMTP error or status message text.

xp_getenv system procedure [page 959]


Returns the value of an environment variable.

xp_msver system procedure [page 961]


Retrieves version and name information about the database server.

xp_read_file system procedure [page 962]


Reads a file and returns the contents of the file as a LONG BINARY variable.

xp_scanf system procedure [page 963]


Extracts substrings from an input string using a format string.

xp_sendmail system procedure [page 965]


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.

xp_sprintf system procedure [page 969]


Builds a result string from a set of input strings.

xp_startmail system procedure [page 970]


Starts an email session under MAPI.

xp_startsmtp system procedure [page 971]


Starts an email session under SMTP.

xp_stopmail system procedure [page 974]


Closes a MAPI email session.

xp_stopsmtp system procedure [page 975]


Closes an SMTP email session.

SAP IQ SQL Reference


822 INTERNAL System Procedures
xp_write_file system procedure [page 976]
Writes data to a file from a SQL statement.

7.6.1 sa_ansi_standard_packages system procedure

Returns information about the non-core SQL extensions used in a SQL statement.

 Syntax

sa_ansi_standard_packages(
<standard>
, <statement>
)

Parameters

standard

Use this LONG VARCHAR parameter to specify the standard to use for the core extensions. One of SQL:
1999 or SQL:2003.
statement

Use this LONG VARCHAR parameter to specify the SQL statement to evaluate.

Result set

Column name Data type Description

package_id VARCHAR(10) The feature identifier.

package_name LONG VARCHAR The feature name.

Remarks

If there are no non-core extensions used for the statement, the result set is empty.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 823
Side effects

None

7.6.2 sa_audit_string system procedure

Adds a string to the transaction log.

 Syntax

sa_audit_string( <string> )

Parameters

string

The VARCHAR(128) 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 128 characters.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the MANAGE AUDITING system
privilege.

Side effects

None

 Example

The following example uses sa_audit_string to add a comment to the transaction log:

CALL sa_audit_string( 'Auditing test' );

SAP IQ SQL Reference


824 INTERNAL System Procedures
Related Information

Determining the Security Model Used by a Database [page 576]

7.6.3 sa_char_terms system procedure

Breaks a CHAR string into terms and returns each term as a row along with its position.

 Syntax

sa_char_terms(
<text>
[, <config_name>
[, <owner> ] ]
)

Parameters

text

The LONG VARCHAR string you are parsing.


config_name

Use this optional CHAR(128) parameter to specify the text configuration object to apply when processing
the string. The default value is 'default_char'.
owner

Use this optional CHAR(128) parameter to specify the owner of the text configuration object. The default
value is NULL. 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.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 825
Side effects

None

 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

7.6.4 sa_checkpoint_execute System Procedure

Allows the execution of shell commands during a checkpoint.

 Syntax

sa_checkpoint_execute '<shell_commands>'

Parameters

shell_commands

One or more user commands to be executed in a system shell. The shell commands are specific to the
system shell. Commands are separated by a semicolon (;).

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have one of the following system privileges:

SAP IQ SQL Reference


826 INTERNAL System Procedures
● CHECKPOINT
● MANAGE ANY MIRROR SERVER

Remarks

Allows users to execute shell commands to copy a running database from the middle of a checkpoint
operation, when the server is quiescent. The copied database can be started and goes through normal
recovery, similar to recovery following a system failure.

sa_checkpoint_execute initiates a checkpoint, and then executes a system shell from the middle of the
checkpoint, passing the user commands to the shell. The server then waits for the shell to complete, creating
an arbitrary size time window during which to copy database files. Most database activity stops while the
checkpoint is executing, so the duration of the shell commands should be limited to acceptable user response
time.

If the shell commands return a nonzero status, sa_checkpoint_execute returns an error.

Do not use the sa_checkpoint_execute with interactive commands, as the server must wait until the
interactive command is killed. Supply override flags to disable prompting for any shell commands that might
become interactive; in other words, the COPY, MOVE, and DELETE commands might prompt for confirmation.

The intended use of sa_checkpoint_execute is with disk mirroring, to split mirrored devices.

When using sa_checkpoint_execute to copy iqdemo.* files to another directory, all files are copied except
the .db and .log files. Error -910 is returned.

This error not a product defect but a Windows limitation; the Windows copy command cannot copy catalog
files while they are open by the database.

Side Effects

None

Example

Assuming you have created a subdirectory named backup, the following statement issues a checkpoint,
copies all of the iqdemo database files to the backup subdirectory, and completes the checkpoint:

sa_checkpoint_execute 'cp iqdemo.* backup/'

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 827
7.6.5 sa_conn_activity system procedure

Returns the most recently prepared SQL statement for each connection to the indicated database on the
server.

 Syntax

sa_conn_activity( [ <connidparm> ] )

Parameters

connidparm

Use this optional INTEGER parameter to specify the connection ID number. The default is NULL.

Result set

Column name Data type Description

Number INTEGER Returns the connection ID (a number)


for the current connection.

Name VARCHAR(255) Returns the name of the current con­


nection.

Temporary connection names have


INT: prepended to the connection
name.

Userid VARCHAR(255) Returns the user ID for the connection.

DBNumber INTEGER Returns the ID number of the database.

LastReqTime VARCHAR(255) Returns the time at which the last re­


quest for the specified connection
started. This property can return an
empty string for internal connections,
such as events.

LastStatement LONG VARCHAR Returns the most recently prepared


SQL statement for the current connec­
tion.

SAP IQ SQL Reference


828 INTERNAL System Procedures
Remarks

If <connidparm> is less than zero, then information for the current connection is returned. If <connidparm>
is not supplied or is NULL, then information is returned for all connections to all databases running on the
database server.

The sa_conn_activity system procedure returns a result set consisting of the most recently prepared SQL
statement for the connection. 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.

Privileges

You must have EXECUTE privilege on the system procedure.

To obtain a list of all connection IDs, you must also have either the SERVER OPERATOR, MONITOR, or DROP
CONNECTION system privilege.

Side effects

None

 Example

The following example uses the sa_conn_activity system procedure to display the most recently prepared
SQL statement for each connection.

CALL sa_conn_activity( );

Number Name Userid DBNumber ...

1,949 SQL_DBC_117acc40 DBA 0 ...

1,948 setup User1 0 ...

... ... ... ... ...

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 829
7.6.6 sa_conn_info system procedure

Reports connection property information.

 Syntax

sa_conn_info( [ <connidparm> ] )

Parameters

connidparm

This optional INTEGER parameter specifies the connection ID number. The default is NULL.

Result set

Column name Data type Description

Number INTEGER Returns the connection ID (a number)


for the current connection.

Name VARCHAR(255) Returns an identifier (string) for the


current connection.

Temporary connection names have


INT: prepended to the connection
name.

Userid VARCHAR(255) Returns the user ID for the connection.

DBNumber INTEGER Returns the ID number of the database.

LastReqTime VARCHAR(255) Returns the time at which the last re­


quest for the specified connection
started, in the timezone of the data­
base. This property can return an
empty string for internal connections,
such as events.

ReqType VARCHAR(255) Returns the type of the last request. If a


connection has been cached by con­
nection pooling, its ReqType value is
CONNECT_POOL_CACHE.

SAP IQ SQL Reference


830 INTERNAL System Procedures
Column name Data type Description

CommLink VARCHAR(255) Returns the communication link for the


connection. This is one of the network
protocols supported by SAP IQ, or local
for a same-computer connection.

NodeAddr VARCHAR(255) Returns the address of the client in a


client/server connection.

ClientPort INTEGER Returns the client's TCP/IP port num­


ber or 0 if the connection isn't a TCP/IP
connection.

ServerPort INTEGER Returns the database server's TCP/IP


port number or 0.

BlockedOn INTEGER Returns zero if the current connection


isn't blocked, or if it is blocked, the con­
nection number on which the connec­
tion is blocked because of a locking
conflict.

LockRowID UNSIGNED BIGINT Returns the identifier of the locked row.

LockRowID is NULL if the connection is


not waiting on a lock associated with a
row (that is, it is not waiting on a lock,
or it is waiting on a lock that has no as­
sociated row).

LockIndexID INTEGER Returns the identifier of the locked in­


dex.

LockIndexID is -1 if the lock is associ­


ated with all indexes on the table in
LockTable. LockIndexID is NULL if the
connection is not waiting on a lock as­
sociated with an index (that is, it is not
waiting on a lock, or it is waiting on a
lock that has no associated index).

LockTable VARCHAR(255) Returns the name of the table associ­


ated with a lock if the connection is cur­
rently waiting for a lock. The LockTable
value is an empty string if there is no
lock, or if the object associated with the
lock is not a table.

UncommitOps INTEGER Returns the number of uncommitted


operations.

SAP IQ SQL Reference


System Procedures INTERNAL 831
Column name Data type Description

ParentConnection INTEGER Returns the connection ID of the con­


nection that created a temporary con­
nection to perform a database opera­
tion (such as performing a backup or
creating a database). For other types of
connections, this property returns
NULL.

LockObject VARCHAR(255) Returns the name of the object associ­


ated with the lock for which the connec­
tion is waiting, if any. If the object is a
table, this value is the same as the
LockTable value. LockObject is NULL if
the connection is not waiting for a lock.

LockObjectType CHAR(20) Returns the type of the object associ­


ated with the lock for which the connec­
tion is waiting, if any. LockObjectType is
NULL if the connection is not waiting
for a lock.

Remarks

If <connidparm> is less than zero, then a result set consisting of connection properties for the current
connection is returned. If <connidparm> is not supplied or is NULL, then connection properties are returned
for all connections to all databases running on the database server.

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.

SAP IQ SQL Reference


832 INTERNAL System Procedures
Privileges

You must have EXECUTE privilege on the system procedure.

To obtain a list of all connection IDs, you must also have either the SERVER OPERATOR, MONITOR, or DROP
CONNECTION system privilege.

Side effects

None

 Example

The following example uses the sa_conn_info system procedure to return a result set summarizing
connection properties for all connections to the server.

CALL sa_conn_info( );

Number Name Userid DBNumber ...

79 SQL_DBC_10dcf810 DBA 0 ...

46 setup User1 0 ...

... ... ... ... ...

The following example uses the sa_conn_info system procedure to return a result set showing which
connection created a temporary connection.

SELECT Number, Name, ParentConnection FROM sa_conn_info();

Connection 8 created the temporary connection that executed a CREATE DATABASE statement.

Number Name ParentConnection


------------------------------------------------
1000000048 INT: CreateDB 8
9 SQL_DBC_14675af8 (NULL)
8 SQL_DBA_152d5ac0 (NULL)

The following example uses the sa_conn_info system to return the number of blocked connections.

SELECT COUNT(*) FROM sa_conn_info()


WHERE blockedOn = connection_property('number');

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 833
7.6.7 sa_conn_list System Procedure

Returns a result set containing connection IDs.

 Syntax

sa_conn_list ( [ <connidparm> ] [ ,<dbidparm> ] )

Parameters

connidparm

(Optional) An INTEGER parameter that specifies the connection ID number.


dbidparm

(Optional) An INTEGER parameter that specifies the database ID number.

Result Set

Column Name Data Type Description

Number INTEGER The connection ID number.

Remarks

If <connidparm> is greater than zero, then information for the supplied connection is returned. If
<connidparm> is less than zero, then information for the current connection is returned. If <connidparm>
and <dbidparm> are not supplied or are NULL, then connection IDs for all connections to all databases
running on the database server are returned.

If <connidparm> is NULL and <dbidparm> is greater than or equal to zero, then connection IDs for only that
database are returned. If <connidparm> is NULL and <dbidparm> is less than zero, then connection IDs for
just the current database are returned.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have one of the following system privileges:

● SERVER OPERATOR

SAP IQ SQL Reference


834 INTERNAL System Procedures
● MONITOR
● DROP CONNECTION

Side Effects

None

Example

The following example uses the sa_conn_list system procedure to display a list of connection IDs:

CALL sa_conn_list( );

Number

1,949

1,948

...

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.8 sa_conn_properties system procedure

Reports connection property information.

 Syntax

sa_conn_properties( [ <connidparm> ] )

Parameters

connidparm

Use this optional INTEGER parameter to specify the connection ID number. The default is NULL.

SAP IQ SQL Reference


System Procedures INTERNAL 835
Result set

Column name Data type Description

Number INTEGER Returns the connection ID (a number)


for the current connection.

PropNum INTEGER Returns the connection property num­


ber.

PropName VARCHAR(255) Returns the connection property name.

PropDescription VARCHAR(255) Returns the connection property de­


scription.

Value LONG VARCHAR Returns the connection property value.

Remarks

Returns the connection ID as Number, and the PropNum, PropName, PropDescription, and Value for each
available connection property. Values are returned for all connection properties, database option settings
related to connections, and statistics related to connections. Valid properties with NULL values are also
returned.

If <connidparm> is less than zero, then property values for the current connection are returned. If
<connidparm> is not supplied or is NULL, then property values are returned for all connections to the current
database.

Privileges

You must have EXECUTE privilege on the system procedure.

To obtain a list of all connection IDs, you must also have either the SERVER OPERATOR, MONITOR, or DROP
CONNECTION system privilege.

Side effects

None

 Example

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( );

SAP IQ SQL Reference


836 INTERNAL System Procedures
Number PropNum PropName ...

79 37 ClientStmtCacheHits ...

79 38 ClientStmtCacheMisses ...

... ... ... ...

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;

7.6.9 sa_db_info system procedure

Reports database property information.

 Syntax

sa_db_info( [ <dbidparm> ] )

Parameters

dbidparm

Use this optional INTEGER parameter to specify the database ID number. The default is NULL.

Result set

Column name Data type Description

Number INTEGER Returns the connection ID (a number)


for the current connection.

Alias VARCHAR(255) Returns the database name.

File VARCHAR(255) Returns the file name of the database


root file, including path.

SAP IQ SQL Reference


System Procedures INTERNAL 837
Column name Data type Description

ConnCount INTEGER Returns the number of connections to


the database. The property value does
not include connections used for inter­
nal operations, but it does include con­
nections used for events and external
environment support.

PageSize INTEGER Returns the page size of the database,


in bytes.

LogName VARCHAR(255) Returns the file name of the transaction


log, including path.

Remarks

If you specify a database ID, sa_db_info returns a single row containing the Number, Alias, File, ConnCount,
PageSize, and LogName for the specified database.

If <dbidparm> is greater than zero, then properties for the supplied database are returned. If <dbidparm> is
less than zero, then properties for the current database are returned. If <dbidparm> is not supplied or is NULL,
then properties for all databases running on the database server are returned.

Privileges

You must have EXECUTE privilege on the system procedure.

To execute this system procedure for other databases, you must also have either the SERVER OPERATOR or
MONITOR system privilege.

Side effects

None

 Example

The following statement returns a row for each database that is running on the server:

CALL sa_db_info( );

SAP IQ SQL Reference


838 INTERNAL System Procedures
Related Information

Determining the Security Model Used by a Database [page 576]

7.6.10 sa_db_option system procedure

Overrides a database option while the database is running.

 Syntax

sa_db_option(
<opt>
, <val>
)

Parameters

opt

Use this CHAR(128) parameter to specify a database option name.


val

Use this LONG VARCHAR parameter to specify the new value for the database option.

Remarks

Database administrators can use this procedure to override some database options temporarily, without
restarting the database.

The option values that are changed using this procedure are reset to their default values when the database
shuts down. To change an option value every time the database is started, specify the corresponding database
option when the database is started (if one exists).

SAP IQ SQL Reference


System Procedures INTERNAL 839
The following option settings can be changed:

Option name Values System privilege Additional information

DiskSandbox ON, OFF SERVER OPERATOR When DiskSandbox is set to


ON, it restricts read-write file
operations on the database
to the directory where the
main database file is located
and any subdirectories of
this directory. To use the
sa_db_option system proce­
dure to change disk sandbox
settings, you must provide
the secured feature key for
the manage_disk_sandbox
feature.

PropertyHistoryList comma-delimited list of data­ MANAGE PROPERTY HIS­ When PropertyHistoryList is


base server properties TORY
turned on, a default list of
properties is selected. You
can specify a comma-delim­
ited list of database server
properties to track. The de­
fault is an empty list.

If this option is not set then


only properties tracked by
the database server or by
other databases on the same
database server can be quer­
ied.

If the memory required to


track all specified properties
is greater than the limit set
by the PropertyHistorySize
database server option or by
the available memory, then
an error is raised and the
property list is not modified
for the database.

CollectStmtPerfStats ON, OFF MONITOR When CollectStmtPerfStats


is set to ON, it collects state­
ment performance summary
information. When it is set to
OFF, it stops data collection
and discards data that has
been collected.

SAP IQ SQL Reference


840 INTERNAL System Procedures
Privileges

You must have EXECUTE privilege on the system procedure, as well as the SERVER OPERATOR system
privilege.

Side effects

None.

 Example

For the following example to work, the database server must be started with the option -sk securefkey.

This example enables the SYSTEM secured feature key that includes MANAGE_KEYS, creates a new
secured feature key called SECURITY with case-sensitive authorization code NewSecurityCode, and then
uses the new secured feature key to enable the DiskSandbox option.

CALL sp_use_secure_feature_key( 'system', 'securefkey' );


CALL sp_create_secure_feature_key( 'security', 'NewSecurityCode',
'manage_security' );
CALL sp_use_secure_feature_key( 'security', 'NewSecurityCode' );
CALL sa_db_option( 'DiskSandbox', 'on' );

7.6.11 sa_db_properties system procedure

Reports database property information.

 Syntax

sa_db_properties( [ <dbidparm> ] )

Parameters

dbidparm

Use this optional INTEGER parameter to specify the database ID number. The default is NULL.

SAP IQ SQL Reference


System Procedures INTERNAL 841
Result set

Column name Data type Description

Number INTEGER The database ID number.

PropNum INTEGER The database property number.

PropName VARCHAR(255) The database property name.

PropDescription VARCHAR(255) The database property description.

Value LONG VARCHAR The database property value.

Remarks

If you specify a database ID, the sa_db_properties system procedure returns the database ID number and the
PropNum, PropName, PropDescription, and Value for each available database property. Values are returned for
all database properties and statistics related to databases. Valid properties with NULL values are also returned.

If <dbidparm> is greater than zero, then database properties for the supplied database are returned. If
<dbidparm> is less than zero, then database properties for the current database are returned. If <dbidparm>
is not supplied or is NULL, then database properties for all databases running on the database server are
returned.

Privileges

You must have EXECUTE privilege on the system procedure.

To execute this system procedure for other databases, you must also have either the SERVER OPERATOR or
MONITOR system privilege.

Side effects

None

 Example

The following example uses the sa_db_properties system procedure to return a result set summarizing
database properties for all databases when the invoker has SERVER OPERATOR or MONITOR system
privilege. Otherwise, database properties for the current database are returned.

CALL sa_db_properties( );

SAP IQ SQL Reference


842 INTERNAL System Procedures
Number PropNum PropName ...

0 0 ConnCount ...

0 1 IdleCheck ...

0 2 IdleWrite ...

... ... ... ...

The following example uses the sa_db_properties system procedure to return a result set summarizing
database properties for a second database.

CALL sa_db_properties( 1 );

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.12 sa_dependent_views system procedure

Returns the list of all dependent views for a given table or view.

 Syntax

sa_dependent_views(
[ <tbl_name>
[, <owner_name> ] ]
)

Parameters

tbl_name

Use this optional CHAR(128) parameter to specify the name of the table or view. The default is NULL.
owner_name

Use this optional CHAR(128) parameter to specify the owner for <tbl_name>. The default is NULL.

SAP IQ SQL Reference


System Procedures INTERNAL 843
Result set

Column name Data type Description

table_id UNSIGNED INTEGER The object ID of the table or view.

dep_view_id UNSIGNED INTEGER The object ID of the dependent views.

Remarks

Use this procedure to obtain the list of IDs of tables and their dependent views.

No errors are generated if no existing tables satisfy the specified criteria for table and owner names. The
following conditions also apply:

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

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

In this example, the sa_dependent_views system procedure is used to obtain the list of IDs for the views
that are dependent on the SalesOrders table. The procedure returns the table_id for SalesOrders, and the
dep_view_id for the dependent view, ViewSalesOrders.

CALL sa_dependent_views( 'SalesOrders' );

In this example, the sa_dependent_views system procedure is used in a SELECT statement to obtain the
list of names of views dependent on the SalesOrders table. The procedure returns the ViewSalesOrders
view.

SELECT t.table_name FROM SYSTAB t,


sa_dependent_views( 'SalesOrders' ) v
WHERE t.table_id = v.dep_view_id;

SAP IQ SQL Reference


844 INTERNAL System Procedures
7.6.13 sa_describe_shapefile System Procedure

Describes the names and types of columns contained in an ESRI shapefile. This system feature is for use with
the spatial data features.

 Syntax

sa_describe_shapefile( <shp_filename> , <srid > [, <encoding> ] )

Parameters

shp_filename

A VARCHAR(512) parameter that identifies the location of the ESRI shapefile. The file nameneeds the .shp
extension and 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

(Optional) A VARCHAR(50) parameter that identifies the encoding to use when reading the shapefile. The
default is NULL. When encoding is NULL, the ISO-8859-1 character set is used.

Result Set

Column Name Data Type Description

column_number INTEGER The ordinal position of the column described by this row,
starting at 1.

name VARCHAR(128) The name of the column.

domain_name_with_size VARCHAR(160) The data type name, including size and precision (as used in
CREATE TABLE or CAST functions).

Remarks

The sa_describe_shapefile system procedure is used to describe the name and type of columns in an
ESRI shapefile. This information can be used to create a table to load data from a shapefile using the LOAD
TABLE or INPUT statements. Alternately, this system procedure can be used to read a shapefile by specifying
the WITH clause for OPENSTRING...FORMAT SHAPEFILE.

SAP IQ SQL Reference


System Procedures INTERNAL 845
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. In addition:

● If the -gl database option is set to DBA, you must have one of the following system privileges:
○ ALTER ANY TABLE
○ ALTER ANY OBJECT
○ LOAD ANY TABLE
○ READ FILE
● If the -gl database option is set to ALL, no additional system privileges are needed.
● If the -gl database option is set to NONE, you must have the READ FILE system privilege.

Side Effects

None

Example

The following example displays a string that was used to create a table for storing shapefile data:

BEGIN
DECLARE create_cmd LONG VARCHAR;
SELECT 'create table if not exists esri_load( record_number int primary
key, ' ||
(SELECT list( name || ' ' || domain_name_with_size, ', ' ORDER BY
column_number )
FROM sa_describe_shapefile( 'c:\\esri\\tgr36069trt00.shp', 1000004326 )
WHERE column_number > 1 ) || ' )'
INTO create_cmd;
SELECT create_cmd;
EXECUTE IMMEDIATE create_cmd;
END

You can load the shapefile data into the table using the following statement (provided that you have the LOAD
ANY TABLE system privilege and that the -gl database option has not been set to NONE):

LOAD TABLE esri_load


USING FILE 'c:\\esri\\tgr36069trt00.shp'
FORMAT SHAPEFILE;

SAP IQ SQL Reference


846 INTERNAL System Procedures
7.6.14 sa_disable_auditing_type system procedure

Disables auditing of specific events.

 Syntax

sa_disable_auditing_type( <types> )

Parameters

types

Use this VARCHAR(128) parameter to specify a comma-delimited string containing one or more of the
following values:

all

disables all types of auditing.


connect

disables auditing of both successful and failed connection attempts.


connectFailed

disables auditing of failed connection attempts.


DDL

disables auditing of DDL statements.


options

disables auditing of public options.


permission

disables auditing of permission checks, user checks, and SETUSER statements.


permissionDenied

disables auditing of failed permission and user checks.


triggers

disables auditing in response to trigger events.


xp_cmdshell disables auditing for xp_cmdshell.

Remarks

Use sa_disable_auditing_type to specify which types of auditing to exclude. This system procedure removes
the specified events from the current set of audit events. Use sa_enable_auditing_type to add events to the
current set of audit events. These system procedures set the PUBLIC auditing_options database option so the
setting is permanent.

Set the PUBLIC auditing database option to On or Off to enable or disable auditing.

SAP IQ SQL Reference


System Procedures INTERNAL 847
By default, all events are audited (types='all'). If you want a smaller set, use the sa_disable_auditing_type
system procedure to clear the events you are not interested in; or use the sa_disable_auditing_type system
procedure to clear all events and then use the sa_enable_auditing_type system procedure to specify which
types of auditing you want.

If the set of events is empty and you set the PUBLIC auditing database option to On, no auditing information is
recorded. To re-establish auditing, you must use the sa_enable_auditing_type system procedure to specify
which types of information you want to audit.

If you set the PUBLIC auditing database option to Off, then no auditing information is recorded.

Specify the location where events are logged with the audit_log database option.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SET ANY SECURITY OPTION system
privilege.

Side effects

None

 Example

The following example disables all auditing:

CALL sa_disable_auditing_type( 'all' );

The following example enables only DDL and triggers auditing:

CALL sa_disable_auditing_type( 'all' );


CALL sa_enable_auditing_type( 'DDL,triggers' );

The following example enables all auditing except for DDL and options auditing:

CALL sa_enable_auditing_type( 'all' );


CALL sa_disable_auditing_type( 'DDL,options' );

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


848 INTERNAL System Procedures
7.6.15 sa_disk_free_space system procedure

Reports information about space available for a transaction log, transaction log mirror, and/or temporary file.

 Syntax

sa_disk_free_space( [ <p_dbspace_name> ] )

Parameters

p_dbspace_name

Use this VARCHAR(128) parameter to specify the name of a transaction log file, transaction log mirror file,
or temporary file. The default is NULL.

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 transaction log file, transac­


tion log mirror file, or temporary file.

free_space UNSIGNED BIGINT The number of free bytes on the vol­


ume.

total_space UNSIGNED BIGINT The total amount of disk space availa­


ble on the drive.

Remarks

If the <p_dbspace_name> parameter is not specified or is NULL, then the result set contains 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 log or mirror is specified and there is no log or
mirror file).

SAP IQ SQL Reference


System Procedures INTERNAL 849
Privileges

You must have EXECUTE privilege on the system procedure, as well as the MANAGE ANY DBSPACE system
privilege.

Side effects

None

 Example

The following example uses the sa_disk_free_space system procedure to return a result set containing
information about available space.

CALL sa_disk_free_space( );

dbspace_name free_space total_space

system 10952101888 21410402304

translog 10952101888 21410402304

temporary 10952101888 21410402304

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.16 sa_enable_auditing_type system procedure

Specifies which events to include in auditing.

 Syntax

sa_enable_auditing_type( <types> )

Parameters

types

SAP IQ SQL Reference


850 INTERNAL System Procedures
Use this VARCHAR(128) parameter to specify a comma-delimited string containing one or more of the
following values:

all

enables all types of auditing.


connect

enables auditing of both successful and failed connection attempts.


connectFailed

enables auditing of failed connection attempts.


DDL

enables auditing of DDL statements.


options

enables auditing of public options.


permission

enables auditing of permission checks, user checks, and SETUSER statements.


permissionDenied

enables auditing of failed permission and user checks.


triggers

enables auditing of a trigger event.


xp_cmdshell

enables auditing of xp_cmdshell invocations.

Remarks

Use sa_enable_auditing_type to specify which types of auditing to include. This system procedure adds the
specified events to the current set of audit events. Use sa_disable_auditing_type to remove events from the
current set of audit events. These system procedures set the PUBLIC auditing_options database option so the
setting is permanent.

Set the PUBLIC auditing database option to On or Off to enable or disable auditing.

By default, all events are audited (types='all'). If you want a smaller set, use the sa_disable_auditing_type
system procedure to clear the events you are not interested in; or use the sa_disable_auditing_type system
procedure to clear all events and then use the sa_enable_auditing_type system procedure to specify which
types of auditing you want.

If the set of events is empty and you set the PUBLIC auditing database option to On, no auditing information is
recorded. To re-establish auditing, you must use the sa_enable_auditing_type system procedure to specify
which types of information you want to audit.

If you set the PUBLIC auditing database option to Off, then no auditing information is recorded.

Specify the location where events are logged with the audit_log database option.

SAP IQ SQL Reference


System Procedures INTERNAL 851
Privileges

You must have EXECUTE privilege on the system procedure, as well as the SET ANY SECURITY OPTION system
privilege.

Side effects

None

 Example

The following example enables all auditing:

CALL sa_enable_auditing_type( 'all' );

The following example enables only DDL and triggers auditing:

CALL sa_disable_auditing_type( 'all' );


CALL sa_enable_auditing_type( 'DDL,triggers' );

The following example illustrates another way to enable only DDL and triggers auditing:

CALL sa_disable_auditing_type( 'all' );


CALL sa_enable_auditing_type( 'triggers' );
CALL sa_enable_auditing_type( 'DDL' );

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.17 sa_eng_properties system procedure

Reports database server property information.

 Syntax

sa_eng_properties( )

SAP IQ SQL Reference


852 INTERNAL System Procedures
Result set

Column name Data type Description

PropNum INTEGER The database server property number.

PropName VARCHAR(255) The database server property name.

PropDescription VARCHAR(255) The database server property descrip­


tion.

Value LONG VARCHAR The database server property value.

Remarks

Returns the PropNum, PropName, PropDescription, and Value for each available server property. Values are
returned for all database server properties and statistics related to database servers.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

The following statement returns a set of available server properties

CALL sa_eng_properties( );

PropNum PropName ...

1 IdleWrite ...

2 IdleChkPt ...

... ... ...

Related Information

Viewing all trackable database server property values [page 214]

SAP IQ SQL Reference


System Procedures INTERNAL 853
7.6.18 sa_external_library_unload System Procedure

Unloads an external library.

 Syntax

sa_external_library_unload ( [ '<external-library>' ] )

Parameters

external-library

(Optional) A LONG VARCHAR parameter that specifies 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.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MANAGE ANY EXTERNAL OBJECT system privilege.

Side Effects

None

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();

SAP IQ SQL Reference


854 INTERNAL System Procedures
Related Information

Determining the Security Model Used by a Database [page 576]

7.6.19 sa_flush_cache system procedure

Empties all pages for the current database in the database server cache.

 Syntax

sa_flush_cache( )

Remarks

Database administrators can use this procedure to empty the contents of the database server cache for the
current database. This is useful in performance measurement to ensure repeatable results.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SERVER OPERATOR system
privilege.

Side effects

None

 Example

The following example empties all pages for the current database in the database server cache.

CALL sa_flush_cache( );

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


System Procedures INTERNAL 855
7.6.20 sa_get_ldapserver_status System Procedure

Determines the current status of the LDAP server configuration object.

 Syntax

sa_get_ldapserver_status()

Result Set

Column Name Data Type Description

ldsrv_id UNSIGNED BIGINT A unique identifier for the LDAP server configuration object
that is the primary key and is used by the login policy to refer
to the LDAP server.

ldsrv_name CHAR(128) The name assigned to the LDAP server configuration object.

ldsrv_state CHAR(9) Read-only state of the LDAP server, A numeric value is


stored in system table; a corresponding text value appears in
the system view:

● 1 – RESET
● 2 – READY
● 3 – ACTIVE
● 4 – FAILED
● 5 – SUSPENDED

ldsrv_last_state_change TIMESTAMP Indicates the time the last state change occurred. The value
is stored in Coordinated Universal Time (UTC), regardless of
the local time zone of the LDAP server.

Remarks

To see SYSLDAPSERVER column values before a checkpoint occurs and the contents of memory are written to
the catalog on disk. The updates to the catalog columns ldsrv_state and ldsrv_last_state_change occur
asynchronously during checkpoint to the LDAP server object as the result of an event that changes the LDAP
server object state, such as a failed connection due to a failed LDAP directory server. The LDAP server object
state reflects the state of the LDAP directory server.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


856 INTERNAL System Procedures
Side Effects

None

7.6.21 sa_get_user_status system procedure

Allows you to determine the current status of users.

 Syntax

sa_get_user_status( )

Result set

Column name Data type Description

user_id UNSIGNED INTEGER A unique number identifying the user.

user_name CHAR(128) The name of the user.

connections INTEGER The current number of connections by


this user.

failed_logins UNSIGNED INTEGER The number of failed login attempts


made by the user.

last_login_time TIMESTAMP Returns the database server local date


and time (accurate to hours and mi­
nutes) that the most recent connection
was established. This value is affected
by simulated time zone.

locked TINYINT Indicates if the user account is locked.

reason_locked LONG VARCHAR The reason the account is locked.

user_dn CHAR(1024) The Distinguished Name (DN) for a


user ID connecting to an LDAP server.

user_dn_cached_at TIMESTAMP The date and time that the user_dn col­
umn was last cached. This value is used
to determine whether to purge an old
DN. Regardless of the database server
local time zone, the value is stored in
Coordinated Universal Time (UTC). This
value is not affected by simulated time
zone.

password_change_state BIT A value that indicates whether a dual


password change is in progress (0=No,
1=Yes). The default is 0.

SAP IQ SQL Reference


System Procedures INTERNAL 857
Column name Data type Description

password_change_first_user UNSIGNED INTEGER The user_id of the user who set the first
part of a dual password; otherwise
NULL.

password_change_second_user UNSIGNED INTEGER The user_id of the user who set the sec­
ond part of a dual password; otherwise
NULL.

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.

If the user is authenticated using LDAP User Authentication, the output includes the user's distinguished name
and the date and time that the distinguished name was found.

Privileges

You must have EXECUTE privilege on the system procedure.

To view information about other users, you must also have the MANAGE ANY USER system privilege.

Side effects

None

 Example

The following example uses the sa_get_user_status system procedure to return the status of database
users.

CALL sa_get_user_status;

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


858 INTERNAL System Procedures
7.6.22 sa_http_header_info system procedure

Returns HTTP request header names and values.

 Syntax

sa_http_header_info( [<header_parm>] )

Parameters

header_parm

Use this optional VARCHAR(255) parameter to specify an HTTP header name. The default is NULL.

Result set

Column name Data type Description

Name VARCHAR(255) The HTTP header name.

Value LONG VARCHAR The HTTP header value.

Remarks

The sa_http_header_info system procedure returns header names and values. If you do not specify the header
name using the optional parameter, the result set contains values for all headers.

This procedure returns a non-empty result set if it is called while processing an HTTP request within a web
service.

 Note

The sa_http_header_info system procedure may return multiple rows with the same name if the request
contains multiple HTTP headers with the same name.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 859
Side effects

None

 Example

The following web service procedure which is called from a web service illustrates the use of the
sa_http_header_info system procedure.

CREATE OR REPLACE PROCEDURE User1.HTTPHeaderExample()


RESULT ( html_string LONG VARCHAR )
BEGIN
DECLARE myname VARCHAR(255);
DECLARE myvalue LONG VARCHAR;
DECLARE err_notfound
EXCEPTION FOR SQLSTATE '02000';
DECLARE curs CURSOR FOR
SELECT Name, Value FROM sa_http_header_info();
MESSAGE '=== HTTP Headers ===' TO CONSOLE;
OPEN curs;
FetchLoop: LOOP
FETCH next curs INTO myname, myvalue;
IF SQLSTATE = err_notfound THEN
LEAVE FetchLoop;
END IF;
MESSAGE myname, '=', myvalue TO CONSOLE;
END LOOP FetchLoop;
CLOSE curs;
END;

When the web service that calls this web service procedure is used, output appears in the database server
messages window that is similar to the following.

=== HTTP Headers ===


@HttpQueryString=param1=value1&param2=value2&param3=value3
User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101
Firefox/16.0
Authorization=Basic VXNlcjE6dXNlcg==
Cache-Control=max-age=0
Connection=keep-alive
Host=webserver-t3500.sap.com:8082
@HttpURI=/ShowHTTPHeaders?param1=value1&param2=value2&param3=value3
@HttpMethod=GET
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
@HttpVersion=HTTP/1.1
Accept-Language=en-US,en;q=0.5
Accept-Encoding=gzip, deflate

7.6.23 sa_list_external_library System Procedure

Lists the external libraries currently loaded in the server.

 Syntax

sa_list_external_library( )

SAP IQ SQL Reference


860 INTERNAL System Procedures
Remarks

Returns a list of external libraries loaded in the engine along with their reference count.

The reference count is the number of instances of the library in the engine. An external library can be unloaded
by executing the procedure sa_external_library_unload, only if its reference count is 0.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MANAGE ANY EXTERNAL OBJECT system privilege.

Side Effects

None

Example

The following example lists the external libraries and their reference count:

CALL sa_list_external_library()

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.24 sa_list_statements system procedure

Returns the list of statements in use by the current connection.

 Syntax

sa_list_statements( )

SAP IQ SQL Reference


System Procedures INTERNAL 861
Result set

Column name Data type Description

handle UNSIGNED INTEGER A unique handle identifying the state­


ment.

statement_number INTEGER The number of the statement within the


connection.

num_client_prepares UNSIGNED INTEGER The number of times the client has pre­
pared the identical statement text.

num_opens UNSIGNED INTEGER The number of times the statement has


been opened.

schema_version_on_create UNSIGNED INTEGER For internal use only.

dropped_by_app BIT If the statement has been dropped by


the client but retained for caching the
value is 1; otherwise, the value is 0.

invalid_cached_statement BIT If this is a cached statement that is no


longer valid (for example, due to
schema changes) the value is 1; other­
wise the value is 0.

SQLStatement LONG VARCHAR The text of the statement.

Remarks

The sa_list_statements system procedure can be used in a CALL statement or in the FROM clause of a SELECT
statement. The statement executing the sa_list_statements system procedure is not included in the result.

The SQLStatement column is rewritten from the original text due to semantic transform optimizations and
normalization in a manner similar to that of the REWRITE function. Sensitive information such as encryption
keys and passwords is replaced with ***. Because of these changes, the SQLStatement value requires
interpretation when comparing to statements in the application, which might have a different form.

Privileges

None

Side effects

None

SAP IQ SQL Reference


862 INTERNAL System Procedures
 Example

The following example returns the list of statements for the connection:

CALL sa_list_statements();

The following example returns the list of statements that contribute to the max_statement_count resource
governor:

SELECT *
FROM sa_list_statements()
WHERE dropped_by_app=0;

7.6.25 sa_locks System Procedure

Displays all locks (including mutexes) in the database.

 Syntax

sa_locks(
[ <connection>
[, <creator>
[, <table_name>
[, <max_locks>
[, <object_type> ] ] ] ] )

Parameters

connection

(Optional) This INTEGER parameter specifies 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

(Optional) This CHAR(128) parameter specifies 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 <table_name> is unspecified – locking information is returned for all tables in the database
● If <table_name> is specified – locking information is returned for tables with the specified name that
were created by the current user
table_name

(Optional) This CHAR(128) parameter specifies 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

SAP IQ SQL Reference


System Procedures INTERNAL 863
(Optional) This INTEGER parameter specifies the maximum number of locks for which to return
information. The default value is 1000. The value -1 means return all lock information
object_type

(Optional) This CHAR(5) parameter limits your results to the type of object associated with the lock.
Specify ALL to return lock information for all object types. Specify TABLE to return lock information for
tables, global temporary tables, and materialized views. Specify MUTEX to return mutex information. If you
do not specify <object_type>, the procedure returns lock information for all object types.

Result Set

Column Name Data Type Description

conn_name VARCHAR(128) The name of the current connection.

conn_id INTEGER The connection ID number.

user_id CHAR(128) The user ID for the connection.

table_type CHAR(6) The type of table. This type is either BASE for a table,
GLBTMP for global temporary table, or MVIEW for a materi­
alized view.

creator VARCHAR(128) The owner of the table.

table_name VARCHAR(128) The table on which the lock is held.

index_id INTEGER The index ID or NULL.

lock_class CHAR(8) The lock class. One of Schema, Row, Table, or Position.

lock_duration CHAR(11) The duration of the lock. One of Transaction, Position, or


Connection.

lock_type CHAR(9) The lock type (this is dependent on the lock class).

row_identifier UNSIGNED BIGINT The identifier for the row. This is either an 8-byte row identi­
fier 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:

Lock Class Lock Types Comments

Schema ● Shared – shared schema lock For schema locks, the row_identifier and index ID values
● Exclusive – (IQ catalog store tables are NULL.
only) exclusive schema lock

SAP IQ SQL Reference


864 INTERNAL System Procedures
Lock Class Lock Types Comments

Row ● Read – read lock Row read locks can be short-term locks (scans at isolation
● Intent – intent lock level 1) or long-term locks at higher isolation levels. The
● ReadPK – read lock lock_duration column indicates whether the read lock is of
● Write – write lock short duration because of cursor stability (Position) or
● WriteNoPK – write lock long duration, held until COMMIT/ROLLBACK (Transac­
● Surrogate – surrogate lock tion). Row locks are always held on a specific row that has
an 8-byte row identifier that is reported as a 64-bit integer
value in the row_identifier column.

A surrogate lock is a special case of a row lock. Surrogate


locks are held on surrogate entries, which are created
when referential integrity checking is delayed. 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
connection. The row_identifier value is unique for the table
and connection associated with the surrogate lock.

If required, key and non-key portions of a row can be


locked independently. A connection can obtain a read lock
on the key portion of a row for shared (read) access so
that other connections can still obtain write locks on other
non-key columns of a row. Updating non-key columns of a
row does not interfere with the insertion and deletion of
foreign rows referencing that row.

Table ● Shared – shared table lock None


● Intent – intent to update table lock
● Exclusive – (IQ catalog store tables
only) exclusive table lock

Position ● Phantom – (IQ catalog store tables Usually a position lock is also held on a specific row, and
only) phantom lock that row's 64-bit row identifier appears in the row_identi­
● Insert – insert lock fier column in the result set. However, Position locks can
be held on entire scans (index or sequential), in which
case the row_identifier column 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.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MONITOR system privilege.

SAP IQ SQL Reference


System Procedures INTERNAL 865
Side Effects

None

Example

You can execute the following query to identify locks:

CALL sa_locks( );

Use the sa_locks system procedure to view the locks that are currently held in the database, including
information about the connection holding the lock, the lock duration, and the lock type. Execute a query that
joins the results of the sa_locks system procedure to a particular table by using the ROWID of the table in the
join predicate.

SELECT S.conn_id, S.user_id, S.lock_class, S.lock_type, E.*


FROM sa_locks() S JOIN Employees E WITH( NOLOCK )
ON ROWID(E) = S.row_identifier
WHERE S.table_name = 'Employees';

The result set of the sa_locks system procedure contains the row_identifier column that allows you to identify
the row in a table the lock refers to. It may not be necessary to specify the WITH NOLOCK clause; however, if
the query is issued at isolation levels other than 0, the query may block until the locks are released, which
reduces the usefulness of this method of checking.

7.6.26 sa_make_object system procedure (deprecated)

Ensures that a skeletal instance of an object exists before executing an ALTER statement.

 Syntax

sa_make_object(
<objtype>
, <objname>
[, <owner>
[, <tabname> ] ]
)

<objtype>:
'procedure'
| 'function'
| 'view'
| 'trigger'
| 'service'
| 'event'

SAP IQ SQL Reference


866 INTERNAL System Procedures
Parameters

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 is
NULL.
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. The default is NULL.

Remarks

This procedure can be used in scripts that are run repeatedly to create or modify a database schema, however
its use is deprecated in favor of using the CREATE OR REPLACE statement for the type object you are creating
or modifying, wherever possible. Using CREATE OR REPLACE is more efficient, and offers the correct behavior
when trying to create an object that already exists.

If you use the sa_make_object system procedure, you typically follow it by an ALTER statement that contains
the entire object definition.

Privileges

You must have EXECUTE privilege on the system procedure, as well as other privileges, as follows:

Procedures or functions owned by the invoker

CREATE PROCEDURE, CREATE ANY PROCEDURE, or CREATE ANY OBJECT system privilege
Procedures or functions owned by other users

CREATE ANY PROCEDURE or CREATE ANY OBJECT system privilege


Services

MANAGE ANY WEB SERVICE system privilege


Events

MANAGE ANY EVENT or CREATE ANY OBJECT system privilege


Views owned by the invoker

CREATE VIEW, CREATE ANY VIEW, or CREATE ANY OBJECT system privilege
Views owned by other users

CREATE ANY VIEW or CREATE ANY OBJECT system privilege

SAP IQ SQL Reference


System Procedures INTERNAL 867
Triggers

If the trigger is on a table owned by you, you must have either the CREATE ANY TRIGGER or CREATE ANY
OBJECT system privilege.

If the trigger is on a table owned by another user, you must have either the CREATE ANY TRIGGER or the
CREATE ANY OBJECT system privilege. Additionally, you must have one of the following:

● ALTER ANY TABLE privilege


● ALTER ANY OBJECT system privilege
● ALTER permission on the table on which the trigger is being created.

Side effects

Automatic commit

 Example

The following statements ensure that a skeleton procedure definition is created, define the procedure, and
grant privileges 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' );

7.6.27 sa_nchar_terms System Procedure

Breaks an NCHAR string into terms and returns each term as a row along with its position.

 Syntax

sa_nchar_terms
( '<char-string>' [ , '<text-config-name>' [, '<owner>' ] ] ] )

Parameters

char-string

SAP IQ SQL Reference


868 INTERNAL System Procedures
The NCHAR string you are parsing.
text-config-name

(Optional) The text configuration object to apply when processing the string. The default value is
'default_nchar'.
owner

(Optional) The owner of the specified text configuration object. The default value is DBA.

Remarks

You can use sa_nchar_terms 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.

The syntax for sa_nchar_terms is similar to the syntax for the sa_char_terms system procedure.

 Note

The NCHAR data type is supported only for IN SYSTEM tables.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

7.6.28 sa_performance_diagnostics System Procedure

Returns a summary of request timing information for all connections when the database server has request
timing logging enabled.

 Syntax

sa_performance_diagnostics( )

SAP IQ SQL Reference


System Procedures INTERNAL 869
Result Set

Column Name Data Type Description

Number INTEGER Returns the connection ID (a number) for the current con­
nection.

Name VARCHAR(255) Returns the name of the current connection.

You can specify a connection name using the Connection­


Name (CON) connection parameter.

The following names are used for temporary connections


created by the database server:

● INT:ApplyRecovery
● INT:BackupDB
● INT:Checkpoint
● INT:Cleaner
● INT:CloseDB
● INT:CreateDB
● INT:CreateMirror
● INT:DelayedCommit
● INT:DiagRcvr
● INT:DropDB
● INT:EncryptDB
● INT:Exchange
● INT:FlushMirrorLog
● INT:FlushStats
● INT:HTTPReq
● INT:PromoteMirror
● INT:PurgeSnapshot
● INT:ReconnectMirror
● INT:RecoverMirror
● INT:RedoCheckpoint
● INT:RefreshIndex
● INT:ReloadTrigger
● INT:RenameMirror
● INT:RestoreDB
● INT:StartDB
● INT:VSS

Userid VARCHAR(255) Returns the user ID for the connection.

DBNumber INTEGER Returns the ID number of the database.

LoginTime TIMESTAMP Returns the date and time the connection was established.

SAP IQ SQL Reference


870 INTERNAL System Procedures
Column Name Data Type Description

TransactionStar TIMESTAMP Returns a string containing the time the database was first
tTime modified after a COMMIT or ROLLBACK, or an empty string
if no modifications have been made to the database since
the last COMMIT or ROLLBACK.

LastReqTime TIMESTAMP Returns the time at which the last request for the specified
connection started. This property can return an empty string
for internal connections, such as events.

ReqType VARCHAR(255) Returns the type of the last request. If a connection has been
cached by connection pooling, its ReqType value is CON­
NECT_POOL_CACHE.

ReqStatus VARCHAR(255) Returns the status of the request. It can be one of the follow­
ing values:

● Idle – the connection is not currently processing a re­


quest.
● Unscheduled – the connection has work to do and is
waiting for an available database server worker.
● BlockedIO – the connection is blocked waiting for an
I/O.
● BlockedContention – the connection is blocked waiting
for access to shared database server data structures.
● BlockedLock – the connection is blocked waiting for a
locked object.
● Executing – the connection is executing a request.

The values marked with an asterisk (*) are only returned


when logging of request timing information has been turned
on for the database server using the -zt server option. If re­
quest timing information is not being logged (the default),
the values are reported as Executing.

ReqTimeUnschedu DOUBLE Returns the amount of unscheduled time, or NULL if the -zt
led option was not specified.

ReqTimeActive DOUBLE Returns the amount of time, in seconds, spent processing


requests, or NULL if the -zt option was not specified.

ReqTimeBlockIO DOUBLE Returns the amount of time, in seconds, spent waiting for
I/O to complete, or NULL if the -zt option was not specified.

ReqTimeBlockLoc DOUBLE Returns the amount of time, in seconds, spent waiting for a
k lock, or NULL if the -zt option was not specified.

ReqTimeBlockCon DOUBLE Returns the amount of time, in seconds, spent waiting for
tention atomic access, or NULL if the RequestTiming server prop­
erty is set to Off.

ReqCountUnsched INTEGER Returns the number of times the connection waited for
uled scheduling, or NULL if the -zt option was not specified.

ReqCountActive INTEGER Returns the number of requests processed, or NULL if the


RequestTiming server property is set to Off.

SAP IQ SQL Reference


System Procedures INTERNAL 871
Column Name Data Type Description

ReqCountBlockIO INTEGER Returns the number of times the connection waited for I/O
to complete, or NULL if the -zt option was not specified.

ReqCountBlockLo INTEGER Returns the number of times the connection waited for a
ck lock, or NULL if the -zt option was not specified.

ReqCountBlockCo INTEGER Returns the number of times the connection waited for
ntention atomic access, or NULL if the -zt option was not specified.

LastIdle INTEGER Returns the number of ticks between requests.

BlockedOn INTEGER Returns zero if the current connection isn't blocked, or if it is


blocked, the connection number on which the connection is
blocked because of a locking conflict.

UncommitOp INTEGER Returns the number of uncommitted operations.

CurrentProcedur VARCHAR(255) Returns the name of the procedure that a connection is cur­
e rently executing. If the connection is executing nested proce­
dure calls, the name is the name of the current procedure. If
there is no procedure executing, an empty string is returned.

EventName VARCHAR(255) Returns the name of the associated event if the connection
is running an event handler. Otherwise, an empty string is re­
turned.

CurrentLineNumb INTEGER Returns the current line number of the procedure or com­
er pound statement a connection is executing. The procedure
can be identified using the CurrentProcedure property. If the
line is part of a compound statement from the client, an
empty string is returned.

LastStatement LONG VARCHAR Returns the most recently prepared SQL statement for the
current connection.

The LastStatement value is set when a statement is pre­


pared, and is cleared when a statement is dropped. Only one
statement string is remembered for each connection.

If sa_conn_activity reports a non-empty value for a connec­


tion, it is most likely the statement that the connection is
currently executing. If the statement had completed, it
would likely have been dropped and the property value
would have been cleared. If an application prepares multiple
statements and retains their statement handles, then the
LastStatement value does not reflect what a connection is
currently doing.

When client statement caching is enabled, and a cached


statement is reused, this property returns an empty string.

LastPlanText LONG VARCHAR Returns the long text plan of the last query executed on the
connection. You control the remembering of the last plan by
setting the RememberLastPlan option of the sa_server_op­
tion system procedure, or using the -zp server option.

SAP IQ SQL Reference


872 INTERNAL System Procedures
Column Name Data Type Description

AppInfo LONG VARCHAR Returns information about the client that made the connec­
tion. For HTTP connections, this includes information about
the browser. For connections using older versions of jCon­
nect or Open Client, the information may be incomplete.

The API value can be DBLIB, ODBC, OLEDB, ADO.NET, iAny­


whereJDBC, PHP, PerlDBD, or DBEXPRESS.

LockCount INTEGER Returns the number of locks held by the connection.

SnapshotCount INTEGER Returns the number of snapshots associated with the con­
nection.

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' );

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MONITOR system privilege.

Side Effects

None

Examples

● The following query identifies 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,
IF T <>

SAP IQ SQL Reference


System Procedures INTERNAL 873
● The following example finds 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 sa_performance_diagnostics()
WHERE ReqStatus <> 'IDLE' AND ReqTime > 60.0
ORDER BY ReqTime DESC;

7.6.29 sa_procedure_profile System Procedure

Reports information about the execution time for each line within procedures, functions, events, or triggers
that have been executed in a database.

 Syntax

sa_procedure_profile(
[ <filename>
[, <save_to_file> ] ] )

Parameters

filename

(Optional) A LONG VARCHAR parameter that specifies the file to which the profiling information should be
saved, or from which file it should be loaded. The default is NULL. See the Remarks section below for more
about saving and loading the profiling information.
save_to_file

(Optional) An INTEGER parameter that specifies whether to save the profiling information to a file, or load
it from a previously stored file. The default is 0.

SAP IQ SQL Reference


874 INTERNAL System Procedures
Result Set

Column Name Data Type Description

object_type CHAR(1) The type of object. The object_type column of the result set
can be:

● P – stored procedure
● F – function
● E – event
● T – trigger
● C – ON UPDATE system trigger
● D – ON DELETE system tribber

object_name CHAR(128) The name of the stored procedure, function, event, or trig­
ger. If the object_type is C or D, then this is the name of the
foreign key for which the system trigger was defined.

owner_name CHAR(128) The object's owner.

table_name CHAR(128) The table associated with a trigger (the value is NULL for
other object types).

line_num UNSIGNED INTEGER The line number within the procedure.

executions UNSIGNED INTEGER The number of times the line has been executed.

millisecs UNSIGNED INTEGER The time to execute the line, in milliseconds.

percentage DOUBLE The percentage of the total execution time required for the
specific 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

You can use this procedure to:

● Return detailed procedure profiling information – to do this, call the procedure without specifying any
arguments.
● Save detailed procedure profiling information to file – to do this, 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, include the
<filename> argument and specify 0 for the <save_to_file> argument. 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.

SAP IQ SQL Reference


System Procedures INTERNAL 875
If you want summary information instead of line by line details for each execution, use the
sa_procedure_profile_summary procedure instead.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MONITOR or MANAGE PROFILING system privilege.

You must also have the following privileges:

● SELECT ANY TABLE – when <filename> is not NULL and <save_to_file> is 1


● LOAD ANY TABLE – when <filename> is not NULL and <save_to_file> is 0

Side Effects

None

Examples

● 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 detailedinfo.txt:

CALL sa_procedure_profile( 'detailedinfo.txt', 0 );


CALL sa_procedure_profile( 'detailedinfo.txt' );

7.6.30 sa_procedure_profile_summary System Procedure

Reports summary information about the execution times for all procedures, functions, events, or triggers that
have been executed in a database.

 Syntax

sa_procedure_profile_summary (

SAP IQ SQL Reference


876 INTERNAL System Procedures
[ <filename> [, <save_to_file> ] ] )

Parameters

filename

(Optional) A LONG VARCHAR parameter that specifies the file to which the profiling information is saved,
or from which file it should be loaded. The default is NULL. See the Remarks section below for more about
saving and loading the profiling information.
save_to_file

(Optional) An INTEGER parameter that specifies whether to save the summary information to a file, or to
load it from a previously saved file. The default is 0.

Result Set

Column Name Data Type Description

object_type CHAR(1) The type of object. The object_type column of the result set
can be:

● P – stored procedure
● F – function
● E – event
● T – trigger
● C – ON UPDATE system trigger
● D – ON DELETE system trigger

object_name CHAR(128) The name of the stored procedure, function, event, or trig­
ger.

owner_name CHAR(128) The object's owner.

table_name CHAR(128) The table associated with a trigger (the value is NULL for
other object types).

executions UNSIGNED INTEGER The number of times each procedure has been executed.

millisecs UNSIGNED INTEGER The time to execute the procedure, in milliseconds.

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:

SAP IQ SQL Reference


System Procedures INTERNAL 877
● Return current summary information – to do this, call the procedure without specifying any arguments.
● Save current summary information to file – to do this, include the <filename> argument and specify 1 for
the <save_to_file> argument.
● Load stored summary information from a file – to do this, include the <filename> argument and specify 0
for the <save_to_file> argument. 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.

If you want line by line details for each execution instead of summary information, use the
sa_procedure_profile procedure instead.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have either the MONITOR or MANAGE PROFILING system privilege.
Finally, you must also have the following privileges:

● SELECT ANY TABLE – when <filename> is not NULL and <save_to_file> is 1


● LOAD ANY TABLE – when <filename> is not NULL and <save_to_file> is 0

Side Effects

None

Examples

● 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
summaryinfo.txt:

CALL sa_procedure_profile_summary( 'summaryinfo'.txt, 0 );

SAP IQ SQL Reference


878 INTERNAL System Procedures
CALL sa_procedure_profile_summary( 'summaryinfo.txt' );

7.6.31 sa_report_deadlocks System Procedure

Retrieves information about deadlocks from an internal buffer created by the database server.

 Syntax

sa_report_deadlocks( )

Result Set

Column Name Data Type Description

snapshotId BIGINT The deadlock instance (all rows pertaining to a particular


deadlock have the same ID).

snapshotAt TIMESTAMP The time when the deadlock occurred.

waiter INT The connection handle of the waiting connection.

who VARCHAR(128) The user ID associated with the connection that is waiting.

what LONG VARCHAR The command being executed by the waiting connection.

This information is only available if you have turned on cap­


turing of the most recently-prepared SQL statement by
specifying the -zl option on the database server command
line.

object_id UNSIGNED BIGINT The object ID of the table containing the row.

record_id BIGINT The row ID for system tables.

owner INT The connection handle of the connection owning the lock
being waited on.

is_victim BIT Identifies the rolled back transaction.

rollback_operat UNSIGNED INT The number of uncommitted operations that may be lost if
ion_count the transaction rolls back.

iq_rid UNSIGNED BIGINT The row ID for IQ RLV-enabled tables.

iq_txn_id UNSIGNED BIGINT The transaction id of the associated row.

SAP IQ SQL Reference


System Procedures INTERNAL 879
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.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MONITOR system privilege.

Side Effects

None

7.6.32 sa_rowgenerator system procedure

Returns a result set with rows between a specified start and end value.

 Syntax

sa_rowgenerator(
[ <rstart>
[, <rend>
[, <rstep> ] ] ]
)

Parameters

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.

SAP IQ SQL Reference


880 INTERNAL System Procedures
Result set

Column name Data type Description

row_num INTEGER Sequence number.

Remarks

The sa_rowgenerator procedure can be used in the FROM clause of a query to generate a sequence of
numbers. This procedure is an alternative to using the RowGenerator system table. You can use
sa_rowgenerator for such tasks as:

● generating test data for a known number of rows in a result set.


● generating a result set with rows for values in every range. For example, you can generate a row for every
day of the month, or you can generate ranges of ZIP codes.
● generating a query that has a specified number of rows in the result set. This may be useful for testing the
performance of queries.

No rows are returned if you do not specify correct start and end values and a positive non-zero step value.

You can emulate the behavior of the RowGenerator table with the following statement:

SELECT row_num FROM sa_rowgenerator( 1, 255 );

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

The following query returns a result set containing one row for each day of the current month.

SELECT DATEADD( day, row_num-1,


YMD( DATEPART( year, CURRENT DATE ),
DATEPART( month, CURRENT DATE ), 1 ) )
AS day_of_month
FROM sa_rowgenerator( 1, 31, 1 )
WHERE DATEPART( month, day_of_month ) = DATEPART( month, CURRENT DATE )
ORDER BY row_num;

The following query shows how many employees live in ZIP code ranges (0-9999), (10000-19999), ...,
(90000-99999). Some of these ranges have no employees, which causes a warning.

SAP IQ SQL Reference


System Procedures INTERNAL 881
The sa_rowgenerator procedure can be used to generate these ranges, even though no employees have a
ZIP code in the range.

SELECT row_num AS r1, row_num+9999 AS r2, COUNT( PostalCode ) AS zips_in_range


FROM sa_rowgenerator( 0, 99999, 10000 ) D LEFT JOIN Employees
ON PostalCode BETWEEN r1 AND r2
GROUP BY r1, r2
ORDER BY 1;

The following example generates 10 rows of data and inserts them into the NewEmployees table:

INSERT INTO NewEmployees ( ID, Salary, Name )


SELECT row_num, CAST( RAND() * 1000 AS INTEGER ), 'Mary'
FROM sa_rowgenerator( 1, 10 );

The following example uses the sa_rowgenerator system procedure to create a view containing all integers.
The value 2147483647 in this example represents the maximum signed integer that is supported.

CREATE VIEW Integers AS


SELECT row_num AS n
FROM sa_rowgenerator( 0, 2147483647, 1 );

This example uses the sa_rowgenerator system procedure to create a view containing dates from
0001-01-01 to 9999-12-31. The value 3652058 in this example represents the number of days between
0001-01-01 and 9999-12-31, the earliest and latest dates that are supported.

CREATE VIEW Dates AS


SELECT DATEADD( day, row_num, '0001-01-01' ) AS d
FROM sa_rowgenerator( 0, 3652058, 1 );

The following query returns all years between 1900 and 2058 that have 54 weeks.

SELECT DATEADD ( day, row_num, '1900-01-01' ) AS d, DATEPART ( week, d ) w


FROM sa_rowgenerator ( 0, 63919, 1 )
WHERE w = 54;

7.6.33 sa_server_option System Procedure

Overrides a server option while the server is running.

 Syntax

sa_server_option( <opt> , <val> )

Go to:

● Privileges
● Side Effects
● Examples

SAP IQ SQL Reference


882 INTERNAL System Procedures
Parameters

opt

A CHAR(128) parameter that specifies a server option name.


val

A CHAR(128) parameter that specifies the new value for the server option.

The following table lists the valid values for <opt> and <val>:

Option Name (<opt>) Values (<val>) Description

AutoMultiProgrammingLevel YES (default); NO 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 mul­
tiprogramming level manually by setting this option to NO, you can
still set the initial, minimum, and maximum values for the multi­
programming level.

AutoMultiProgrammingLevel­ YES; NO (default) When set to YES, statistics for automatic multiprogramming level
Statistics
adjustments appear in the database server message log.

CacheSizingStatistics YES; NO (default) When set to YES, display cache information in the database server
messages window whenever the cache size changes.

CollectStatistics YES (default); NO When set to YES, the database server collects Performance Moni­
tor statistics.

ConnsDisabled YES; NO (default) When set to YES, no other connections are allowed to any data­
bases on the database server.

ConnsDisabledForDB YES; NO (default) When set to YES, no other connections are allowed to the current
database.

ConsoleLogFile <filename>
The name of the file used to record database server message log
information. Specifying an empty string stops logging to the file.
Double any backslash characters in the path because this value is
a SQL string.

ConsoleLogMaxSize <file-size>
The maximum size, in bytes, of the file used to record database
(bytes)
server message log information. When the database server mes­
sage log file reaches the size specified by either this property or
the -on server option, the file is renamed with the exten­
sion .old appended (replacing an existing file with the same
name if one exists). The database server message log file is then
restarted.

CurrentMultiProgrammingLevel Integer Sets the multiprogramming level of the database server. Default is
20.

SAP IQ SQL Reference


System Procedures INTERNAL 883
Option Name (<opt>) Values (<val>) Description

DatabaseCleaner ON (default); OFF Do not change the setting of this option except on the recommen­
dation of Technical Support.

DeadlockLogging ON; OFF (default); Controls deadlock logging. The value deadlock_logging is also
RESET; CLEAR
supported. The following values are supported:

● ON – enables deadlock logging.


● OFF – disables deadlock logging and leaves the deadlock data
available for viewing.
● RESET – clears the logged deadlock data, if any exists, and
then enables deadlock logging.
● CLEAR – clears the logged deadlock data, if any exists, and
then disables deadlock logging.

Once deadlock logging is enabled, you can use the sa_re­


port_deadlocks system procedure to retrieve deadlock informa­
tion from the database.

DebuggingInformation YES; NO (default) Displays diagnostic messages and other messages for trouble­
shooting purposes. The messages appear in the database server
messages window.

DiskSandbox ON; OFF (default) Sets the default disk sandbox settings for all databases started on
the database server that do not have explicit disk sandbox set­
tings. Changing the disk sandbox settings by using the
sa_server_option system procedure does not affect data­
bases already running on the database server. To use the
sa_server_option system procedure to change disk sandbox
settings, you must provide the secure feature key for the man­
age_disk_sandbox secure feature.

DropBadStatistics YES (default); NO Allows automatic statistics management to drop statistics that re­
turn bad estimates from the database.

DropUnusedStatistics YES (default); NO Allows automatic statistics management to drop statistics that
have not been used for 90 consecutive days from the database.

IdleTimeout Integer (minutes) Disconnects TCP/IP connections that have not submitted a re­
quest for the specified number of minutes. This prevents inactive
connections from holding locks indefinitely. The default is 240

IPAddressMonitorPeriod Integer (seconds) The minimum value is 10 and the default is 0. For portable devices,
the default value is 120.

Sets the time to check for new IP addresses in seconds.

LivenessTimeout Integer (seconds) A liveness packet is sent periodically across a client/server TCP/IP
network to confirm that a connection is intact. If the network
server runs for a LivenessTimeout period without detecting a liv­
eness packet, the communication is severed. The default is 120.

SAP IQ SQL Reference


884 INTERNAL System Procedures
Option Name (<opt>) Values (<val>) Description

MaxMultiProgrammingLevel Integer Default is four times the value for CurrentMultiProgrammingLevel.

Sets the maximum database server multiprogramming level.

MessageCategoryLimit Integer Sets the minimum number of messages of each severity and cate­
gory that can be retrieved using the sa_server_messages system
procedure. The default is 400

MinMultiProgrammingLevel Integer Default is the minimum of the value of the -gtc server option and
the number of logical CPUs on the computer.

OptionWatchAction MESSAGE (default); Specifies the action that the database server takes when an at­
ERROR
tempt is made to set an option in the list. When OptionWatchAc­
tion is set to MESSAGE, and an option specified by OptionWatch­
List 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:

SELECT DB_PROPERTY( 'OptionWatchAction' );

OptionWatchList Comma-separated Specifies a comma-separated list of database options that you


list of database op­
want to be notified about, or have the database server return an
tions
error for, when they are set. The string length is limited to 128
bytes. By default, it is an empty string. For example, the following
command adds the automatic_timestamp, float_as_double, and
tsql_hex_constant option to the list of options being watched:

CALL sa_server_option( 'OptionWatchList',


'automatic_timestamp, float_as_double,
tsql_hex_constant' );

You can view the current setting for this property by executing:

SELECT DB_PROPERTY( 'OptionWatchList' );

ProcedureProfiling YES; NO (default); Enables or disables procedure profiling, which provides informa­
RESET; CLEAR tion about the usage of stored procedures, user-defined functions,
events, system triggers, and triggers by all connections.

ProfileFilterConn <connection-id>
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.

SAP IQ SQL Reference


System Procedures INTERNAL 885
Option Name (<opt>) Values (<val>) Description

ProcessorAffinity Comma-delimited Instructs the database server which logical processors to use on
list of processor
Windows or Linux. Specify a comma-delimited list of processor
numbers and/or
numbers and/or ranges. If the lower endpoint of a range is omit­
ranges. The default
is that all processors ted, then it is assumed to be zero. If the upper endpoint of a range
are used or the set­ is omitted, then it is assumed to be the highest CPU known to the
ting of the -gta op­ operating system. The in_use column returned by the
tion. sa_cpu_topology system procedure contains the current pro­
cessor affinity of the database server, and the in_use column indi­
cates

The database server might not use all of the specified logical pro­
cessors in the following cases:

● If one or more of the specified logical processors does not ex­


ist, or is offline.
● If the license does not allow it.

If you specify an invalid processor ID, sa_server_option re­


turns an error.

ProfileFilterUser <user-id>
Instructs the database server to capture profiling information for a
specific user ID.

PropertyHistoryList ON (default); OFF; Values are:


NONE; comma-de­
● ON – when PropertyHistoryList is turned on, a default list of
limited list of data­
properties is tracked.
base server proper­
● OFF – when PropertyHistoryList is turned off, property track­
ties
ing is disabled for the database server.
● NONE – setting this property to NONE enables property
tracking but no properties are tracked by the database server.
Only properties requested by databases are tracked.
● Comma-delimited list of database server properties – specify
a comma-delimited list of database server properties to
track.

SAP IQ SQL Reference


886 INTERNAL System Procedures
Option Name (<opt>) Values (<val>) Description

PropertyHistorySize <time>; <memory- Specifies either the minimum amount of time to store tracked
size>; MAX; DE­
property values or the maximum amount of memory to use to
FAULT
store tracked property values. To set this property to a time, use
the format '[HH:]MM:SS'. To set this property to a memory size,
specify the memory size in bytes. For example, 1M. The default
value is '00:10:00' (ten minutes), unless that amount of time viola­
tes the maximum size limit, in which case MAX is used as the de­
fault.

Specify MAX to request that the fixed maximum amount of mem­


ory is used. The maximum memory is either 2% of the cache or
256 MB, whichever is smaller.

When PropertyHistoryList is set, the amount of memory used for


tracking property history is updated. If it has increased beyond the
fixed maximum amount of memory allowed for storing property
history, then an error is raised. If the amount of memory used has
decreased and there is no longer enough memory to track the
specified properties' history, then an error is raised. If an error is
raised, then the property history reverts back to its previous value.

If there is insufficient memory to track all properties specified by


PropertyHistoryList, an error is returned and the property is not
added to the list of tracked properties.

QuittingTime Valid date and time Instructs the database server to shut down at the specified time.

RememberLastPlan YES; NO (default) Instructs the database server to capture the long text plan of the
last query executed on the connection. This setting is also control­
led by the -zp server option.When RememberLastPlan is turned
on, obtain the textual representation of the plan of the last query
executed on the connection by querying the value of the LastPlan­
Text connection property:

SELECT
CONNECTION_PROPERTY( 'LastPlanText' );

SAP IQ SQL Reference


System Procedures INTERNAL 887
Option Name (<opt>) Values (<val>) Description

RememberLastStatement YES; NO (default) Instructs the database server to capture the most recently pre­
pared 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 RememberLast­
Statement is turned on, you can obtain the current value of the
LastStatement for a connection by querying the value of the Last­
Statement connection property:

SELECT
CONNECTION_PROPERTY( 'LastStatement' );

When client statement caching is enabled, and a cached state­


ment is reused, this property returns an empty string. When Re­
memberLastStatement is turned on, the following statement re­
turns the most recently prepared statement for the specified con­
nection:

SELECT
CONNECTION_PROPERTY( 'LastStatement',
connection-id );

The sa_conn_activity system procedure returns this same


information for all connections.

 Note
When -zl is specified, or when the RememberLastState­
ment server setting is turned on, any user can call
thesa_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.
Use this option with caution and turn it off when it is not re­
quired.

SAP IQ SQL Reference


888 INTERNAL System Procedures
Option Name (<opt>) Values (<val>) Description

RequestFilterConn <connection-id>; Filter the request logging information so that only information for
-1
a particular connection is logged. This filtering can 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 log a specific connection once you have obtained the connec­


tion ID, execute the following statement:

CALL
sa_server_option( 'RequestFilterConn',
<connection-id> );

Filtering remains in effect until it is explicitly reset, or until the da­


tabase server is shut down. To reset filtering, use the following
statement:

CALL
sa_server_option( 'RequestFilterConn',
-1 );

RequestFilterDB <database-id>; -1 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 data­
bases. You can obtain the database ID by executing the following
statement when you are connected to the desired database:

SELECT CONNECTION_PROPERTY( 'DBNumber' );

To log only information for a particular database, execute the fol­


lowing statement:

CALL sa_server_option( 'RequestFilterDB',


<database-id> );

Filtering remains in effect until it is explicitly reset, or until the da­


tabase server is shut down. To reset filtering, use the following
statement:

CALL sa_server_option( 'RequestFilterDB',


-1 );

SAP IQ SQL Reference


System Procedures INTERNAL 889
Option Name (<opt>) Values (<val>) Description

RequestLogFile <filename>
The name of the file used to record request information. Specify­
ing 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 data­
base server messages window. Double any backslash characters
in the path because this value is a SQL string.

When client statement caching is enabled, set the


max_client_statements_cached option 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.

SAP IQ SQL Reference


890 INTERNAL System Procedures
Option Name (<opt>) Values (<val>) Description

RequestLogging SQL; HOSTVARS; This call turns on logging of individual SQL statements sent to the
PLAN; PROCE­
database server for use in troubleshooting with the database
DURES; TRIGGERS;
server -zr and -zo options. Values can be combinations of the
OTHER; BLOCKS;
REPLACE; ALL; YES; following, separated by either a plus sign (+), or a comma:
NONE (default); NO
● PLAN – enables logging of execution plans (short form). If
logging of procedures (PROCEDURES) is enabled, execution
plans for procedures are also recorded.
● HOSTVARS – enables logging of host variable values. If you
specify HOSTVARS, the information listed for SQL is also log­
ged.
● The maximum size of the file used to record request logging
information, in bytes. If you specify 0, then there is no maxi­
mum size for the request logging file, and the file is never­
PROCEDURES – enables logging of statements executed
from within procedures.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 value is the default. When
the request log file reaches the size specified by either the re­
named. This value is the default. When the request log file
reaches the size specified by either the
● TRIGGERS – enables logging of statements executed from
within triggers.
● OTHER – enables logging of additional request types not in­
cluded 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 per­
formance.
● BLOCKS – enables logging of details showing when a connec­
tion 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. Other­
wise, the existing request log is opened and new entries are
appended to the end of the file.
● ALL – logs all supported information. This value is equivalent
to specifying SQL+PLAN+HOSTVARS+PROCEDURES+TRIG­
GERS+OTHER+BLOCKS. This setting can cause the log file to
grow rapidly and could negatively impact server performance.
● NO or NONE – turns off logging to the request log.

You can view the current setting for this property by executing:

SELECT PROPERTY( 'RequestLogging' );

SAP IQ SQL Reference


System Procedures INTERNAL 891
Option Name (<opt>) Values (<val>) Description

RequestLogMaxSize <file-size>
The maximum size of the file used to record request logging infor­
(bytes)
mation, in bytes. If you specify 0, then there is no maximum size
for the request logging file, and the file is neverPROCEDURES –
enables logging of statements executed from within proce­
dures.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
value is the default. When the request log file reaches the size
specified by either the renamed. This value is the default. When
the request log file reaches the size specified by either the
sa_server_option system procedure or the -zs server op­
tion, the file is renamed with the extension .old appended (replac­
ing an existing file with the same name if one exists). The request
log file is then restarted.

RequestLogNumFiles Integer The number of request log file copies to retain. If request logging
is enabled over a long period, the request log file can become
large. The -zn option allows you to specify the number of request
log file copies to retain

RequestTiming YES; NO (default) Instructs the database server to maintain timing information for
each new connection. This feature is turned off by default. When it
is turned on, the database server maintains cumulative timers for
all new connections that indicate how much time the connection
spent in the server in each of several states. The change is only
effective for new connections, and lasts for the duration each con­
nection. 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.

SAP IQ SQL Reference


892 INTERNAL System Procedures
Option Name (<opt>) Values (<val>) Description

rlv_auto_merge ON (default); OFF


 Note
This option is deprecated.

Enables or disables automatic merges of the RLV store into the IQ


main store for row-level versioning-enabled tables.

If rlv_auto_merge is OFF, no automated merges of the RLV and IQ


main stores occur. This implies that you assume responsibility to
manually merge data so that the RLV store gets synced to the IQ
main store before the upper rlv_memory_mb threshold is reached.

rlv_memory_mb The minimum value Replaced with the RV_AUTO_MERGE database option. To avoid­
is 1 MB. The maxi­
Specifies the maximum amount of memory (the RLV store), in
mum value is 2048.
MB, to reserve for row-level versioning. The default value is 2048
Any other value will
set the amount of MB. If the value exceeds 2/3rds of the system virtual memory
memory to 2048 limit, the server generates an error.
MB.

SecureFeatures <feature-list>
Allows you to manage secure features for a database server that is
already running. The feature-list is a comma-separated list of fea­
ture 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.

To call sa_server_option('SecureFeatures',...),
the connection must have the ManageFeatures secure feature en­
abled on the connection. The -sf key (the system secure feature
key) enables ManageFeatures, as well as all of the other features.
So if you used the system secure feature key, then changing the
set of SecureFeatures will not have any effect on the connection.
But if you used another key (for example a key that had been cre­
ated using the create_secure_feature_key system pro­
cedure) then your connection may be immediately affected by the
change, depending on what other features are included in the key.

Any changes you make to allow or prevent access to features take


effect immediately for the database server. The connection that
executes the sa_server_option system procedure may or
may not be affected, depending on the secure feature key the con­
nection is using and whether or not it allows the connection ac­
cess to the specified features.

For example, to secure two features, use the following syntax:

CALL sa_server_option('SecureFeatures',
'CONSOLE_LOG,WEBCLIENT_LOG' );

After executing this statement, the list of secure features is set ac­
cording to what has been changed.

SAP IQ SQL Reference


System Procedures INTERNAL 893
Option Name (<opt>) Values (<val>) Description

StatisticsCleaner ON (default); OFF 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 gov­
ernor, but when the statistics cleaner is turned off, statistics are
only created or fixed when a query is run.

WebClientLogFile <filename>
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. Dou­
ble any backslash characters in the path because this value is a
string.

WebClientLogging ON; OFF (default) This option enables and disables logging of web service clients.
The information that is logged includes HTTP requests and re­
sponse data. Specify ON to start logging to the web service client
log file, and specify OFF to stop logging to the file.

Privileges

(back to top)

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MANAGE PROFILING system privilege to use the following
options, which are related to application profiling or request logging:

● ProcedureProfiling
● ProfileFilterConn
● ProfileFilterUser
● RequestFilterConn
● RequestFilterDB
● RequestLogFile
● RequestLogging
● RequestLogMaxSize
● RequestLogNumFiles

Side Effects

(back to top)

None

SAP IQ SQL Reference


894 INTERNAL System Procedures
Examples

(back to top)

● The following statement causes cache information to be displayed in the database server messages
window whenever the cache size changes:

CALL sa_server_option( 'CacheSizingStatistics', 'YES' );

● The following statement disallows new connections to the current database:

CALL sa_server_option( 'ConnsDisabledForDB', 'YES' );

● The following statement enables logging of all SQL statements, procedure calls, plans, blocking and
unblocking events, and starts a new request log:

CALL sa_server_option( 'RequestLogging', 'SQL+PROCEDURES+BLOCKS+PLAN


+REPLACE' );

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.34 sa_set_http_header system procedure

Permits a web service to set an HTTP response header.

 Syntax

sa_set_http_header(
<fldname>
, <val>
[, <instance> ]
)

Parameters

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

SAP IQ SQL Reference


System Procedures INTERNAL 895
Use this UNSIGNED INT parameter to specify which instance of the HTTP response header to set. The
default is 1.

Remarks

Setting the special header field @HttpStatus sets the status code returned with the request. The status code is
also known as the response code. For example, the following script sets the status code to 404 Not Found:

CALL sa_set_http_header( '@HttpStatus', '404' );

You can create a user-defined status message by specifying a three digit status code with an optional colon-
delimited text message. For example, the following script outputs a status code with the message "999 User
Code":

CALL sa_set_http_header( '@HttpStatus', '999:User Code' );

 Note

A user defined status text message is not translated into a database character-set when logged using the
LogOptions protocol option.

The body of the error message is inserted automatically. Only valid HTTP error codes can be used. Setting the
status to an invalid code causes a SQL error.

The sa_set_http_header procedure always overwrites the existing header value of the header field when called.

Response headers generated automatically by the database server can be removed. For example, the following
command removes the Expires response header:

CALL sa_set_http_header( 'Expires', NULL );

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

The following example sets the Set-Cookie header field to type=chocolate and specifies the third instance
of the header.

CALL sa_set_http_header( 'Set-Cookie', 'type=chocolate', 3 );

SAP IQ SQL Reference


896 INTERNAL System Procedures
7.6.35 sa_set_http_option system procedure

Permits a web service to set an HTTP option for process control.

 Syntax

sa_set_http_option(
<optname>
, <val>
)

Parameters

optname

Use this CHAR(128) parameter to specify a string containing the name of one of the HTTP options.

The supported options are:

CharsetConversion

Use this option to control whether the result set is to be automatically converted from the character
set encoding of the database to the character set encoding of the client. The only permitted values are
ON and OFF. The default value is ON.
AcceptCharset

Use this option to specify the web server's preferences for a response character set encoding. One or
more character set encodings may be specified in order of preference. The syntax for this option
conforms to the syntax used for the HTTP Accept-Charset request-header field specification in
RFC2616 Hypertext Transfer Protocol.

An HTTP client such as a web browser may provide an Accept-Charset request header which specifies
a list of character set encodings ordered by preference. Optionally, each encoding may be given an
associated quality value (q=<qvalue>) which represents the client's preference for that encoding. By
default, the quality value is 1 (q=1). Here is an example:

Accept-Charset: iso-8859-5, utf-8;q=0.8

A plus sign (+) in the AcceptCharset HTTP option value may be used as a shortcut to represent the
current database character set encoding. The plus sign also indicates that the database character set
encoding should take precedence if the client also specifies the encoding in its list, regardless of the
quality value assigned by the client.

An asterisk (*) in the AcceptCharset HTTP option may be used to indicate that the web service should
use a character set encoding preferred by the client, as long as it is also supported by the server, when
client and server do not have an intersecting list.

When sending the response, the first character set encoding preferred by both client and web service
is used. The client's order of preference takes precedence. If no mutual encoding preference exists,
then the web service's most preferred encoding is used, unless an asterisk (*) appears in the web
service list in which case the client's most preferred encoding is used.

SAP IQ SQL Reference


System Procedures INTERNAL 897
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.

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 timeout period is reset whenever an HTTP request uses the given session. The session

SAP IQ SQL Reference


898 INTERNAL System Procedures
is automatically deleted when the SessionTimeout is exceeded. When an HTTP session is created, the
default timeout period is taken from the current setting of the http_session_timeout database option.
The SessionTimeout option can be used to override this default. Allowed values are 1 to 525600 (365
days).
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.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

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.

CALL sa_set_http_option( 'AcceptCharset', '+,UTF-8,*');

The following example illustrates the use of sa_set_http_option to correctly identify the character encoding
in use by the web service. In this example, the web server is connected to a 1251CYR database and is
prepared to serve HTML documents containing the Cyrillic alphabet to any web browser.

CREATE OR REPLACE PROCEDURE cyrillic_html()


RESULT (html_doc XML)
BEGIN
DECLARE pos INT;
DECLARE charset VARCHAR(30);
CALL sa_set_http_option( 'AcceptCharset', 'iso-8859-5, utf-8' );
SET charset = CONNECTION_PROPERTY( 'CharSet' );
-- Change any IANA labels like ISO_8859-5:1988
-- to ISO_8859-5 for Firefox.
SET pos = LOCATE( charset, ':' );
IF pos > 0 THEN
SET charset = LEFT( charset, pos - 1 );

SAP IQ SQL Reference


System Procedures INTERNAL 899
END IF;
CALL sa_set_http_header( 'Content-Type', 'text/html; charset=' ||
charset );
SELECT '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">' ||
XMLCONCAT(
XMLELEMENT('HTML',
XMLELEMENT('HEAD',
XMLELEMENT('TITLE', 'Cyrillic characters')
),
XMLELEMENT('BODY',
XMLELEMENT('H1', 'First 5 lowercase Russian letters'),
XMLELEMENT('P', UNISTR('\u0430\u0431\u0432\u0433\u0434'))
)
)
);
END;
CREATE SERVICE cyrillic
TYPE 'RAW'
AUTHORIZATION OFF
USER DBA
AS CALL cyrillic_html();

To illustrate the process of establishing the correct character set encoding to use, consider the following
Accept-Charset header delivered by a web browser such as Firefox to the web service. It indicates that the
browser prefers ISO-8859-1 and UTF-8 encodings but is willing to accept others.

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

The web service will not accept the ISO-8859-1 character set encoding since the web page to be
transmitted contains Cyrillic characters. The web service prefers ISO-8859-5 or UTF-8 encodings as
indicated by the call to sa_set_http_option. In this example, the UTF-8 encoding will be chosen since it is
agreeable to both parties. The database connection property CharSet indicates which encoding has been
selected by the web service. The sa_set_http_header procedure is used to indicate the HTML document's
encoding to the web browser.

Content-Type: text/html; charset=UTF-8

If the web browser does not specify an Accept-Charset, then the web service defaults to its first preference,
ISO-8859-5. The sa_set_http_header procedure is used to indicate the HTML document's encoding.

Content-Type: text/html; charset=ISO_8859-5

The following example sets a unique HTTP session identifier:

BEGIN
DECLARE sessionid VARCHAR(30);
DECLARE tm TIMESTAMP;
SET tm = NOW(*);
SET sessionid = 'MySessions_' ||
CONVERT( VARCHAR, SECONDS(tm)*1000 + DATEPART(millisecond,tm));
SELECT sessionid;
CALL sa_set_http_option('SessionID', sessionid);
END;

The following example sets the timeout for an HTTP session to 5 minutes:

CALL sa_set_http_option('SessionTimeout', 5);

SAP IQ SQL Reference


900 INTERNAL System Procedures
7.6.36 sa_stack_trace system procedure

Returns the stack trace leading to the current call location.

 Syntax

sa_stack_trace(
[ <stack_frames>
[, <detail_level>
[, <connection_id> ] ] ]
)

Parameters

stack_frames

Use this optional CHAR(128) parameter to specify one of the following:

'procedure'

Return procedures but not the outer-most statement. This is the default behavior.
'caller'

Return only the outer-most statement (the statement that arrived from the client).
'procedure+caller', 'caller+procedure'

Return all statements.


detail_level

Use this optional CHAR(128) parameter to specify one of the following:

'stack'

Include procedure names and line numbers. This is the default behavior.
'stack+sql', 'sql+stack'

Include the procedure names and line numbers, as well as the SQL text of the statement being
executed at each level.
connection_id

Use this optional UNSIGNED INTEGER parameter to filter the results returned to the specified connection
ID. If not specified, information for the current connection is returned.

Result set

Column name Data type Description

StackLevel UNSIGNED SMALLINT The current line has Stack Level 1.

SAP IQ SQL Reference


System Procedures INTERNAL 901
Column name Data type Description

UserName CHAR(128) The name of the owner of the proce­


dure or trigger, or NULL if the current
level is in a batch.

ProcName CHAR(128) The name of the procedure or trigger


where the call was performed or the
batch type.

LineNumber UNSIGNED INTEGER The line number of the call within the
procedure, trigger, or batch.

SQLStatement LONG VARCHAR The statement being executed.

Remarks

Each record in the result set represents a single call on the stack. If the compound statement is not part of a
procedure, function, trigger, or event, then the type of batch (watcom_batch or tsql_batch) is returned instead
of the procedure name.

This function returns line numbers as found in the proc_defn column of the SYSPROCEDURE system table for
the procedure. These line numbers might differ from those of the source definition used to create the
procedure.

This procedure returns the same information as the STACK_TRACE function.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None.

 Example

This example shows how to obtain the result set columns from the sa_stack_trace system procedure:

SELECT StackLevel, UserName, ProcName, LineNumber FROM sa_stack_trace();

When this statement is executed outside of the context of a stored procedure, the result set is empty.

The following example shows the implementation of a general stack trace procedure that sends its results
to the client window:

CREATE OR REPLACE PROCEDURE StackDump( MSG CHAR(128) )


BEGIN

SAP IQ SQL Reference


902 INTERNAL System Procedures
DECLARE myStackLevel UNSIGNED SMALLINT;
DECLARE myUserName CHAR(128);
DECLARE myProcName CHAR(128);
DECLARE myLineNumber UNSIGNED SMALLINT;
DECLARE mySQLStatement long varchar;
DECLARE err_notfound
EXCEPTION FOR SQLSTATE '02000';
DECLARE myStack CURSOR FOR
SELECT StackLevel, UserName, ProcName, LineNumber, SQLStatement FROM
sa_stack_trace('caller+procedure', 'stack+sql');
MESSAGE 'Stack Trace: ' || MSG TO CLIENT;
OPEN myStack;
StackLoop: LOOP
FETCH NEXT myStack
INTO myStackLevel, myUserName, myProcName, myLineNumber,
mySQLStatement;
IF SQLSTATE = err_notfound THEN
LEAVE StackLoop;
END IF;
IF myStackLevel != 1 THEN
MESSAGE myStackLevel - 1 || ' ' || myUserName || ' ' ||
myProcName || ' ' || myLineNumber || ' ' || mySQLStatement
TO CLIENT;
ENDIF
END LOOP StackLoop;
CLOSE myStack;
END;

CREATE OR REPLACE PROCEDURE Proc1()


BEGIN
CALL Proc2();
END;

CREATE OR REPLACE PROCEDURE Proc2()


BEGIN
CALL Proc3();
END;

CREATE OR REPLACE PROCEDURE Proc3()


BEGIN
CALL StackDump('Snapshot from Proc3');
END;

CALL Proc1();

Results:

CALL Proc1();
-- Stack Trace: Snapshot from Proc3
-- 1 DBA proc3 3 call StackDump('Snapshot from Proc3')
-- 2 DBA proc2 3 call Proc3()
-- 3 DBA proc1 3 call Proc2()
-- Procedure completed

Related Information

STACK_TRACE function [Miscellaneous] [page 521]


STACK_TRACE function [Miscellaneous] [page 521]

SAP IQ SQL Reference


System Procedures INTERNAL 903
7.6.37 sa_table_page_usage system procedure

Reports information about the page usage of database tables.

 Syntax

sa_table_page_usage( )

Result set

Column name Data type Description

TableId UNSIGNED INTEGER The table ID.

TablePages INTEGER The number of table pages used by the


table.

PctUsedT INTEGER The percentage of used table page


space.

IndexPages INTEGER The number of index pages used by the


table.

PctUsedI INTEGER The percentage of used index page


space.

PctOfFile INTEGER The percentage of the total database


file the table occupies.

TableName CHAR(128) The table name.

Remarks

The results include the same information provided by the Information utility. When the progress_messages
database option is set to Raw or Formatted, progress messages are sent from the database server to the client
while the sa_table_page_usage system procedure is running.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the MANAGE ANY DBSPACE system
privilege.

SAP IQ SQL Reference


904 INTERNAL System Procedures
Side effects

None

 Example

The following example obtains information about the page usage of the SalesOrderItems table.

SELECT * FROM sa_table_page_usage( )


WHERE TableName = 'SalesOrderItems';

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.38 sa_text_index_stats System Procedure

Returns statistical information about the TEXT indexes in the database.

 Syntax

sa_text_index_stats( )

Result Set

Column Name Data Type Description

owner_id UNSIGNED INT ID of the owner of the table

table_id UNSIGNED INT ID of the table

index_id UNSIGNED INT ID of the TEXT index

text_config_id UNSIGNED BIGINT ID of the text configuration referenced by the TEXT index

owner_name CHAR(128) Name of the owner

table_name CHAR(128) Name of the table

index_name CHAR(128) Name of the TEXT index

text_config_nam CHAR(128) Name of the text configuration object


e

doc_count UNSIGNED BIGINT Total number of indexed column values in the TEXT index

SAP IQ SQL Reference


System Procedures INTERNAL 905
Column Name Data Type Description

doc_length UNSIGNED BIGINT Total length of data in the TEXT index

pending_length UNSIGNED BIGINT Total length of the pending changes

deleted_length UNSIGNED BIGINT Total length of the pending deletions

last_refresh TIMESTAMP Date and time of the last refresh

Remarks

Use sa_text_index_stats to view statistical information for each TEXT index in the database.

The pending_length, deleted_length, and last_refresh values are NULL for IMMEDIATE REFRESH
TEXT indexes.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have one of the following system privileges:

● MANAGE ANY STATISTICS


● CREATE ANY INDEX
● ALTER ANY INDEX
● DROP ANY INDEX
● CREATE ANY OBJECT
● ALTER ANY OBJECT
● DROP ANY OBJECT

Side Effects

None

Example

The following example returns statistical information for each TEXT index in the database:

CALL sa_text_index_stats( );

SAP IQ SQL Reference


906 INTERNAL System Procedures
Related Information

Determining the Security Model Used by a Database [page 576]

7.6.39 sa_text_index_vocab System Procedure

Lists all terms that appear in a TEXT index, and the total number of indexed values in which each term appears.

 Syntax

sa_text_index_vocab (
'<text-index-name>',
'<table-name>',
'<table-owner>'
)

Parameters

text-index-name

A CHAR(128) parameter that specifies the name of the TEXT index.


table-name

A CHAR(128) parameter that specifies the name of the table on which the TEXT index is built.
table-owner

A CHAR(128) parameter that specifies the owner of the table.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have one of the following:

● SELECT ANY TABLE system privilege


● SELECT privilege on the indexed table

Remarks

sa_text_index_vocab returns all terms that appear in a TEXT index, and the total number of indexed values
in which each term appears (which is less than the total number of occurrences, if the term appears multiple
times in some indexed values).

SAP IQ SQL Reference


System Procedures INTERNAL 907
Parameter values cannot be host variables or expressions. The arguments <text-index-name>, <table-
name>, and <table-owner> must be constraints or variables.

Side Effects

None

Example

The following example executes sa_text_index_vocab to return all the terms that appear in the TEXT index
MyTextIndex on table Customers owned by GROUPO:

sa_text_index_vocab
('MyTextIndex','Customers','GROUPO');

Terms in the index are:

Term Frequency

a 1

Able 1

Acres 1

Active 5

Advertising 1

Again 1

... ...

Related Information

Determining the Security Model Used by a Database [page 576]

SAP IQ SQL Reference


908 INTERNAL System Procedures
7.6.40 sa_validate system procedure

Validates all or parts of a database.

 Syntax

sa_validate(
[ <tbl_name>
[, <owner_name> ] ]
[, <check_type> ] ]
[, <isolation_type> ] ]
)

Parameters

tbl_name

Use this optional CHAR(128) parameter to specify the name of a table or materialized view to validate. The
default is NULL, in which case the entire database is validated.
owner_name

Use this optional CHAR(128) parameter to specify an owner. When specified by itself, all tables and
materialized views owned by the owner are validated. The default is NULL.
check_type

Use this optional CHAR(10) parameter to specify the type of validation to perform. The possible values are

EXPRESS

If this parameter is EXPRESS, each table is checked using a VALIDATE TABLE statement with the WITH
EXPRESS CHECK clause.
NULL If this parameter is NULL (the default), each table is checked using a VALIDATE TABLE
statement.
isolation_type

Use this optional parameter when validating tables that have active transactions to prevent receiving false
errors about corrupt tables. The possible values are:

DATA LOCK Prevents transactions from modifying the table schema or data by applying exclusive data
locks on the specified tables. Concurrent transactions can read, but not modify the table data or
schema.
SNAPSHOT Ensures that only committed data is checked by applying snapshot isolation. Transactions
can read and modify the data. This clause requires that the database have snapshot isolation enabled
(with the allow_snapshot_isolation database option). Because this clause uses snapshot isolation,
performance is often affected.

SAP IQ SQL Reference


System Procedures INTERNAL 909
Result set

Column name Data type Description

Messages CHAR(128) If validation succeeds without error,


then the column contains No error
detected.

IsValid BIT 1 if valid; 0 if validation errors are de­


tected

ObjectName CHAR(261) ● Empty string if valid


● Database if database validation
fails
● The owner and name of a table if
table validation fails.

Remarks

Argument specified Type of validation

None All tables, materialized views, and indexes in the database


are validated (equivalent to a VALIDATE TABLE on every ta­
ble). The database itself is also validated (equivalent to a
VALIDATE DATABASE statement), including checksum vali­
dation.

<tbl_name> If <owner_name> is NULL, then all tables matching


<tbl_name>, their materialized views, and their indexes
are validated.

<owner_name> All tables, materialized views, and indexes owned by the


specified user are validated.

<tbl_name> and <owner_name> The specified table or materialized view owned by the
specified user, and all of its indexes, are validated.

<check_type> The specified table(s), materialized view(s), or index(es) is


validated using WITH EXPRESS CHECK. The database itself
is also validated, including checksum validation.

<isolation_type> The specified table(s), materialized view(s), or index(es) is


validated. Tables either have exclusive data locks applied to
them, or only committed data is evaluated. The database it­
self is also validated, including checksum validation.

 Caution

If <isolation_type> is not specified, then only perform validation while no connections are making
changes to the database; otherwise, false errors may be reported indicating some form of database
corruption.

SAP IQ SQL Reference


910 INTERNAL System Procedures
You can validate disk pages for databases that use global or write checksums. If a database has global
checksums enabled, then all database pages are validated. If a database has used only write checksums, then
only pages with checksums are validated.

For databases with checksums enabled, a checksum is calculated for each database page and this value is
stored when the page is written to disk. You can use the Validation utility (dbvalid), the VALIDATE statement,
the sa_validate system procedure, or the Validate Database Wizard in SQL Central to perform checksum
validation, which consists of reading the database pages from disk and calculating the checksum for the page.
If the calculated checksum does not match the stored checksum for a page, the page has been modified or
corrupted while on disk or while writing to the page. If one or more pages has been corrupted, an error is
returned and information about the invalid pages appears in the database server messages window.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the VALIDATE ANY OBJECT system
privilege.

Side effects

If <isolation type> is DATA LOCK, then exclusive data locks are applied to the specified table(s) or view(s).

Automatic commit for both <isolation_type> options.

 Example

The following statement performs a validation of tables and materialized views owned by user pjones:

CALL sa_validate( owner_name = 'pjones' );

Related Information

Determining the Security Model Used by a Database [page 576]

7.6.41 sa_verify_password system procedure

Validates the password of the current user.

 Syntax

sa_verify_password( <curr_pswd> )

SAP IQ SQL Reference


System Procedures INTERNAL 911
Parameters

curr_pswd

Use this CHAR(128) parameter to specify the password of the current database user.

Returns

The function returns an INTEGER value.

Remarks

This procedure is used by sp_password. If the password matches, 0 is returned and no error occurs. If the
password does not match, an error is diagnosed. The connection is not terminated if the password does not
match.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

The following example attempts to validate the current connection's password when the current user is
DBA or User1. An error occurs if the current password does not match.

IF USER_NAME() = 'DBA' THEN


SELECT sa_verify_password( 'sql' );
ELSEIF USER_NAME() = 'User1' THEN
SELECT sa_verify_password( 'user' );
END IF;

SAP IQ SQL Reference


912 INTERNAL System Procedures
7.6.42 sp_alter_secure_feature_key System Procedure

Alters a previously-defined secure feature key by modifying the authorization key and/or the feature list.

 Syntax

sp_alter_secure_feature_key (
<name>,
<auth_key>,
<features> )

Parameters

name

A VARCHAR (128) name for the secure feature key you want to alter. A key with the given name must
already exist.
auth_key

A CHAR (128) authorization key for the secure feature key. The authorization key must be either a non-
empty string of at least six characters, or NULL, indicating that the existing authorization key is not to be
changed.
features

A LONG VARCHAR, comma-separated list of secure features that the key can enable. The feature_list can
be NULL, indicating that the existing feature_list is not to be changed.

Remarks

This procedure allows you to alter the authorization key or feature list of an existing secure feature key.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. In addition, you must be the database server owner and have the manage_keys feature
enabled on the connection.

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 913
7.6.43 sp_auth_sys_role_info System Procedure

Generates a report which maps authorities to corresponding system roles and role id. This procedure returns a
row for each authority.

 Syntax

sp_auth_sys_role_info()

Result Set

Column Name Data Type Description

auth VARCHAR(20) The name of the authority.

role_name CHAR(128) The name of the equivalent system role.

role_id UNSIGNED INT The id of the system role.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

7.6.44 sp_create_secure_feature_key System Procedure

Creates a new secure feature key.

 Syntax

sp_create_secure_feature_key (
<name>,
<auth_key>,
<features> )

SAP IQ SQL Reference


914 INTERNAL System Procedures
Parameters

name

A VARCHAR (128) name for the new secure feature key. This argument cannot be NULL or an empty string.
auth_key

A CHAR (128) authorization key for the secure feature key. The authorization key must be a non-empty
string of at least six characters.
features

A LONG VARCHAR comma-separated list of secure features that the new key can enable. Specifying "-"
before a feature means that the feature is not re-enabled when the secure feature key is set.

Remarks

This procedure creates a new secure feature key that can be given to any user. The system secure feature key is
created using the -sk database server option.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. In addition, you must be the database server owner and have the manage_keys feature
enabled on the connection.

Side Effects

None

7.6.45 sp_displayroles System Procedure

Displays all roles granted to a user-defined role or a user, or displays the entire hierarchical tree of roles.

 Syntax

sp_displayroles(
[ <user_role_name> ],
[ <display_mode> ],
[ <grant_type> ] )

SAP IQ SQL Reference


System Procedures INTERNAL 915
Parameters

user_role_name

The user role name. Valid values are:

● A valid system privilege name or system privilege role name


● A valid user-defined role name
● A valid user name

By default, if no argument is specified, the current login user is used.


display_mode

The display mode. Valid values are:

● EXPAND_UP – shows all roles granted the input role or system privilege; that is the role hierarchy tree
for the parent levels.
● EXPAND_DOWN – shows all roles or system privileges granted to the input role or user; that is, the role
hierarchy tree for the child levels.

If no argument is specified (default), only the directly granted roles or system privileges appear.
grant_type

The grant type. Valid values are:

● ALL – shows all roles or system privileges granted.


● NO_ADMIN – shows all roles or system privileges granted with the WITH NO ADMIN OPTION or WITH
ADMIN OPTION clause.
● ADMIN – shows all roles or system privileges granted with the WITH ADMIN OPTION or WITH ADMIN
ONLY OPTION clause.

If no argument is specified, ALL is used.

Result Set

Column Name Data Type Description

role_name CHAR(128) Lists role/system privilege name.

parent_role_nam CHAR(128) Lists role name of the parent.


e

grant_type CHAR(10) Lists grant type.

role_level SMALLINT For Expand_down mode, 1 indicates directly granted roles;


2 indicates the next hierarchy below, and so on. For
Expand_up mode, 0 indicates the roles to which the speci­
fied role is granted; -1 indicates the next hierarchy above, and
so on.

SAP IQ SQL Reference


916 INTERNAL System Procedures
Remarks

For:

● Name = System privilege name – the results show the system privilege name instead of the system
privilege role name.
● Mode = Expand_down – parent_role_name is NULL for level 1 (directly granted roles). If no mode is
specified (default), role_level is 1 and parent_role_name is NULL, since only directly granted roles appear.
● Name = User name, with Mode = expand_up – no results are returned since a user resides at the top level
in any role hierarchy. Similarly, if Name = an immutable system privilege name, with Mode = Expand_down,
no results are returned because an immutable system privilege resides at the bottom level in any role
hierarchy.
● Default Mode – parent_role_name column is NULL and role_level is 1.

Side Effects

None

Examples

These examples assume that the following GRANT statements have been executed:

GRANT SERVER OPERATOR TO r4;


GRANT BACKUP DATABASE TO r3 WITH ADMIN OPTION;
GRANT DROP CONNECTION TO r3 WITH ADMIN ONLY OPTION;
GRANT MONITOR TO r2;GRANT CHECKPOINT TO r1;
GRANT ROLE r2 TO r1 WITH ADMIN OPTION;
GRANT ROLE r3 TO r2 WITH NO ADMIN OPTION;
GRANT ROLE r4 TO r3 WITH ADMIN ONLY OPTION;
GRANT ROLE r1 TO user1;
GRANT ROLE r1 TO r7;
GRANT ROLE r7 TO user2 WITH ADMIN OPTION;
GRANT BACKUP DATABASE TO user2 WITH ADMIN ONLY OPTION;

● In the following example, sp_displayroles( 'user2', 'expand_down', 'ALL' ) produces output


similar to:

role_name parent_role_name grant_type role_level

r7 NULL ADMIN 1

PUBLIC NULL NO ADMIN 1

BACKUP DATABASE NULL ADMIN ONLY 1

dbo PUBLIC NO ADMIN 2

r1 r7 NO ADMIN 2

r2 r1 ADMIN 3

SAP IQ SQL Reference


System Procedures INTERNAL 917
role_name parent_role_name grant_type role_level

CHECKPOINT r1 NO ADMIN 3

r3 r2 NO ADMIN 4

MONITOR r2 NO ADMIN 4

r4 r3 ADMIN ONLY 5

BACKUP DATABASE r3 ADMIN 5

DROP CONNECTION r3 ADMIN ONLY 5

● In the following example, sp_displayroles( 'user2', 'expand_down', 'NO_ADMIN' ) produces


output similar to:

role_name parent_role_name grant_type role_level

r7 NULL ADMIN 1

PUBLIC NULL NO ADMIN 1

dbo PUBLIC NO ADMIN 2

r1 r7 NO ADMIN 2

r2 r1 ADMIN 3

CHECKPOINT r1 NO ADMIN 3

r3 r2 NO ADMIN 4

MONITOR r2 NO ADMIN 4

BACKUP DATABASE r3 ADMIN 5

● In the following example, sp_displayroles( 'r3', 'expand_up', 'NO_ADMIN' ) produces out put
similar to:

role_name parent_role_name grant_type role_level

r1 r7 NO ADMIN -2

r2 r1 ADMIN -1

r3 r2 NO ADMIN 0

● In the following example, sp_displayroles( 'r1', 'NO_ADMIN', 'expand_up') produces output


similar to:

role_name parent_role_name grant_type role_level

r1 r7 NO ADMIN 0

SAP IQ SQL Reference


918 INTERNAL System Procedures
7.6.46 sp_drop_secure_feature_key System Procedure

Deletes a secure feature key.

 Syntax

sp_drop_secure_feature_key ( <name> )

Parameters

name

A VARCHAR (128) name of the secure feature key to drop.

Remarks

If the named key does not exist, an error is returned. If the named key exists, it is deleted as long as it is not the
last secure feature key that is allowed to manage secure features and secure feature keys. For example, the
system secure feature key cannot be dropped until there is another key that has the manage_features and
manage_keys secure features enabled.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. In addition, you must be the database server owner and have the manage_keys feature
enabled on the connection.

Side Effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 919
7.6.47 sp_expireallpasswords System Procedure

Immediately expires all user passwords.

 Syntax

Syntax 1

call sp_expireallpasswords

Syntax 2

sp_expireallpasswords

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. You must also have the MANAGE ANY USER system privilege.

Side Effects

None

Related Information

(Deprecated) sp_iqaddlogin Procedure [page 585]


sp_iqcopyloginpolicy Procedure [page 627]
sp_iqmodifylogin Procedure [page 703]
(Deprecated) sp_iqpassword Procedure [page 725]

7.6.48 sp_find_top_statements system procedure

Reports performance statistics for each logged statement/plan combination.

 Syntax

sp_find_top_statements( <stmt_text>, <stmt_hash> )

SAP IQ SQL Reference


920 INTERNAL System Procedures
Parameters

stmt_text

Use this optional LONG VARCHAR parameter to specify a SQL statement string. The default is NULL.
stmt_hash Use this optional UNSIGNED BIGINT parameter to specify a statement hash. The default is
NULL.

Result set

Column name Data type Description

stmt_hash UNSIGNED BIGINT Returns the statement identifier.

owner_name CHAR(128) Returns the name of the owner of the


stored procedure. The value is NULL if
the statement is not part of a stored
procedure, user-defined function, trig­
ger, or event. The value may also be
NULL if the statement is executed as
part of a stored procedure and the
stored procedure is subsequently drop­
ped. A statement executed as part of a
stored procedure gets a hash that is re­
lated to the procedure, not the state­
ment text.

proc_name CHAR(128) Returns the name of the procedure that


the statement belongs to. The value is
NULL if the statement is not part of a
stored procedure, user-defined func­
tion, trigger or event. The value may
also be NULL if the statement is exe­
cuted as part of a stored procedure and
the stored procedure is subsequently
dropped. A statement executed as part
of a stored procedure gets a hash that
is related to the procedure, not the
statement text.

reusable_stmt_id UNSIGNED INTEGER Returns a unique identifier assigned to


the statement within a procedure (not
necessarily a line number). The value is
NULL if the statement is not part of a
stored procedure, user-defined func­
tion, trigger, or event.

plan_hash UNSIGNED BIGINT Returns the plan identifier.

max_seconds DOUBLE Returns the maximum runtime ob­


served for the statement when exe­
cuted with the current plan.

SAP IQ SQL Reference


System Procedures INTERNAL 921
Column name Data type Description

sum_runtime DOUBLE Returns the total runtime for the state­


ment with the current plan.

sum_square_runtime DOUBLE Returns the sum of the squares of the


observed runtimes. This value is used
for the standard deviation calculation.

max_blocking_time DOUBLE Returns the maximum observed block­


ing time for the statement when exe­
cuted with the current plan.

sum_blocking_time DOUBLE Returns the total blocking time for the


statement executions using the current
plan.

num_exec UNSIGNED BIGINT Returns the number of times the state­


ment was executed using the current
plan.

total_num_rows UNSIGNED BIGINT Returns the total number of rows re­


turned or modified by the statement
over all executions performed with the
current plan.

last_max_time_utc TIMESTAMP Returns the date and time in Coordi­


nated Universal Time (UTC) that the
maximum runtime was last updated.

last_time_utc TIMESTAMP Returns the date and time in Coordi­


nated Universal Time (UTC) that the
statement statistics were last updated
with the current plan.

Remarks

This procedure returns one or more rows for each logged statement, with each row indicating the execution
plan that was used.

Specify the stmt_text parameter if you want to see the hash for the specified statement, as well as the logged
results for the statement, if any. If there is no data for the hash, a single row with hash and NULL is returned. If
you want to fetch data for the statement and know the hash, specify the stmt_hash parameter. Otherwise, do
not specify either parameter. Specifying both parameters concurrently is not permitted by the server.

This system procedure returns all of the data collected by the server, unless you provide a parameter to refine
the results. By viewing these statistics, you can identify irregularities that can explain slow running statements.

 Note

If the list of returned statements is long, then it is possible that not all of the data has been captured due to
space limitations.

SAP IQ SQL Reference


922 INTERNAL System Procedures
Privileges

You must have the MONITOR and MANAGE PROFILING privileges on the system procedure.

Side effects

None.

Example

The following query returns performance statistics for each logged statement that has both of the statements
logged:

SELECT *
FROM dbo.sp_find_top_statements( ) TS
INNER JOIN SYS.GTSYSPERFCACHESTMT PS ON TS.stmt_hash = PS.stmt_hash
ORDER BY TS.stmt_hash;

For all data, use OUTER JOIN.

7.6.49 sp_http_listeners system procedure

Lists the HTTP and HTTPS connection listeners used for the specified database.

 Syntax

sp_http_listeners( <database-ID> )

Parameters

database-ID The ID of the database that the HTTP and HTTPS connection listeners are servicing. The
default is the current database ID.

SAP IQ SQL Reference


System Procedures INTERNAL 923
Result set

Column name Data type Description

ip_address VARCHAR (128) Returns the IP address of the connec­


tion listener.

port INTEGER Returns the port number of the connec­


tion listener.

dbname VARCHAR (255) Returns NULL if the connection listener


can service any database; otherwise,
returns the database name.

uri_prefix LONG VARCHAR Returns the prefix of any URI that can
be serviced by the connection listener.
Includes the http:// or https:// identi­
fier, the IP address, the port number
(optional), and the database name if re­
quired.

Remarks

One row appears in the result set for each HTTP and HTTPS connection listener running. A row only appears if
a connection listener is available to execute web services on the specified database.

Privileges

You must have EXECUTE privilege on the system procedure.

To execute this system procedure for other databases, you must have any one of the following system
privileges:

● SERVER OPERATOR
● MONITOR
● MANAGE LISTENERS

 Example

Start a database server using the following command:

dbeng16 database1.db database2.db -xs


http(port=80),http(port=8080;dbn=database1)

Connect to database1 and execute the following statement:

SELECT * FROM dbo.sp_http_listeners();

SAP IQ SQL Reference


924 INTERNAL System Procedures
The database server returns a result set similar to the following:

ip_address port dbname uri_prefix

127.0.0.1 80 NULL http://127.0.0.1/database1/

127.0.0.1 8080 database1 http://127.0.0.1:8080/

If you connect to database2 and run the same statement, then the database server returns the following
result set:

ip_address port dbname uri_prefix

127.0.0.1 80 NULL http://127.0.0.1/database2/

7.6.50 sp_list_mutexes_semaphores system procedure

Returns information about all temporary and permanent mutexes and semaphores, including which
connection is holding each mutex and whether a semaphore is being waited for.

 Syntax

sp_list_mutexes_semaphores( [<oid>] )

Parameters

oid (For internal use only) The unsigned bigint object ID parameter. Use the default parameter value NULL.

Result set

Column name Type Column description

<mutex_semaphore_id> UNSIGNED INTEGER The ID for the object. If the object is


permanent, the ID value is the same as
found SYSMUTEXSEMAPHORE system
view. If the object is temporary, the
value is the internally-generated tempo­
rary ID.

<creator> VARCHAR(128) The owner of the mutex or semaphore

<"name"> VARCHAR(128) The name of the mutex or semaphore

SAP IQ SQL Reference


System Procedures INTERNAL 925
Column name Type Column description

<"type"> VARCHAR(9) The type of object. The value 'mutex:T'


is for transaction-scope mutexes, the
value 'mutex:C' is for connection-scope
mutexes, and the value 'semaphore' is
for semaphores.

<is_temp> CHAR(1) 'Y' or 'N' indicating whether the mutex


or semaphore is temporary.

<is_dropped> CHAR(1) 'Y' or 'N' indicating whether the mutex


or semaphore is dropped but not yet re­
leased. Y indicates that the mutex was
dropped but still needs to be released,
N indicates the mutex was dropped and
released. This value is always N for
semaphores

<start_with> UNSIGNED INTEGER The initial value of the semaphore. This


value is always NULL for mutexes.

<current_count> UNSIGNED INTEGER The current value of the semaphore.


This value is always NULL for mutexes.

<currently_owned_by> LONG VARCHAR A comma-separated list of connection


IDs for connections currently holding
the mutex locked.

<currently_waited_for> LONG VARCHAR A comma-separated list of connection


IDs for connections that are currently
waiting for a semaphore or that are cur­
rently blocked on a mutex.

Remarks

None

Privileges

You must have EXECUTE privilege on the system procedure, and the MONITOR and UPDATE ANY MUTEX
SEMAPHORE system privileges.

SAP IQ SQL Reference


926 INTERNAL System Procedures
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement returns information about all of the mutexes and semaphores in the database:

CALL dbo.sp_list_mutexes_semaphores();

7.6.51 sp_list_secure_feature_keys System Procedure

Returns information about the contents of a directory.

 Syntax

sp_list_secure_feature_keys ( )

Result Set

Column Name Data Type Description

name VARCHAR(128) The name of the secure feature key.

features LONG VARCHAR The secure features enabled by the secure feature key.

Remarks

This procedure returns the names of existing secure feature keys, as well as the set of secure features that can
be enabled by each key.

If the user has the manage_features and manage_keys secure features enabled, then the procedure returns a
list of all secure feature keys.

If the user only has the manage_keys secure feature enabled, then the procedure returns keys that have the
same features or a subset of the same features that the current user has enabled.

SAP IQ SQL Reference


System Procedures INTERNAL 927
Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499]. In addition, you must be the database server owner and have the manage_keys feature
enabled on the connection.

Side Effects

None

7.6.52 sp_login_environment system procedure

Sets connection options when users log in.

 Syntax

sp_login_environment( )

Remarks

The dbo.sp_login_environment procedure is called by the login_procedure database option by default.

Do not edit this procedure. Instead, to change the login environment, set the login_procedure option to point to
a different procedure.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

SAP IQ SQL Reference


928 INTERNAL System Procedures
7.6.53 sp_objectpermission System Procedure

Generates a report on object privileges granted to the specified role, or user name, or the object privileges
granted on the specified object or dbspace.

 Syntax

sp_objectpermission ( [ <object_name> ], [ <object_owner> ],


[ <object_type> ] )

Parameters

object_name

(Optional) The name of an object or dbspace or a user or a role. If not specified, object privileges of the
current user are reported. Default value is NULL.
object_owner

(Optional) The name of the object owner for the specified object name. The object privileges of the
specified object owned by the specified object owner are displayed. This parameter must be specified to
obtain the object privileges of an object owned by another user or role. Default value is NULL.
object_type

(Optional) Valid values are:

● TABLE – column-level object privileges also appear.


● VIEW
● MATERIALIZED VIEW
● SEQUENCE
● PROCEDURE
● FUNCTION
● DBSPACE
● USER

If no value is specified, privileges on all object types are returned. Default value is NULL.

Result Set

Column Name Data Type Description

grantor CHAR(128) The user ID of the grantor

grantee CHAR(128) The user ID of the grantee

object_name CHAR(128) The name of the object

owner CHAR(128) The name of the object owner

SAP IQ SQL Reference


System Procedures INTERNAL 929
Column Name Data Type Description

object_type CHAR(20) The type of object

column_name CHAR(128) The name of the column

permission CHAR(20) The name of the privilege

grantable CHAR(1) Whether or not the privilege is grantable

Remarks

All arguments are optional and can generate these reports:

● If input is an object (table, view, procedure, function, sequence, and so on), procedure displays list of all
roles and user that have different object privilege on the object.
● If input is a role or user, procedure displays list of all object privileges granted to the role or input. When
executing sp_objectpermission to display object privileges of a user or a role, the object privileges that
are inherited through role grants also.
● If input is a dbspace name, procedure displays list of all user or roles that have CREATE privilege on the
specified dbspace.
● By default, object type is NULL and the object privileges for all existing object types matching the specified
object name appear.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].. Users can execute sp_objectpermission to obtain all the object privileges granted
to them. Object owners can also execute this procedure to obtain the object privileges for self-owned objects.
Additional system privileges are needed to obtain object privileges for the following:

Object privileges granted to other users or granted on objects owned by other users

You must also have the MANAGE ANY OBJECT PRIVILEGE system privilege
Object privileges that are granted on objects owned by a role or granted to a role

You must also have the MANAGE ANY OBJECT PRIVILEGE system privilege or be a role administrator on
the role
Object privileges of a dbspace

You must have the MANAGE ANY DBSPACE system privilege

Side Effects

None

SAP IQ SQL Reference


930 INTERNAL System Procedures
Examples

The following GRANT statements are executed:

GRANT SERVER OPERATOR TO r4;


GRANT BACKUP DATABASE TO r3 WITH ADMIN OPTION;
GRANT DROP CONNECTION TO r3 WITH ADMIN ONLY OPTION;
GRANT MONITOR TO r2;GRANT CHECKPOINT TO r1;
GRANT ROLE r2 TO r1 WITH ADMIN OPTION;
GRANT ROLE r3 TO r2 WITH NO ADMIN OPTION;
GRANT ROLE r4 TO r3 WITH ADMIN ONLY OPTION;

Consider these object privileges:

● r5 owns a table named test_tab and a procedure named test_proc in the database.
● u5, which has administrative rights over r5, grants the following privileges:
○ GRANT SELECT ON r5.test_tab TO r2 WITH GRANT OPTION;
○ GRANT SELECT (c1), UPDATE (c1) ON r5.test_tab TO r6 WITH GRANT OPTION;
○ GRANT EXECUTE ON r5.test_proc TO r3;
● u6, which has administrative rights over r6, grants the following privileges:
○ GRANT SELECT (c1), REFERENCES (c1) ON r5.test_tab TO r3;

If sp_objectpermission( 'r1' ) is executed, output is similar to:

grantor grantee object_name

u5 r2 test_tab

u6 r3 test_tab

u6 r3 test_tab

u6 r3 test_proc

(Continued)

owner object_type grantor

r5 TABLE u5

r5 COLUMN u6

r5 COLUMN u6

r5 PROCEDURE u6

(Continued)

grantable column_name privilege

Y NULL SELECT

N c1 SELECT

Y c1 REFERENCES

N NULL EXECUTE

SAP IQ SQL Reference


System Procedures INTERNAL 931
If sp_objectpermission( 'test_tab', 'r5', 'table' ) is executed, output is similar to:

grantor grantee object_name

u5 r2 test_tab

u5 r6 test_tab

u5 r6 test_tab

u6 r3 test_tab

u6 r3 test_tab

(Continued)

owner object_type grantor

r5 TABLE u5

r5 COLUMN u5

r5 COLUMN u5

r5 COLUMN u6

r5 COLUMN u6

(Continued)

column_name privilege grantable

NULL SELECT Y

c1 SELECT Y

c1 UPDATE Y

c1 SELECT N

c1 REFERENCES N

7.6.54 sp_proc_priv System Procedure

Generates a report of the minimum system privileges required to run a stored procedure and pass the privilege
check for the procedure.

 Syntax

sp_proc_priv ( [ <proc_name> ] )

SAP IQ SQL Reference


932 INTERNAL System Procedures
Remarks

If multiple system privileges, separated by a comma, are displayed for a stored procedure, this implies that any
one of them would suffice to execute the stored procedure. If multiple rows are displayed for a stored
procedure, then one system privilege from each row is required to execute the stored procedure.

This procedure lists only those system privileges for a stored procedure that will always pass the privilege
check for the procedure. There may be other system privileges which would pass the privilege check to execute
the procedure given conditions, but these are not listed by this procedure.

Result Set

Column Name Data Type Description

proc_name CHAR(128) The name of the stored procedure.

privilege LONG VARCHAR The privileges required to pass privilege check.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

Side Effects

None

Examples

If sp_proc_priv is invoked without any parameter specified, the procedure displays all the stored procedures
and the system privileges required to execute each. Stored procedures which do not require any system
privileges for their execution are not displayed.

If sp_proc_priv () is executed, output would be similar to the following:

proc_name privileges

sp_iqrowdensity MONITOR, MANAGE ANY DBSPACE, CREATE ANY INDEX, ALTER ANY INDEX, CREATE
ANY OBJECT, ALTER ANY OBJECT

sp_iqworkmon MONITOR

SAP IQ SQL Reference


System Procedures INTERNAL 933
proc_name privileges

sp_iqindexsize MANAGE ANY DBSPACE, ALTER ANY INDEX, ALTER ANY OBJECT

sp_addlogin MANAGE ANY USER

sp_iqemptyfile BACKUP DATABASE, SERVER OPERATOR, ALTER DATABASE

sp_iqemptyfile INSERT ANY TABLE, UPDATE ANY TABLE, DELETE ANY TABLE, ALTER ANY TABLE,
LOAD ANY TABLE, TRUNCATE ANY TABLE, ALTER ANY OBJECT

... ...

If sp_proc_priv is invoked with a procedure name parameter, it returns the system privileges required to
execute that procedure. If no system privileges are required, it lists "No Privilege Required" against the
procedure.

proc_name privileges

sp_iqindexsize MANAGE ANY DBSPACE, ALTER ANY INDEX

An error message appears if the procedure does not exist.

7.6.55 sp_property_history system procedure

Returns values for all database server properties tracked by the database.

 Syntax

sp_property_history( <property>, <min_ticks> )

Parameters

property Use this VARCHAR(255) to specify the name of the database server property to report. If NULL,
then all currently monitored properties are reported. The default is NULL.
min_ticks Specify a tick value to return all recorded property values with a ticks value that is equal to or
greater than the specified tick value. The default is NULL.

Result set

Column name Data type Description

name VARCHAR(255) The name of the database server prop­


erty.

SAP IQ SQL Reference


934 INTERNAL System Procedures
Column name Data type Description

ticks UNSIGNED BIGINT A monotonically increasing value that


chronologically orders property values.

time_recorded TIMESTAMP WITH TIME ZONE The system time when this value was
recorded.

time_delta UNSIGNED INTEGER The number of milliseconds since the


previous recording, independent of sys­
tem time.

value DOUBLE The current value of the database


server property.

value_delta DOUBLE The change in the database property


value since the previous recording.

Remarks

This system procedure returns results for database server properties being tracked by any database running
on the database server, as well as by the -phl database server option. The database server uses ticks,
measured by your computer's system clock, to track the chronological order in which property values are
recorded. Each recorded value has a tick value that increases monotonically, along with an associated
timestamp measured in GMT.

If <property-name> is NULL, then all database server property values are returned.

If <min_ticks> is NULL, then all property values for the selected properties (or all properties if <property-
name> is NULL) are returned.

If the database is restarted, then property history data is only kept for properties currently being tracked by
another running database.

If the database server is restarted, then property history data and tracking settings are lost. Desired tracking
settings must be re-supplied.

Database-specific property tracking settings are also lost if all [of] the following are true:

● The database is restarted.


● No other database running on the database server is tracking the database server property.
● The database server property is not being tracked at the database server level.

 Tip

To maintain database-specific tracking settings, create a database start-up event to mimic the persistence
of these settings.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 935
You must have the MANAGE ANY PROPERTY HISTORY system privilege.

Side effects

None

 Example

To list all of the recorded database server property values in descending order, execute the following
statement:

SELECT * FROM dbo.sp_property_history( )


ORDER BY ticks desc;

7.6.56 sp_remote_columns system procedure

Produces a list of the columns in a remote table, and a description of their data types.

 Syntax

sp_remote_columns(
<@server_name>
, <@table_name>
[, <@table_owner>
[, <@table_qualifier> ] ]
)

Parameters

@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>. The default is %.
@table_qualifier

Use this optional CHAR(128) parameter to specify the name of the database in which <table_name> is
located. The default is %.

SAP IQ SQL Reference


936 INTERNAL System Procedures
Result set

Column name Data type Description

database CHAR(128) The database name.

owner CHAR(128) The database owner name.

table_name CHAR(128) The table name.

column_name CHAR(128) The name of a column.

domain_id SMALLINT An INTEGER that 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 charac­
ters.

scale SMALLINT The meaning of this column depends


on the data type. For NUMERIC 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 column.

Remarks

The server must be defined with the CREATE SERVER statement to use this system procedure.

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.

If the table does not exist on the remote server, the procedure returns an empty result set.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 937
Standards

N/A

 Example

The following example returns information about the columns in the ULProduct table on the remote SAP IQ
database server named RemoteSA. The table owner is DBA.

CALL dbo.sp_remote_columns( 'RemoteSA', 'ULProduct', 'DBA', null );

The following example returns information about the columns in the SYSOBJECTS table in the Adaptive
Server Enterprise database Production using the remote server named RemoteASE. The table owner is
unspecified.

CALL dbo.sp_remote_columns( 'RemoteASE', 'sysobjects', null, 'Production' );

The following example returns information about the columns in the Customers table in the Microsoft
Access database c:\users\me\documents\MyAccesDB.accdb using the remote server MyAccessDB.
The Microsoft Access database does not have a table owner so NULL is specified.

CALL dbo.sp_remote_columns( 'MyAccessDB', 'Customers', null, 'c:\\users\\me\


\documents\\MyAccesDB.accdb' );

7.6.57 sp_remote_exported_keys system procedure

Provides information about tables with foreign keys on a specified primary table.

 Syntax

sp_remote_exported_keys(
<@server_name>
, <@table_name>
[, <@table_owner>
[, <@table_qualifier> ] ]
)

Parameters

@server_name

Use this CHAR(128) parameter to specify the server the primary table is located on.
@table_name

Use this CHAR(128) parameter to specify the table containing the primary key.
@table_owner

Use this optional CHAR(128) parameter to specify the primary table's owner. The default is '%'.

SAP IQ SQL Reference


938 INTERNAL System Procedures
@table_qualifier

Use this optional CHAR(128) parameter to specify the database containing the primary table. The default
is '%'.

Result set

Column name Data type Description

pk_database CHAR(128) The database containing the primary


key table.

pk_owner CHAR(128) The owner of the primary key table.

pk_table CHAR(128) The primary key table.

pk_column CHAR(128) The name of the primary key column.

fk_database CHAR(128) The database containing the foreign key


table.

fk_owner CHAR(128) The foreign key table's owner.

fk_table CHAR(128) The foreign key table.

fk_column CHAR(128) The name of the foreign key column.

key_seq SMALLINT The key sequence number.

fk_name CHAR(128) The foreign key name.

pk_name CHAR(128) The primary key name.

Remarks

The server must be defined with the CREATE SERVER statement to use this system procedure.

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.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 939
Side effects

None

 Example

The following example returns information about the foreign key relationships in the ULEmployee table on
the remote server named RemoteSA:

CALL dbo.sp_remote_exported_keys( 'RemoteSA', 'ULEmployee', 'DBA' );

7.6.58 sp_remote_imported_keys system procedure

Provides information about remote tables with primary keys that correspond to a specified foreign key.

 Syntax

sp_remote_imported_keys(
<@server_name>
, <@table_name>
[, <@table_owner>
[, <@table_qualifier> ] ]
)

Parameters

@server_name

Use this CHAR(128) parameter to specify the server the foreign key table is located on. A value is required
for this parameter.
@table_name

Use this CHAR(128) parameter to specify the table containing the foreign key. A value is required for this
parameter.
@table_owner

Use this optional CHAR(128) parameter to specify the foreign key table's owner. The default is '%'.
@table_qualifier

Use this optional CHAR(128) parameter to specify the database containing the foreign key table. The
default is '%'.

SAP IQ SQL Reference


940 INTERNAL System Procedures
Result set

Column name Data type Description

pk_database CHAR(128) The database containing the primary


key table.

pk_owner CHAR(128) The owner of the primary key table.

pk_table CHAR(128) The primary key table.

pk_column CHAR(128) The name of the primary key column.

fk_database CHAR(128) The database containing the foreign key


table.

fk_owner CHAR(128) The foreign key table's owner.

fk_table CHAR(128) The foreign key table.

fk_column CHAR(128) The name of the foreign key column.

key_seq SMALLINT The key sequence number.

fk_name CHAR(128) The foreign key name.

pk_name CHAR(128) The primary key name.

Remarks

The server must be defined with the CREATE SERVER statement to use this system procedure.

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.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

SAP IQ SQL Reference


System Procedures INTERNAL 941
 Example

The following example returns the tables with primary keys that correspond to a foreign key on the ULOrder
table on the remote server named RemoteSA:

CALL dbo.sp_remote_imported_keys( 'RemoteSA', 'ULOrder', 'DBA' );

7.6.59 sp_remote_primary_keys system procedure

Provides primary key information about remote tables using remote data access.

 Syntax

sp_remote_primary_keys(
<@server_name>
, <@table_name>
[, <@table_owner>
[, <@table_qualifier> ] ]
)

Parameters

@server_name

Use this CHAR(128) parameter to specify the remote server name.


@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 the remote table. The default is '%'.
@table_qualifier

Use this optional CHAR(128) parameter to specify the name of the remote database. The default is '%'.

Result set

Column name Data type Description

database CHAR(128) The name of the remote database.

owner CHAR(128) The owner of the table.

table_name CHAR(128) The name of the table.

SAP IQ SQL Reference


942 INTERNAL System Procedures
Column name Data type Description

column_name CHAR(128) The name of the primary key column.

key_seq SMALLINT The primary key sequence number.

pk_name CHAR(128) The primary key name.

Remarks

This system procedure provides primary key information about remote tables using remote data access.

Because of differences in the underlying ODBC calls, the information returned differs slightly from the catalog/
database value depending upon the remote data access class that is specified for the server.

Privileges

You must have EXECUTE privilege on the system procedure.

Standards

N/A

Side effects

None

 Example

The following example returns information about the primary keys in tables owned by DBA in a SAP IQ
remote server named RemoteSA.

CALL dbo.sp_remote_primary_keys( 'RemoteSA', null, 'DBA' );

To get a list of the primary keys in all the tables owned by Fred in the production database in an Adaptive
Server Enterprise server named RemoteASE:

CALL dbo.sp_remote_primary_keys( 'RemoteASE', null, 'Fred', 'production' );

SAP IQ SQL Reference


System Procedures INTERNAL 943
7.6.60 sp_remote_tables system procedure

Returns a list of the tables on a server.

 Syntax

sp_remote_tables(
<@server_name>
[, <@table_name>
[, <@table_owner>
[, <@table_qualifier>
[, <@with_table_type> ] ] ] ]
)

Parameters

@server_name

Use this CHAR(128) parameter to specify the remote server name.


@table_name

Use this optional CHAR(128) parameter to specify the name of the remote table. The default is '%'.
@table_owner

Use this optional CHAR(128) parameter to specify the owner of the remote table. The default is '%'.
@table_qualifier

Use this optional CHAR(128) parameter to specify the database in which <table_name> is located. The
default is '%'.
@with_table_type

Use this optional BIT parameter to specify the inclusion of remote table types. The default is 0. Specify 1 if
you want the result set to include a column that lists table types or specify 0 if you do not.

Result set

Column name Data type Description

database CHAR(128) The name of the remote database.

owner CHAR(128) The name of the table owner.

table_name CHAR(128) The name of the table.

table_type CHAR(128) Specifies the table type. The value de­


pends on the type of remote server. For
example, TABLE, VIEW, SYS, and GBL
TEMP are possible values.

SAP IQ SQL Reference


944 INTERNAL System Procedures
Remarks

The server must be defined with the CREATE SERVER statement to use this system procedure.

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.

Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

Standards

N/A

 Example

The following example returns information about the tables owned by DBA in a SAP IQ remote server
named RemoteSA.

CALL dbo.sp_remote_tables( 'RemoteSA', null, 'DBA' );

To get a list of all the tables owned by Fred in the production database in an Adaptive Server Enterprise
server named RemoteASE:

CALL dbo.sp_remote_tables( 'RemoteASE', null, 'Fred', 'production' );

To get a list of all the Microsoft Excel worksheets available from an ODBC data source referenced by a
server named RemoteExcel:

CALL dbo.sp_remote_tables( 'RemoteExcel' );

SAP IQ SQL Reference


System Procedures INTERNAL 945
7.6.61 sp_servercaps system procedure

Displays information about a remote server's capabilities.

 Syntax

sp_servercaps( <@server_name> )

Parameters

@server_name

Use this CHAR(128) parameter to specify a server defined with the CREATE SERVER statement.
<@server_name> is the same server name used in the CREATE SERVER statement.

Results

Column Type Description

capid INTEGER The capability identifier.

capname CHAR(128) The name of the capability.

capvalue CHAR(128) The setting of the capability, usually T


(true) or F (false).

Remarks

The server must be defined with the CREATE SERVER statement to use this system procedure.

This procedure displays information about a remote server's capabilities. The capability information is used to
determine how much of a SQL statement can be forwarded to a remote server. The ISYSCAPABILITY system
table, which lists the server capabilities, is not populated until a connection is made to the first remote server.

Standards

N/A

SAP IQ SQL Reference


946 INTERNAL System Procedures
Privileges

You must have EXECUTE privilege on the system procedure.

Side effects

None

 Example

To display information about the remote server RemoteSA:

CALL dbo.sp_servercaps( 'RemoteSA' );

7.6.62 sp_start_listener system procedure

Starts a new connection listener.

 Syntax

sp_start_listener(
<type>
, <address>
[ , <options> ]
)

Parameters

type

Use this VARCHAR (12) parameter to specify the type of connection listener to start. The value is one of
sharedmemory, shmem, tcpip, tcp, http, or https.
address

Use this VARCHAR (100) parameter to specify the address of the connection listener to start. The address
is a numeric IP address with a port number (for example, 0.0.0.0:9998) separated by a colon (:) or an IP
address without a port number. For IPv6 addresses with a port number, enclose the address in parentheses
and then append the colon and port number. If you do not specify a port number, then the default port
(TCPIP:2638, HTTP:80, HTTPS:443) is used.

If you specify a port number for TCP/IP and HTTP(S), then the address parameter can be a port number
between 1 and 65535. In this case, listeners are started on all available IP addresses using that port
number, and the database server acts as though the port number was supplied as the ServerPort (PORT)
protocol option to the -x TCPIP or -xs HTTPS(S) database server options.

SAP IQ SQL Reference


System Procedures INTERNAL 947
To indicate all available IPv4 or IPv6 addresses, specify an IP address of "0.0.0.0" or "(::)".

The personal database server only accepts loopback IP addresses, for example 127.0.0.1.

This parameter is ignored for shared memory. For shared memory, specify NULL.
options

Use this LONG VARCHAR parameter to specify a semicolon-delimited list of network protocol options. This
parameter is ignored if you are starting shared memory or TCP/IP connection listeners.

 Note

You cannot specify either the ServerPort (PORT) protocol option or the MyIP (ME) protocol option
when using the <options> parameter.

Remarks

The new connection listener uses whichever available port number is found first from the following list:

● The port given by the address parameter.


● The default port (2638 for TCP/IP, 80 for HTTP, and 443 for HTTPS).

TCP/IP connection listeners use the encryption setting specified by the -ec database server option when the
database server is started.

Shared memory connection listeners can be created regardless of whether or not the -es database server
option was specified when the database server was started. Shared memory connection listeners started with
the sp_start_listener system procedure always allow unencrypted connections to the database server.

Privileges

You must have the MANAGE LISTENERS system privilege.

 Example

Assume that a database server is started allowing local connections only. A problem occurs that is
convenient to debug remotely. To allow remote connections to the database server using port 9998, a user
connects to the database server by using shared memory and executes the following statement:

CALL dbo.sp_start_listener ( 'tcpip' , '0.0.0.0:9998' );

SAP IQ SQL Reference


948 INTERNAL System Procedures
7.6.63 sp_stop_listener system procedure

Stops an existing connection listener.

 Syntax

sp_stop_listener(
<type>
, <address>
[ , <force> ]
)

Parameters

type

Use this VARCHAR (12) parameter to specify the type of connection listener to stop. The value is one of
sharedmemory, shmem, tcpip, tcp, http, https.
address

Use this VARCHAR (100) parameter to specify the address of the connection listener to stop. The address
is an IP address with a port number separated by a colon (:) or an IP address without a port number. For
IPv6 addresses with a port number, enclose the address in parentheses and then append the colon and
port number. If a port number is not specified, the default port (TCPIP:2638, HTTP:80, HTTPS:443) is
used. For TCP/IP and HTTP(S), the address parameter can be a port number between 1 and 65535. If you
only specify a port number, then the database server stops any listeners of the specified type using that
port.

To indicate all available IPv4 or IPv6 addresses, specify an IP address of "0.0.0.0" or "(::)".

The personal database server only accepts loopback IP addresses, for example 127.0.0.1.

This parameter is ignored for shared memory. For shared memory, specify NULL.
force

Specify 1 to force the connection listener to stop if it is the last network driver listener running. The default
is 0.

Remarks

The sp_stop_listener system procedure only stops new connections from being started on the connection
listener. Existing connections are not changed.

Set the <force> parameter to 1 if one of the following is true:

● The connection listener is the last TCP/IP listener and shared memory is not enabled.
● The connection listener is shared memory and there are no TCP/IP listeners running.
● The connection listener is the last HTTP listener and there are no HTTPS listeners running.

SAP IQ SQL Reference


System Procedures INTERNAL 949
● The connection listener is the last HTTPS listener and there are no HTTP listeners running.

Privileges

You must have the MANAGE LISTENERS system privilege.

 Example

Assume that a database server is started allowing local connections only. A problem occurs that is
convenient to debug remotely. To allow remote connections to the database server using port 9998, a user
connects to the database server by using shared memory and executes the following statement:

CALL dbo.sp_start_listener ( 'tcpip' , '0.0.0.0:9998' );

Once the problem has been solved, shut down the connection listener by executing the following
statement:

CALL dbo.sp_stop_listener ( 'tcpip' , '0.0.0.0:9998' );

7.6.64 sp_sys_priv_role_info System Procedure

Generates a report to map a system privilege to the corresponding system role. A single row is returned for
each system privilege.

 Syntax

sp_sys_priv_role_info()

Result Set

Column Name Data Type Description

sys_priv_name CHAR(128) The name of the system privilege

sys_priv_role_name CHAR(128) The role name corresponding to the system privilege.

sys_priv_id UNSIGNED INT The id of the system privilege.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


950 INTERNAL System Procedures
Side Effects

None

7.6.65 sp_top_k_statements system procedure

Returns a specified number of statement/plan combinations with the highest maximum runtimes.

 Syntax

sp_top_k_statements( [ <k> ] )

Parameters

Use this optional UNSIGNED INTEGER to specify the number of records to return. The default value is
1000.

Result set

Column name Data type Description

stmt_hash UNSIGNED BIGINT Returns the statement identifier.

owner_name CHAR(128) Returns the name of the owner of the


stored procedure. The value is NULL if
the statement is not part of a stored
procedure, user-defined function, trig­
ger, or event. The value may also be
NULL if the statement is executed as
part of a stored procedure and the
stored procedure is subsequently drop­
ped. A statement executed as part of a
stored procedure gets a hash that is re­
lated to the procedure, not the state­
ment text.

SAP IQ SQL Reference


System Procedures INTERNAL 951
Column name Data type Description

proc_name CHAR(128) Returns the name of the owner of the


stored procedure. The value is NULL if
the statement is not part of a stored
procedure, user-defined function, trig­
ger, or event. The value may also be
NULL if the statement is executed as
part of a stored procedure and the
stored procedure is subsequently drop­
ped. A statement executed as part of a
stored procedure gets a hash that is re­
lated to the procedure, not the state­
ment text.

reusable_stmt_id UNSIGNED INTEGER Returns a unique identifier assigned to


the statement within a procedure (not
necessarily a line number). The value is
NULL if the statement is not part of a
stored procedure, user-defined func­
tion, trigger, or event.

plan_hash UNSIGNED BIGINT Returns the plan identifier.

max_seconds DOUBLE Returns the maximum runtime ob­


served for the statement when exe­
cuted with the current plan.

avg_seconds DOUBLE Returns the average runtime of the


statement with the current plan.

stddev_seconds DOUBLE Returns the standard deviation of the


runtimes of the statement with the cur­
rent plan. The standard deviation is
computed by using the sum of squares
method. The value is NULL if only a sin­
gle execution of a statement has been
observed so far.

max_blocking_seconds DOUBLE Returns the maximum blocking time


observed for the statement with the
current plan.

avg_blocking_seconds DOUBLE Returns the average blocking time ob­


served for the statement with the cur­
rent plan.

num_exec UNSIGNED BIGINT Returns the number of times the state­


ment was executed using the current
plan.

total_num_rows UNSIGNED BIGINT Returns the total number of rows re­


turned or modified by the statement
over all executions performed with the
current plan.

last_max_time _utc TIMESTAMP Returns the date and time in Coordi­


nated Universal Time (UTC) that the
maximum runtime was last updated.

SAP IQ SQL Reference


952 INTERNAL System Procedures
Column name Data type Description

last_time_utc TIMESTAMP Returns the date and time in Coordi­


nated Universal Time (UTC) that the
statement statistics were last updated
with the current plan.

Remarks

Use this system procedure to determine which statement/plan combination is taking the longest to run.
Specify the number of longest running statements returned with the (<k>) parameter.

 Note

If the list of returned statements is long, then it is possible that not all of the data has been captured due to
space limitations.

Privileges

You must have the MONITOR and MANAGE PROFILING privileges on the system procedure.

Side effects

None.

Example

The following query returns the top statements with the longest maximum observed runtime:

SELECT *
FROM dbo.sp_top_k_statements( ) TS
LEFT OUTER JOIN SYS.GTSYSPERFCACHESTMT PS ON TS.stmt_hash = PS.stmt_hash
ORDER BY TS.stmt_hash;

SAP IQ SQL Reference


System Procedures INTERNAL 953
7.6.66 sp_tsql_environment system procedure

Sets connection options when users connect from jConnect or Open Client applications.

 Syntax

sp_tsql_environment( )

Remarks

The sp_login_environment procedure is the default procedure specified by the login_procedure database
option. For each new connection, the procedure specified by login_procedure is called. If the connection uses
the TDS communications protocol (that is, if it is an Open Client or jConnect connection), then
sp_login_environment in turn calls sp_tsql_environment.

This procedure sets database options so that they are compatible with default Adaptive Server Enterprise
behavior.

To change the default behavior, create new procedures and alter your login_procedure option to point to these
new procedures.

Below is the list of the options set by sp_tsql_environment procedure:

if db_property( 'IQStore' ) = 'Off' then


-- SAP
IQ 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';
SET TEMPORARY OPTION on_tsql_error='CONTINUE';
SET TEMPORARY OPTION isolation_level='1';
SET TEMPORARY OPTION date_format='YYYY-MM-DD';
SET TEMPORARY OPTION timestamp_format='YYYY-MM-DD HH:NN:SS.SSS';
SET TEMPORARY OPTION time_format='HH:NN:SS.SSS';
SET TEMPORARY OPTION date_order='MDY';
SET TEMPORARY OPTION escape_character='OFF';

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


954 INTERNAL System Procedures
Side effects

None

 Example

The example below calls the sp_tsql_environment procedure:

CALL dbo.sp_tsql_environment();

7.6.67 sp_use_secure_feature_key System Procedure

Enables an existing secure feature key.

 Syntax

sp_use_secure_feature_key ( <name>, <sfkey> )

Parameter

name

A VARCHAR (128) name of the secure feature key to be enabled.


sfkey

A CHAR (128) authorization key for the secure feature key being enabled. The authorization key must be at
least six characters.

Remarks

This procedure enables the secure features that are turned on by the specified secure feature key.

Privileges

To run this procedure, you must have EXECUTE privilege on the procedure. See GRANT EXECUTE Privilege
Statement [page 1499].

SAP IQ SQL Reference


System Procedures INTERNAL 955
Side Effects

None

7.6.68 xp_cmdshell system procedure

Carries out an operating system command from a procedure.

 Syntax

xp_cmdshell(
<command>
[, <redir_output> | 'no_output' ]
)

Parameters

command

Use this VARCHAR(8000) parameter to specify a system command. The default is NULL.
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. The default value is ' '.

Returns

This function returns an INTEGER exit code.

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.

Use the sa_enable_auditing_type and sa_disable_auditing_type system procedures to enable and disable
auditing of the xp_cmdshell system procedure (using the xp_cmdshell type). When auditing is enabled for

SAP IQ SQL Reference


956 INTERNAL System Procedures
xp_cmdshell, all invocations of the xp_cmdshell procedure are logged to the audit log, including the user that
executed the procedure, and the parameters that were passed to the procedure.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SERVER OPERATOR system
privilege.

 Example

The following statement lists the files in the current directory in the file c:\temp.txt:

CALL dbo.xp_cmdshell( 'dir > c:\\temp.txt' );

The following statement carries out the same operation, but does so without displaying a Command
window.

CALL dbo.xp_cmdshell( 'dir > c:\\temp.txt', 'no_output' );

7.6.69 xp_get_mail_error_code system procedure

Returns information about the most recent SMTP or MAPI error.

 Syntax

xp_get_mail_error_code( )

Returns

This function returns an INTEGER value representing the SMTP or MAPI error code.

Remarks

When the return value of a mail procedure (xp_startmail, xp_startsmtp, xp_sendmail, xp_stopmail, and
xp_stopsmtp) is -1, use this function to retrieve the SMTP or MAPI error code.

When the return value of a mail procedure is 5, 6, or 7, use this function to retrieve the error number for the
most recent socket error.

SAP IQ SQL Reference


System Procedures INTERNAL 957
If MAPI is being used, the value returned is the return code of the MAPI function. If SMTP is being used, the
value returned is either an SMTP error code (and xp_get_mail_error_text returns the SMTP error text) or an
error number (and xp_get_mail_error_text returns an empty string).

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

Side effects

None

 Example

This example gets the most recent SMTP or MAPI error code.

SELECT dbo.xp_get_mail_error_code( )

This example uses SMTP to initiate the sending of a plain text message.

BEGIN
DECLARE err_smtp INTEGER;
DECLARE err_code INTEGER;
DECLARE err_msg LONG VARCHAR;
SELECT dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' )
INTO err_smtp;
SELECT dbo.xp_get_mail_error_code( ), xp_get_mail_error_text( ) INTO
err_code, err_msg;
SELECT err_smtp, err_code, err_msg;
END;

7.6.70 xp_get_mail_error_text system procedure

Returns the most recent SMTP error or status message text.

 Syntax

xp_get_mail_error_text( )

Return value

This function returns a LONG VARCHAR value representing the SMTP or MAPI error or status message text. If
no error text is available, an empty string or NULL is returned.

SAP IQ SQL Reference


958 INTERNAL System Procedures
Remarks

Use this function to obtain the error or status message text for any of the mail procedures (xp_startmail,
xp_startsmtp, xp_sendmail, xp_stopmail, and xp_stopsmtp).

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

Side effects

None

 Example

This example gets the most recent SMTP or MAPI message text.

SELECT xp_get_mail_error_text( )

This example uses SMTP to initiate the sending of a plain text message.

BEGIN
DECLARE err_smtp INTEGER;
DECLARE err_code INTEGER;
DECLARE err_msg LONG VARCHAR;
SELECT dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' )
INTO err_smtp;
SELECT dbo.xp_get_mail_error_code( ), xp_get_mail_error_text( ) INTO
err_code, err_msg;
SELECT err_smtp, err_code, err_msg;
END;

7.6.71 xp_getenv system procedure

Returns the value of an environment variable.

 Syntax

xp_getenv( <environment_variable> )

SAP IQ SQL Reference


System Procedures INTERNAL 959
Parameters

environment_variable

Use this VARCHAR(8000) parameter to specify the environment variable. This parameter is case
insensitive on Windows operating systems and case sensitive on all other operating systems, independent
of the case sensitivity of the database. The default value is NULL.

Returns

This function returns a LONG NVARCHAR value.

Remarks

If the environment variable specified is NULL or not set, NULL is returned.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SERVER OPERATOR system
privilege.

The GETENV feature must be enabled for the connection (-sf server option).

Side effects

None

 Example

The following example uses the xp_getenv system procedure to return the value of the environment
variable PATH.

SELECT CAST( dbo.xp_getenv( 'PATH' ) AS LONG VARCHAR );

The following example uses the xp_getenv and sa_split_list system procedures to return the value of the
Windows environment variable PATH as a list. Use ':' as the separator character on Unix operating systems.

CALL sa_split_list( CAST( dbo.xp_getenv( 'PATH' ) AS LONG VARCHAR ), ';' );

SAP IQ SQL Reference


960 INTERNAL System Procedures
The following example uses the environment variable NONEXISTENT, which is assumed to not exist.
Therefore, the query is expected to return NULL.

SELECT dbo.xp_getenv( 'NONEXISTENT' );

7.6.72 xp_msver system procedure

Retrieves version and name information about the database server.

 Syntax

xp_msver( <the_option> )

Parameters

the_option

Use this CHAR(254) parameter to specify a string. The string must be one of the following, enclosed in
string delimiters.

Argument Description

ProductName Returns the name of the product. ProductName is the de­


fault argument value.

ProductVersion Returns the version number, followed by the build number.


The format is as follows:

17.1.0.1691

CompanyName Returns the name of the company.

FileDescription Returns the name of the product, followed by the name of


the operating system.

LegalCopyright Returns a copyright string for the software.

LegalTrademarks Returns trademark information for the software.

Returns

This function returns a CHAR(254) value.

SAP IQ SQL Reference


System Procedures INTERNAL 961
Remarks

This functions returns product, company, version, and other information.

Privileges

You must have EXECUTE privilege on the system procedure.

 Example

The following statement requests the version and operating system description:

SELECT dbo.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

17.1.0.1691 SAP IQ Windows7

7.6.73 xp_read_file system procedure

Reads a file and returns the contents of the file as a LONG BINARY variable.

 Syntax

xp_read_file(
<filename>
[, <lazy> ]
)

Parameters

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 0, 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 0, or non-lazy.

SAP IQ SQL Reference


962 INTERNAL System Procedures
Returns

This function returns the contents of the named file as a LONG BINARY value. If the file does not exist or cannot
be read, NULL is returned.

Remarks

The <filename> is relative to the starting directory of the database server.

The function can be useful for inserting entire documents or images stored in files into tables. If the file cannot
be read, the function returns NULL.

If the data file is in a different character set, you can use the CSCONVERT function to convert it.

You can also use the CSCONVERT function to address character set conversion requirements you have when
using the xp_read_file system procedure.

If disk sandboxing is enabled, the file referenced in <filename> must be in an accessible location.

The function returns NULL if the specified file does not exist.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the READ FILE system privilege.

 Example

The following statement inserts an image into a column named Photo of the Products table.

UPDATE Products
SET Photo=dbo.xp_read_file( 'c:\\sqlany\\scripts\\adata\
\HoodedSweatshirt.jpg' )
WHERE Products.ID=600;

The following statement reads a text file and displays each line with a line number.

SELECT * FROM sa_split_list( CAST( dbo.xp_read_file( '\\Windows\\win.ini' )


AS LONG VARCHAR ), 0x0a );

7.6.74 xp_scanf system procedure

Extracts substrings from an input string using a format string.

 Syntax

xp_scanf(

SAP IQ SQL Reference


System Procedures INTERNAL 963
<input_buffer>
, <format>
[ , <param1> [, <param2> ... ] ]
)

Parameters

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 place holders (%s) for each
<param> argument. There can be up to fifty place holders in the <format> argument, and there must be
the same number of place holders as <param> arguments.
param1, param2, ...

Use one or more of these CHAR(254) parameters to store the substrings extracted from
<input_buffer>. There can be up to 50 of these parameters.

Privileges

You must have EXECUTE privilege on the system procedure.

Remarks

The xp_scanf system procedure extracts substrings from an input string using the specified format, and puts
the results in the specified parameter values.

Only the %s string format is supported. Other format specifiers such as %d and %f are not supported and
scanning the input string stops if they are encountered.

 Example

The following statements extract the substrings Hello and World! from the input buffer Hello World!, and
puts them into variables string1 and string2, and then selects them:

CREATE VARIABLE string1 CHAR( 254 );


CREATE VARIABLE string2 CHAR( 254 );
CALL dbo.xp_scanf( 'Hello World!', '%s %s', string1, string2 );
SELECT string1, string2;

The following statements show how to take a date string and split it into its year, month, and day
components:

CREATE VARIABLE ymd LONG VARCHAR;


CREATE VARIABLE year CHAR( 254 );

SAP IQ SQL Reference


964 INTERNAL System Procedures
CREATE VARIABLE month CHAR( 254 );
CREATE VARIABLE day CHAR( 254 );
SET ymd = '2014/11/23';
SET ymd = REPLACE(ymd, '/', ' ');
CALL dbo.xp_scanf( ymd, '%s %s %s', year, month, day );
SELECT ymd, year, month, day;

7.6.75 xp_sendmail system procedure

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.

 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> ]
)

Parameters

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.

SAP IQ SQL Reference


System Procedures INTERNAL 965
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 SAP IQ. The default is
NULL.
"message"

This LONG VARCHAR parameter specifies the message contents. The default is NULL. The "message"
parameter name requires double quotes around it because MESSAGE is a reserved word.
attachname

This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The
default is NULL.
attach_result

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
0.
echo_error

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
1.
include_file

This LONG VARCHAR parameter specifies an attachment file. The default is NULL.
no_column_header

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
0.
no_output

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
0.
width

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
80.
separator

This CHAR(1) parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The default is
CHAR(9).
dbuser

This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The
default is guest.
dbname

This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The
default is master.
type

This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. The
default is NULL.

SAP IQ SQL Reference


966 INTERNAL System Procedures
include_query

This INTEGER parameter is provided for Transact-SQL compatibility. It is not used by SAP IQ. 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.

To set headers manually, set the 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.

Returns

This function returns an INTEGER status code.

Remarks

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.

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.

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.

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

If <message-body> contains lines that are longer than 998 characters, the SMTP server may insert newline
characters as well as ! characters into the body of the email. To avoid these extra characters, ensure
<message-body> does not contain lines longer than 998 characters.

SAP IQ SQL Reference


System Procedures INTERNAL 967
Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

 Example

This example uses SMTP to send a plain text message.

CALL dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' );


CALL dbo.xp_sendmail( recipient='jane.smith@sample.com',
subject='This is my subject line',
"message"='This text is the body of my email.\n' );
CALL dbo.xp_stopsmtp( );

This example uses SMTP to send an HTML formatted message with an attachment.

CALL dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' );


CALL dbo.xp_sendmail( recipient='jane.smith@sample.com',
subject='HTML mail example with attachment',
"message"='Plain text.<BR><BR><B>Bold text.</B><BR><BR>' ||
'<a href="www.sap.com">SAP Home Page</a>',
content_type = 'text/html',
include_file = '\\temp\\sendmail2.sql' );
CALL dbo.xp_stopsmtp( );

This example uses SMTP to send an inline HTML formatted message with an attachment.

CALL dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' );


CALL dbo.xp_sendmail( recipient='jane.smith@sample.com',
subject='Inline HTML mail example with attachment',
"message"='Content-Type: text/html;\nContent-Disposition:
inline; \n\n' ||
'Plain text.<BR><BR><B>Bold text.</B><BR><BR>' ||
'<a href="www.sap.com">SAP Home Page</a>',
content_type = 'ASIS',
include_file = '\\temp\\sendmail3.sql' );
CALL dbo.xp_stopsmtp( );

This example uses SMTP to send an inline HTML formatted message with a signature and two
attachments, one of which is a ZIP file.

BEGIN
DECLARE content LONG VARCHAR;
SET content =
'Content-Type: multipart/mixed; boundary="xxxxx";\n' ||
'This part of the email should not be shown. If this ' ||
'is shown then the email client is not MIME compatible\n\n' ||
'--xxxxx\n' ||
'Content-Type: text/html;\n' ||
'Content-Disposition: inline;\n\n' ||
'Plain text.<BR><BR><B>Bold text.</B><BR><BR>' ||
'<a href="www.sap.com">SAP Home Page</a>\n\n' ||
xp_read_file( '\\temp\\johndoe.sig.html' ) ||
'--xxxxx\n' ||
'Content-Type: application/zip; name="sendmail4.zip"\n' ||
'Content-Transfer-Encoding: base64\n' ||
'Content-Disposition: attachment; filename="sendmail4.zip"\n\n' ||
base64_encode( xp_read_file( '\\temp\\sendmail4.zip' ) ) ||
'\n\n' ||
'--xxxxx--\n';
CALL dbo.xp_startsmtp( 'doe@sample.com', 'corporatemail.sample.com' );
CALL dbo.xp_sendmail( recipient='jane.smith@sample.com',

SAP IQ SQL Reference


968 INTERNAL System Procedures
subject='Inline HTML mail example with signature and 2
attachments',
"message"=content,
content_type = 'ASIS',
include_file = '\\temp\\sendmail4.sql' );
CALL dbo.xp_stopsmtp( );
END

7.6.76 xp_sprintf system procedure

Builds a result string from a set of input strings.

 Syntax

xp_sprintf(
<buffer>
, <format>
[ , <param1> [, <param2> ... ] ]
)

Parameters

buffer

This is a CHAR(254) OUT parameter that is filled in with the formatted result.
format

Use this CHAR(254) parameter to specify how to format the result string, using place holders (%s) for
each <param> argument. There can be up to fifty place holders in the <format> argument, and there
should be the same number of place holders as <param> arguments. Only the %s string format is
supported.
param1, param2

The input strings that are used in the result string. You can specify up to 50 of these CHAR(254)
arguments.

Remarks

The result placed in the output parameter is truncated to 254 characters.

Privileges

You must have EXECUTE privilege on the system procedure.

SAP IQ SQL Reference


System Procedures INTERNAL 969
 Example

The following statements put the string Hello World! into the result variable.

CREATE VARIABLE result CHAR( 254 );


CALL dbo.xp_sprintf( result, '%s %s', 'Hello', 'World!' );
SELECT result;

The following statements format the year, month, and day into a date string.

CREATE VARIABLE result CHAR( 254 );


CALL dbo.xp_sprintf( result, '%s/%s/%s', 2014, 11, 23 );
SELECT result;

7.6.77 xp_startmail system procedure

Starts an email session under MAPI.

 Syntax

xp_startmail(
[ mail_user = <mail-login-name>
[, mail_password = <mail-password> ] ]
)

Parameters

mail_user

Use this LONG VARCHAR parameter to specify the MAPI login name. The default is NULL.
mail_password

Use this LONG VARCHAR parameter to specify the MAPI password. The default is NULL.

Returns

This function returns an INTEGER status code.

Remarks

xp_startmail is a system procedure owned by dbo that starts an email session.

SAP IQ SQL Reference


970 INTERNAL System Procedures
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.

Not supported on Unix.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

7.6.78 xp_startsmtp system procedure

Starts an email session under SMTP.

 Syntax

xp_startsmtp(
smtp_sender = <email-address>
, smtp_server = <smtp-server>
[, smtp_port = <port-number> ]
[, timeout = <timeout> ]
[, smtp_sender_name = <username> ]
[, smtp_auth_username = <auth-username> ]
[, smtp_auth_password = <auth-password> ]
[, trusted_certificates = { <public-certificate> | * }
[, secure = { 1 | 0 } ]
[, certificate_company = <organization> ]
[, certificate_unit = <organization-unit> ]
[, certificate_name = <common-name> ]
[, skip_certificate_name_check= { 1 | 0 } ]
)

Parameters

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 comprised of the SMTP 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.

SAP IQ SQL Reference


System Procedures INTERNAL 971
smtp_sender_name

This optional LONG VARCHAR parameter specifies an alias for the sender's email address. For example,
JSmith instead of <email-address>. The default is NULL.
smtp_auth_username

This optional LONG VARCHAR parameter specifies the user name to provide to SMTP servers requiring
authentication. The default is NULL.
smtp_auth_password

This optional LONG VARCHAR parameter specifies the password to provide to SMTP servers requiring
authentication. The default is NULL.
trusted_certificates

This optional LONG VARCHAR parameter is a list of keyword=value pairs separated by semicolons. The
default is NULL. When this parameter is NULL, a standard SMTP connection is made. The possible keys are
listed below. Only one of the file, certificate, and cert_name options should be specified.

This parameter takes the filename given by FILE=key and contains a list of PEM-encoded X.509 trusted
root certificates.

The trusted certificate can be a server's self-signed certificate, a public root certificate, or a certificate
belonging to a commercial Certificate Authority. Generate your certificates using RSA.

To use a certificate from the operating system's certificate store, specify file=*.

To make secure SMTP (SMTPS) connections, which use TLS authentication and encryption, specify
SMTPS=YES.

A single file name can also be specified (trusted_certificates=<file-spec>).

To accept root certificates and database server certificates that are either expired or are not yet valid,
specify allow_expired_certs=yes .

The secure and trusted_certificates options can be used together to indicate how to connect to the server.
The following table describes the different possibilities.

Key Value

file= The path and file name of a file that contains one or more
trusted certificates.

cert_name= The name of a certificate stored in the database.

certificate= The certificate data.

SMTPS= YES | NO

allow_expired_certs= YES | NO

secure

This optional parameter specifies whether the connection is secure and whether to use a specified trusted
certificate or a certificate from the operating system's certificate store. The default is NULL.

SAP IQ SQL Reference


972 INTERNAL System Procedures
secure=NULL secure=0 secure=1

trusted_certificate=NULL Not secure Not secure Secure. Uses operating sys­


tem certificate store.

trusted_certificate='*' Secure. Uses operating sys­ Returns an error. Secure. Uses operating sys­
tem certificate store. tem certificate store.

trusted_certifi- Secure. Uses specified cer­ Returns an error. Secure. Uses specified cer­
cate=<filename> tificate. tificate.

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. The default 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.
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. The default is NULL.
skip_certificate_name_check

This optional BIT parameter controls whether the SMTP server's host is checked against the SMTP server
certificate. Specifying 1 enables this option. The default is 0. This parameter is ignored when the
trusted_certificates value is NULL, or when any of the following parameters are specified:
certificate_company, certificate_unit, or certificate_name.

 Note

Setting this parameter to 1 is not recommended because this setting prevents the database server
from fully authenticating the SMTP server.

Returns

This function returns an INTEGER status code (SMTP/MAPI return code).

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. You should call xp_startsmtp just before executing xp_sendmail.

The database server supports CRAM-MD5 authentication, as well as PLAIN authentication. When you use the
xp_startsmtp system procedure with the smtp_auth_username and smtp_auth_password parameters, the
database server uses CRAM-MD5 authentication. If the SMTP server does not support CRAM-MD5

SAP IQ SQL Reference


System Procedures INTERNAL 973
authentication, then the database server uses PLAIN authentication. If the SMTP server does not support the
SMTP authentication capability, error code 104 (Server error; response not understood) is returned. Also, if the
database server is started using the -fips database server option, then only PLAIN authentication is used.

CRAM-MD5 authentication is more secure than PLAIN authentication, but neither encrypts what is sent to the
SMTP server. To encrypt what is sent to the SMTP server, including email messages, use secure SMTP. Secure
SMTP uses TLS encryption to encrypt and can be used with CRAM-MD5 or PLAIN authentication.

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 dbeng16.exe and start_iq.exe. For example, with McAfee VirusScan you can allow mass
mailing for these two processes by adding them to the list of Excluded Processes in the Properties area.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

7.6.79 xp_stopmail system procedure

Closes a MAPI email session.

 Syntax

xp_stopmail( )

Returns

This function returns an INTEGER status code.

Remarks

xp_stopmail is a system procedure that ends an email session.

Not supported on Unix.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

SAP IQ SQL Reference


974 INTERNAL System Procedures
 Example

The following statement ends the email session.

CALL dbo.xp_stopmail( );

7.6.80 xp_stopsmtp system procedure

Closes an SMTP email session.

 Syntax

xp_stopsmtp( )

Returns

This function returns an INTEGER status code.

Remarks

xp_stopsmtp is a system procedure that ends an email session.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the SEND EMAIL system privilege.

 Example

The following statement ends the email session.

CALL dbo.xp_stopsmtp( );

SAP IQ SQL Reference


System Procedures INTERNAL 975
7.6.81 xp_write_file system procedure

Writes data to a file from a SQL statement.

 Syntax

xp_write_file(
<filename>
, <file_contents>
)

Parameters

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.

Returns

This function returns an INTEGER status code.

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.

If disk sandboxing is enabled, the file referenced in <filename> must in an accessible location.

Privileges

You must have EXECUTE privilege on the system procedure, as well as the WRITE FILE system privilege.

SAP IQ SQL Reference


976 INTERNAL System Procedures
 Example

This example uses xp_write_file to create a file accountnum.txt containing the data 123456:

CALL dbo.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 dbo.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 dbo.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 column stores image data (JPEGs).

7.7 SAP ASE System and Catalog Procedures


SAP Adaptive Server Enterprise provides system and catalog procedures to carry out many administrative
functions and to obtain system information. SAP IQ supports some of these procedures.

System procedures are built-in stored procedures used for getting reports from and updating system tables.
Catalog stored procedures retrieve information from the system tables in tabular form.

 Note

While these procedures perform the same functions as they do in SAP ASE, they are not identical. If you
have preexisting scripts that use these procedures, you might want to examine the procedures. To see the
text of a stored procedure, run:

sp_helptext '<owner.procedure_name>'

For all system stored procedures delivered by SAP, the owner is dbo. To see the text of a stored procedure
of the same name owned by a different user, you must specify that user, for example:

sp_helptext 'myname.myprocedure'

In this section:

SAP ASE System Procedures [page 978]

SAP IQ SQL Reference


System Procedures INTERNAL 977
SAP Adaptive Server Enterprise system procedures provided in SAP IQ:

SAP ASE Catalog Procedures [page 979]


SAP IQ implements most of the SAP Adaptive Server Enterprise catalog procedures with the exception
of the sp_column_privileges procedure.

7.7.1 SAP ASE System Procedures

SAP Adaptive Server Enterprise system procedures provided in SAP IQ:

System Procedure Description Permissions

sp_addlogin <userid>, Adds a new user account to a database. Requires the MANAGE ANY USER sys­
<password>[, <defdb>[, tem privilege.
<deflanguage>[,
<fullname>]]]

sp_addmessage <message- Adds user-defined messages to Requires the CREATE MESSAGE or


num>, <message_text>[, SYSUSERMESSAGES for use by stored CREATE ANY OBJECT system privilege.
<language>] procedure PRINT and RAISERROR
calls.

sp_addtype <typename>, Creates a user-defined data type. SAP Requires the CREATE DATATYPE or
<data-type>, ["<identity>" IQ does not support IDENTITY columns. CREATE ANY OBJECT system privilege.
| <nulltype>]

sp_adduser <userid>[, Adds a new user to a database. Requires MANAGE ANY USER system
<name_in_db>[, <grpname>]] privilege to create a new user. Requires
MANAGE ANY USER and MANAGE
ROLES system privileges to create a
new user and add the user to the role
specified.

sp_dboption [<dbname>, Displays or changes database options. None required.


<optname>, {true | false}]

sp_droplogin <userid> Drops a user from a database. Requires MANAGE ANY LOGIN POLICY
system privilege.

sp_dropmessage <message- Drops user-defined messages. Requires the DROP MESSAGE system
number>[, <language>] privilege.

sp_droptype <typename> Drops a user-defined data type. Requires the DROP DATATYPE system
privilege.

sp_dropuser <userid> Drops a user from a database. Requires the MANAGE ANY USER sys­
tem privilege.

sp_getmessage <message- Retrieves stored message strings from None required.


num>, <@msg-var> output[, SYSUSERMESSAGES for PRINT and
<language>] RAISERROR statements.

sp_helptext Displays the text of a system procedure None required.


'<owner>.<object-name>' or view.

SAP IQ SQL Reference


978 INTERNAL System Procedures
System Procedure Description Permissions

sp_password Adds or changes a password for a user No system privilege is required to


<caller_passwd>, ID. change your own password. The
<new_passwd>[, <userid>] CHANGE PASSWORD system privilege
is required to change the password of
another user.

 Note

Procedures like sp_dropuser provide minimal compatibility with SAP ASE stored procedures. If you are
accustomed to SAP ASE, compare their text with SAP IQ procedures before using the procedure in
Interactive SQL. To compare, use the command:

sp_helptext '<owner.procedure_name>'

For system stored procedures delivered by SAP IQ, the owner is always dbo. To see the text of a stored
procedure of the same name owned by a different user, you must specify that user, for example:

sp_helptext 'myname.myprocedure'

Related Information

Users, Groups/Roles, and Permissions [page 169]

7.7.2 SAP ASE Catalog Procedures

SAP IQ implements most of the SAP Adaptive Server Enterprise catalog procedures with the exception of the
sp_column_privileges procedure.

SAP IQ also has similar customized stored procedures for some of these SAP ASE catalog procedures.

SAP IQ Proce­
SAP ASE Catalog Procedure Description dure

sp_columns <table-name>[, <table-owner>][, Returns the data types of the specified


<table-qualifier>][, <column-name>] column.

sp_fkeys <pktable_name>[, <pktable-owner>] Returns foreign-key information about


[, <pktable-qualifier>][, <fktable-name>] the specified table.
[, <fktable_owner>] [, <fktable-
qualifier>]

sp_pkeys <table-name>[, <table-owner>][, Returns primary-key information for a sp_iqpkeys


<table-qualifier>] single table.

sp_special_columns <table-name>[, <table- Returns the optimal set of columns


owner>][, <table-qualifier>][, <col-type>] that uniquely identify a row in a table.

SAP IQ SQL Reference


System Procedures INTERNAL 979
SAP IQ Proce­
SAP ASE Catalog Procedure Description dure

sp_sproc_columns <proc-name>[, Returns information about the input sp_iqprocpar


<proc_owner>][, <proc-qualifier>][, and return parameters of a stored pro­ m
<column-name>] cedure.

sp_stored_procedures [<sp-name>][, <sp- Returns information about one or sp_iqprocedu


owner>][, <sp-qualifier>] more stored procedures. re

sp_tables <table-name>[, <table-owner>][, Returns a list of objects that can ap­


<table-qualifier>][, <table-type>] pear in a FROM clause.

The following SAP ASE catalog procedures are not supported:

● sp_column_privileges
● sp_databases
● sp_datatype_info
● sp_server_info

SAP IQ SQL Reference


980 INTERNAL System Procedures
8 System Tables and Views

SAP IQ supports system tables, system views, consolidated views, compatibility views, and SAP Adaptive
Server Enterprise T-SQL compatibility views.

In this section:

System Tables [page 982]


The structure of every SAP IQ database is described in a number of system tables. The system tables
are designed for internal use.

System Views [page 987]


SAP IQ supports system views, consolidated views, compatibility views, and SAP Adaptive Server
Enterprise Transact-SQL compatibility views to view the contents of system tables.

SAP IQ SQL Reference


System Tables and Views INTERNAL 981
8.1 System Tables

The structure of every SAP IQ database is described in a number of system tables. The system tables are
designed for internal use.

The DUMMY system table is the only system table you are permitted to access directly. For all other system
tables, listed below, you access their underlying data through their corresponding views:

● ISYSARTICLE ● ISYSIQLOGINPOLICYLSINFO ● ISYSPUBLICATION


● ISYSARTICLECOL ● ISYSIQLSLOGINPOLICYOPTION ● ISYSREMARK
● ISYSATTRIBUTE ● ISYSIQLSMEMBER ● ISYSREMOTEOPTION
● ISYSATTRIBUTENAME ● ISYSIQLSPOLICY ● ISYSREMOTEOPTIONTYPE
● ISYSCAPABILITY ● ISYSIQLSPOLICYOPTION ● ISYSREMOTETYPE
● ISYSCHECK ● ISYSIQMPXSERVER ● ISYSREMOTEUSER
● ISYSCOLPERM ● ISYSIQMPXSERVERAGENT ● ISYSSCHEDULE
● ISYSCOLSTAT ● ISYSIQPARTITIONCOLUMN ● ISYSSERVER
● ISYSCONSTRAINT ● ISYSIQTAB ● ISYSSOURCE
● ISYSDBFILE ● ISYSIQTABCOL ● ISYSSQLSERVERTYPE
● ISYSDBSPACE ● ISYSJAR ● ISYSSUBPARTITIONKEY
● ISYSDBSPACEPERM ● ISYSJARCOMPONENT ● ISYSSUBSCRIPTION
● ISYSDEPENDENCY ● ISYSJAVACLASS ● ISYSSYNC
● ISYSDOMAIN ● ISYSLOGINMAP ● ISYSSYNCPROFILE
● ISYSEVENT ● ISYSLOGINPOLICY ● ISYSSYNCSCRIPT
● ISYSEXTERNENV ● ISYSLOGINPOLICYOPTION ● ISYSTAB
● ISYSEXTERNENVOBJECT ● ISYSMVOPTION ● ISYSTABCOL
● ISYSEXTERNLOGIN ● ISYSMVOPTIONNAME ● ISYSTABLEPERM
● ISYSFKEY ● ISYSOBJECT ● ISYSTEXTCONFIG
● ISYSGROUP ● ISYSOPTION ● ISYSTEXTIDX
● ISYSHISTORY ● ISYSOPTSTAT ● ISYSTEXTIDXTAB
● ISYSIDX ● ISYSPARTITION ● ISYSTRIGGER
● ISYSIDXCOL ● ISYSPARTITIONKEY ● ISYSTYPEMAP
● ISYSIQBACKUPHISTORY ● ISYSPARTITIONSCHEME ● ISYSUSER
● ISYSIQBACKUPHISTORYDETAIL ● ISYSPHYSIDX ● ISYSUSERAUTHORITY
● ISYSIQDBFILE ● ISYSPROCEDURE ● ISYSUSERMESSAGE
● ISYSIQDBSPACE ● ISYSPROCPARM ● ISYSUSERTYPE
● ISYSIQIDX ● ISYSPROCPERM ● ISYSVIEW
● ISYSIQINFO ● ISYSPROXYTAB ● ISYSWEBSERVICE
● ISYSIQLOGICALSERVER ● ISYSPUBLICATION

In this section:

SYS.DUMMY Table Versus IQ_DUMMY Table [page 983]


The DUMMY system table is provided as a table that always has exactly one row.

ISYSIQINFO System Table [page 984]


This table indicates the database characteristics as defined when the SAP IQ database was created
using CREATE DATABASE. It always contains only one row.

ISYSIQLOGICALSERVER System Table [page 986]

SAP IQ SQL Reference


982 INTERNAL System Tables and Views
ISYSIQLOGICALSERVER stores logical server and the correspondence between logical server and
associated logical server policy information.

ISYSIQLOGINPOLICYLSINFO System Table [page 986]


ISYSIQLOGINPOLICYLSINFO stores the login policy logical server assignment information.

ISYSIQLSLOGINPOLICYOPTION System Table [page 986]


ISYSIQLSLOGINPOLICYOPTION stores the login policy option values that have logical server level
settings.

ISYSIQLSMEMBER System Table [page 986]


ISYSIQLSMEMBER stores the logical server membership information.

ISYSIQLSPOLICY System Table [page 986]


ISYSIQLSPOLICY stores logical server policies.

ISYSIQLSPOLICYOPTION System Table [page 987]


ISYSIQLSPOLICYOPTION stores the logical server policy options.

ISYSIQMPXSERVER System Table [page 987]


ISYSIQMPXSERVER stores membership properties and version status data for a given multiplex node.

ISYSIQMPXSERVERAGENT System Table [page 987]


ISYSIQMPXSERVERAGENT stores agent login information for each multiplex node.

8.1.1 SYS.DUMMY Table Versus IQ_DUMMY Table

The DUMMY system table is provided as a 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

Queries using the DUMMY table are run by SAP SQL Anywhere (the catalog store), rather than by SAP IQ. You
can create a dummy table in the SAP IQ database, such as the following example:

CREATE TABLE iq_dummy (dummy_col INT NOT NULL);


INSERT INTO iq_dummy values (1);

The example statement allows you to use the following table explicitly:

SELECT NOW() FROM iq_dummy;

In this section:

DUMMY system table [page 984]


The DUMMY table is provided as a read-only table that always has exactly one row.

SAP IQ SQL Reference


System Tables and Views INTERNAL 983
8.1.1.1 DUMMY system table

The DUMMY table is provided as a read-only table that always has exactly one row.

Column name Column type Column constraint Table constraints

dummy_col INTEGER NOT NULL

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 DUMMY table is less than the cost of reading from a similar user-created table
because there is no lock placed on the table page of DUMMY.

Access plans are not constructed with scans of the DUMMY table. Instead, references to DUMMY are
replaced with a Row Constructor algorithm, which virtualizes the table reference. This eliminates
contention associated with the use of DUMMY. DUMMY still appears as the table and/or correlation name
in short, long, and graphical plans.

8.1.2 ISYSIQINFO System Table

This table indicates the database characteristics as defined when the SAP IQ database was created using
CREATE DATABASE. It always contains only one row.

Column Name Column Type Description

last_full_backup TIMESTAMP The completion time of the most recent


backup.

last_incr_backup TIMESTAMP The completion time of the most recent in­


cremental backup.

create_time TIMESTAMP NOT NULL The date and time when the database was
created.

update_time TIMESTAMP NOT NULL The date and time of the last update.

file_format_version UNSIGNED INT NOT NULL The file format number of files for this da­
tabase.

cat_format_version UNSIGNED INT NOT NULL The catalog format number for this data­
base.

sp_format_version UNSIGNED INT NOT NULL The stored procedure format number for
this database.

block_size UNSIGNED INT NOT NULL The block size specified for the database.

SAP IQ SQL Reference


984 INTERNAL System Tables and Views
Column Name Column Type Description

chunk_size UNSIGNED INT NOT NULL The number of blocks per chunk as deter­
mined by the block size and page size
specified for the database.

file_format_date CHAR(10) NOT NULL The date when file format number was last
changed.

dbsig BINARY(136) NOT NULL Used internally by catalog.

multiplex_name CHAR(128) NULL Used internally by catalog.

last_multiplex_mode TINYINT NULL The mode of the server that last opened
the catalog read-write. One of the following
values.

● 0 – Single Node.
● 1 – Reader.
● 2 – Coordinator.
● 3 – Writer.

Constraint: Primary key( create_time )

SAP IQ SQL Reference


System Tables and Views INTERNAL 985
8.1.3 ISYSIQLOGICALSERVER System Table

ISYSIQLOGICALSERVER stores logical server and the correspondence between logical server and associated
logical server policy information.

8.1.4 ISYSIQLOGINPOLICYLSINFO System Table

ISYSIQLOGINPOLICYLSINFO stores the login policy logical server assignment information.

8.1.5 ISYSIQLSLOGINPOLICYOPTION System Table

ISYSIQLSLOGINPOLICYOPTION stores the login policy option values that have logical server level settings.

8.1.6 ISYSIQLSMEMBER System Table

ISYSIQLSMEMBER stores the logical server membership information.

8.1.7 ISYSIQLSPOLICY System Table

ISYSIQLSPOLICY stores logical server policies.

SAP IQ SQL Reference


986 INTERNAL System Tables and Views
8.1.8 ISYSIQLSPOLICYOPTION System Table
ISYSIQLSPOLICYOPTION stores the logical server policy options.

8.1.9 ISYSIQMPXSERVER System Table


ISYSIQMPXSERVER stores membership properties and version status data for a given multiplex node.

8.1.10 ISYSIQMPXSERVERAGENT System Table


ISYSIQMPXSERVERAGENT stores agent login information for each multiplex node.

8.2 System Views


SAP IQ supports system views, consolidated views, compatibility views, and SAP Adaptive Server Enterprise
Transact-SQL compatibility views to view the contents of system tables.

A number of predefined system views are provided that present the information in the system tables in a
readable format.

The definitions for the system views are included with their descriptions. Some of these definitions are
complicated, but you do not need to understand them to use the views.

In this section:

Consolidated Views [page 987]


Consolidated views provide data in a form more frequently required by users.

Compatibility Views [page 988]


Compatibility views are deprecated views provided for compatibility with earlier versions of SAP SQL
Anywhere and SAP IQ.

Alphabetical List of System Views [page 988]


System tables are hidden; however, there is a system view for each table. To ensure compatibility with
future versions of the IQ main store, make sure your applications use system views and not the
underlying system tables, which may change.

8.2.1 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 straightforward view of raw data in an underlying system table. For example,

SAP IQ SQL Reference


System Tables and Views INTERNAL 987
many of the columns in the system views are unintelligible ID values, whereas in the consolidated views, they
are readable names.

8.2.2 Compatibility Views

Compatibility views are deprecated views provided for compatibility with earlier versions of SAP SQL Anywhere
and SAP IQ.

Where possible, use system views and consolidated views instead of compatibility views, as support for
compatibility views may be eliminated in future versions of SAP IQ.

In this section:

SAP ASE T-SQL Compatibility Views [page 988]


SAP IQ provides a set of views owned by the special user DBO, which correspond to the SAP Adaptive
Server Enterprise system tables and views.

8.2.2.1 SAP ASE T-SQL Compatibility Views

SAP IQ provides a set of views owned by the special user DBO, which correspond to the SAP Adaptive Server
Enterprise system tables and views.

Related Information

Transact-SQL Compatibility Views [page 1113]

8.2.3 Alphabetical List of System Views

System tables are hidden; however, there is a system view for each table. To ensure compatibility with future
versions of the IQ main store, make sure your applications use system views and not the underlying system
tables, which may change.

In this section:

GTSYSPERFCACHEPLAN system view [page 1000]


Each row in the GTSYSPERFCACHEPLAN system view contains a graphical plan string for an execution
plan of the specified statement.

GTSYSPERFCACHESTMT system view [page 1001]


Each row in the GTSYSPERFCACHESTMT system view represents SQL text for a statement with the
constants removed.

ST_GEOMETRY_COLUMNS Consolidated View [page 1001]

SAP IQ SQL Reference


988 INTERNAL System Tables and Views
Each row of the ST_GEOMETRY_COLUMNS system view describes a spatial column defined in the
database.

ST_SPATIAL_REFERENCE_SYSTEMS Consolidated View [page 1002]


Each row of the ST_SPATIAL_REFERENCE_SYSTEMS system view describes an SRS defined in the
database. This view offers a slightly different amount of information than the
SYSSPATIALREFERENCESYSTEM system view.

ST_UNITS_OF_MEASURE Consolidated View [page 1004]


Each row of the ST_UNITS_OF_MEASURE system view describes a unit of measure defined in the
database. This view offers more information than the SYSUNITOFMEASURE system view.

SYSARTICLE system view [page 1005]


Each row of the SYSARTICLE system view describes an article in a publication. The underlying system
table for this view is ISYSARTICLE.

SYSARTICLECOL system view [page 1005]


Each row of the SYSARTICLECOL system view identifies a column in an article. The underlying system
table for this view is ISYSARTICLECOL.

SYSARTICLECOLS consolidated view [page 1006]


Each row in the SYSARTICLECOLS view identifies a column in an article.

SYSARTICLES consolidated view [page 1006]


Each row in the SYSARTICLES view describes an article in a publication.

SYSCAPABILITIES consolidated view [page 1006]


Each row in the SYSCAPABILITIES view specifies the status of a capability for a remote database
server. This view gets its data from the ISYSCAPABILITY system table.

SYSCAPABILITY system view [page 1007]


Each row of the SYSCAPABILITY system view specifies the status of a capability on a remote database
server. The underlying system table for this view is ISYSCAPABILITY.

SYSCAPABILITYNAME system view [page 1007]


Each row in the SYSCAPABILITYNAME system view provides a name for each capability ID in the
SYSCAPABILITY system view.

SYSCATALOG consolidated view [page 1007]


Each row in the SYSCATALOG view describes a system table.

SYSCERTIFICATE System View [page 1008]


Each row of the SYSCERTIFICATE system view stores a certificate in text PEM-format. The underlying
system table for this view is ISYSCERTIFICATE.

SYSCOLLATION compatibility view (deprecated) [page 1008]


The SYSCOLLATION compatibility view contains the collation sequence information for the database. It
is obtainable via built-in functions and is not kept in the catalog. Following is definition for this view:

SYSCOLLATIONMAPPINGS compatibility view (deprecated) [page 1009]


The SYSCOLLATIONMAPPINGS compatibility view contains only one row with the database collation
mapping. It is obtainable via built-in functions and is not kept in the catalog. Following is definition for
this view:

SYSCOLPERM system view [page 1009]


The GRANT statement can give UPDATE, SELECT, or REFERENCES privileges to individual columns in a
table. Each column with UPDATE, SELECT, or REFERENCES privileges is recorded in one row of the
SYSCOLPERM system view. The underlying system table for this view is ISYSCOLPERM.

SAP IQ SQL Reference


System Tables and Views INTERNAL 989
SYSCOLSTAT system view [page 1010]
The SYSCOLSTAT system view contains the column statistics, including histograms, that are used by
the optimizer. The contents of this view are best retrieved using the sa_get_histogram stored procedure
or the Histogram utility. The underlying system table for this view is ISYSCOLSTAT.

SYSCOLSTATS consolidated view [page 1010]


The SYSCOLSTATS view contains the column statistics that are stored as histograms and used by the
optimizer.

SYSCOLUMN compatibility view (deprecated) [page 1011]


The SYSCOLUMN view is provided for compatibility with older versions of the software that offered a
SYSCOLUMN system table.

SYSCOLUMNS consolidated view [page 1011]


Each row in the SYSCOLUMNS view describes one column of each table and view in the catalog.

SYSCOLUMNS ASE Compatibility View [page 1012]


This view is owned by user DBO. syscolumns contains one row for every column in every table and view,
and a row for each parameter in a procedure.

SYSCOMMENTS ASE Compatibility View [page 1012]


syscomments contains entries for each view, rule, default, trigger, table constraint, partition,
procedure, computed column, function-based index key, and other forms of compiled objects.

SYSCONSTRAINT system view [page 1013]


Each row in the SYSCONSTRAINT system view describes a named constraint in the database. The
underlying system table for this view is ISYSCONSTRAINT.

SYSDATABASEVARIABLE system view [page 1013]


Each row in the SYSDATABASEVARIABLE system view describes one database-scope variable in the
database. The underlying system table for this view is ISYSDATABASEVARIABLE.

SYSDBFILE system view [page 1015]


Each row in the SYSDBFILE system view describes a dbspace file. The underlying system table for this
view is ISYSDBFILE.

SYSDBSPACE system view [page 1015]


Each row in the SYSDBSPACE system view describes a dbspace file. The underlying system table for
this view is ISYSDBSPACE.

SYSDBSPACEPERM system view [page 1016]


Each row in the SYSDBSPACEPERM system view describes a privilege on a dbspace file. The underlying
system table for this view is ISYSDBSPACEPERM.

SYSDEPENDENCY system view [page 1016]


Each row in the SYSDEPENDENCY system view describes a dependency between two database
objects. The underlying system table for this view is ISYSDEPENDENCY.

SYSDOMAIN system view [page 1016]


The SYSDOMAIN system view records information about built-in data types (also called domains). The
contents of this view does not change during normal operation. The underlying system table for this
view is ISYSDOMAIN.

SYSEVENT system view [page 1017]


Each row in the SYSEVENT system view describes an event created with CREATE EVENT. The
underlying system table for this view is ISYSEVENT.

SYSEVENTTYPE system view [page 1018]

SAP IQ SQL Reference


990 INTERNAL System Tables and Views
The SYSEVENTTYPE system view defines the system event types that can be referenced by CREATE
EVENT.

SYSEXTERNENV system view [page 1019]


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.

SYSEXTERNENVOBJECT system view [page 1021]


Each row in the SYSEXTERNENVOBJECT system view describes an installed external object. The
underlying system table for this view is ISYSEXTERNENVOBJECT.

SYSEXTERNLOGIN system view [page 1022]


Each row in the SYSEXTERNLOGIN system view describes an external login for remote data access.
The underlying system table for this view is ISYSEXTERNLOGIN.

SYSFILE compatibility view (deprecated) [page 1022]


Each row in the SYSFILE system view describes a dbspace for a database. Every database consists of
one or more dbspaces; each dbspace corresponds to an operating system file.

SYSFKCOL compatibility view (deprecated) [page 1023]


Each row of SYSFKCOL describes the association between a foreign column in the foreign table of a
relationship and the primary column in the primary table. This view is deprecated; use the SYSIDX and
SYSIDXCOL system views instead.

SYSFKEY system view [page 1023]


Each row in the SYSFKEY system view describes a foreign key constraint in the system. The underlying
system table for this view is ISYSFKEY.

SYSFOREIGNKEY compatibility view (deprecated) [page 1024]


The SYSFOREIGNKEY view is provided for compatibility with older versions of the software that offered
a SYSFOREIGNKEY system table. However, the previous SYSFOREIGNKEY system table has been
replaced by the ISYSFKEY system table, and its corresponding SYSFKEY system view, which you should
use instead.

SYSFOREIGNKEYS consolidated view [page 1025]


Each row in the SYSFOREIGNKEYS view describes one foreign key for each table in the catalog.

SYSGROUP compatibility view [page 1026]


There is one row in the SYSGROUP system view for each member of each group. This view describes
the many-to-many relationship between groups and members. A group may have many members, and
a user may be a member of many groups.

SYSGROUPS compatibility view [page 1026]


There is one row in the SYSGROUPS view for each member of each group. This view describes the
many-to-many relationship between groups and members. A group may have many members, and a
user may be a member of many groups.

SYSHISTORY system view [page 1027]


Each row in the SYSHISTORY system view records a system operation on the database, such as a
database start, a database calibration, and so on. The underlying system table for this view is
ISYSHISTORY.

SYSIDX system view [page 1029]


Each row in the SYSIDX system view defines a logical index in the database. The underlying system
table for this view is ISYSIDX.

SYSIDXCOL system view [page 1030]

SAP IQ SQL Reference


System Tables and Views INTERNAL 991
Each row in the SYSIDXCOL system view describes one column of an index described in the SYSIDX
system view. The underlying system table for this view is ISYSIDXCOL.

SYSINDEX compatibility view (deprecated) [page 1031]


The SYSINDEX view is provided for compatibility with older versions of the software that offered a
SYSINDEX system table. However, the SYSINDEX system table has been replaced by the ISYSIDX
system table, and its corresponding SYSIDX system view, which you should use instead.

SYSINDEXES consolidated view [page 1032]


Each row in the SYSINDEXES view describes one index in the database. As an alternative to this view,
you could also use the SYSIDX and SYSIDXCOL system views.

SYSINDEXES ASE Compatibility View [page 1032]


sysindexes contains one row for each clustered index, one row for each nonclustered index, one row for
each table that has no clustered index, and one row for each table that contains text or image columns.

SYSINFO compatibility view (deprecated) [page 1033]


The SYSINFO view indicates the database characteristics, as defined when the database was created. It
always contains only one row. This view is obtainable via built-in functions and is not kept in the
catalog. Following is the definition for the SYSINFO view:

SYSIQBACKUPHISTORY System View [page 1033]


This view presents group information from ISYSIQBACKUPHISTORY in a readable format. Each row in
this view describes a particular backup operation that finished successfully.

SYSIQBACKUPHISTORYDETAIL System View [page 1034]


This view describes all the dbfile records present in the database at backup time. Each row in this view
describes a particular backup operation that finished successfully.

SYSIQCOLUMN System View (Deprecated) [page 1036]


SYSIQCOLUMN has been replaced by the SYSIQTABCOL system view.

SYSIQDBFILE System View [page 1036]


Presents group information from ISYSIQDBFILE in a readable format.

SYSIQDBSPACE System View [page 1037]


Presents group information from ISYSIQDBSPACE in a readable format.

SYSIQFILE System View (Deprecated) [page 1038]


SYSIQFILE has been replaced by the SYSIQDBFILE system view.

SYSIQIDX System View [page 1038]


Presents group information from ISYSIQIDX in a readable format. Each row in the SYSIQIDX view
describes an IQ index.

SYSIQINFO System View [page 1039]


Presents group information from ISYSIQINFO in a readable format.

SYSIQLOGICALSERVER System View [page 1040]


Presents a readable version of the ISYSIQLOGICALSERVER system table.

SYSIQLOGINPOLICYLSINFO System View [page 1041]


Presents a readable version of the table ISYSIQLOGINPOLICYLSINFO.

SYSIQLSLOGINPOLICIES Consolidated View [page 1041]


Describes all the logical server assignments from the login policies.

SYSIQLSLOGINPOLICYOPTION System View [page 1042]


Presents a version of the table ISYSIQLSLOGINPOLICYOPTION in a readable format.

SAP IQ SQL Reference


992 INTERNAL System Tables and Views
SYSIQLSMEMBER System View [page 1042]
Presents group information from the ISYSIQLSMEMBER table, which stores logical server membership
information.

SYSIQLSMEMBERS Consolidated View [page 1043]


Describes all user-defined logical server memberships.

SYSIQLSPOLICY System View [page 1043]


Presents a version of the table ISYSIQLSPOLICY in a readable format.

SYSIQLSPOLICYOPTION System View [page 1044]


Presents a version of the table ISYSIQLSPOLICYOPTION in a readable format.

SYSIQMPXSERVER System View [page 1044]


Presents a readable version of the table ISYSIQMPXSERVER. The ISYSIQMPXSERVER system table
stores membership properties and version status data for the given multiplex node.

SYSIQMPXSERVERAGENT System View [page 1045]


Presents a readable version of the table ISYSIQMPXSERVERAGENT, which stores agent connection
definitions for the specified multiplex server.

SYSIQOBJECTS ASE Compatibility View [page 1046]


sysiqobjects presents one row for each system table, user table, view, procedure, trigger, event,
constraint, domain (sysdomain), domain (sysusertype), column, and index. This view is owned by user
DBO.

SYSIQPARTITIONCOLUMN System View [page 1046]


Presents group information from ISYSIQPARTITIONCOLUMN in a readable format.

SYSIQRVLOG System View [page 1047]


Presents group information from ISYSIQRVLOG in a readable format. Each row in the SYSIQRVLOG
view corresponds to a log for a RLV-enabled table . The row with table_id 0 represents the server-wide
commit log.

SYSIQRLVMERGEHISTORY System View [page 1047]


A log entry is added for each row-level versioning (RLV) enabled table each time a merge between the
RLV store and the IQ main store begins. Log entries are updated when the merge is complete.

SYSIQTAB System View [page 1048]


Presents group information from ISYSIQTAB in a readable format. Each row in the SYSIQTAB view
describes an IQ table.

SYSIQTABCOL System View [page 1050]


Presents group information from ISYSIQTABCOL in a readable format. Each row in the SYSIQTABCOL
view describes a column in an IQ table.

SYSIQTABLE System View (Deprecated) [page 1051]


SYSIQTABLE has been replaced by the SYSIQTAB system view.

SYSIQVINDEX ASE Compatibility View [page 1051]


sysiqvindex provides one row for each non-FP IQ index.

SYSIXCOL compatibility view (deprecated) [page 1051]


Each row of the SYSIXCOL describes a column in an index, and is provided for compatibility with older
versions of the software that offered a SYSIXCOL system table.

SYSJAR system view [page 1052]

SAP IQ SQL Reference


System Tables and Views INTERNAL 993
Each row in the SYSJAR system view defines a JAR file stored in the database. The underlying system
table for this view is ISYSJAR.

SYSJARCOMPONENT system view [page 1052]


Each row in the SYSJARCOMPONENT system view defines a JAR file component, which includes class
files, manifest files, and any other JAR resource. The underlying system table for this view is
ISYSJARCOMPONENT.

SYSJAVACLASS system view [page 1053]


Each row in the SYSJAVACLASS system view describes one Java class stored in the database. The
underlying system table for this view is ISYSJAVACLASS.

SYSLDAPSERVER System View [page 1053]


Presents information on the ISYSLDAPSERVER system table in a readable format.

SYSLOGINMAP system view [page 1055]


The SYSLOGINMAP system view contains one row for each user that can connect to the database
using either an integrated login, or Kerberos login. For that reason, access to this view is restricted. The
underlying system table for this view is ISYSLOGINMAP.

SYSLOGINPOLICY system view [page 1055]


The underlying system table for this view is ISYSLOGINPOLICY.

SYSLOGINPOLICYOPTION system view [page 1055]


The underlying system table for this view is ISYSLOGINPOLICYOPTION.

SYSLOGINS ASE Compatibility View [page 1056]


This view is owned by user DBO. SYSLOGINS contains one row for each valid SAP Adaptive Server
Enterprise user account.

SYSMUTEXSEMAPHORE system view [page 1056]


Each row in the SYSMUTEXSEMAPHORE system view provides information about a user-defined
mutex or semaphore in the database. The underlying system table for this view is
ISYSMUTEXSEMAPHORE.

SYSMVOPTION system view [page 1057]


Each row in the SYSMVOPTION system view describes the setting of one option value for a materialized
view or text index at the time of its creation. The name of the option can be found in the
SYSMVOPTIONNAME system view. The underlying system table for this view is ISYSMVOPTION.

SYSMVOPTIONNAME system view [page 1057]


Each row in the SYSMVOPTION system view gives the name option value for a materialized view or text
index at the time of its creation. The value for the option can be found in the SYSMVOPTION system
view. The underlying system table for this view is ISYSMVOPTIONNAME.

SYSOBJECT system view [page 1057]


Each row in the SYSOBJECT system view describes a database object. The underlying system table for
this view is ISYSOBJECT.

SYSOBJECTS ASE Compatibility View [page 1058]


sysobjects contains one row for each table, view, stored procedure, extended stored procedure, log,
rule, default, trigger, check constraint, referential constraint, computed column, function-based index
key, and temporary object, and other forms of compiled objects.

SYSOPTION system view [page 1059]


The SYSOPTION system view contains the options one row for each option setting stored in the
database.

SAP IQ SQL Reference


994 INTERNAL System Tables and Views
SYSOPTIONS consolidated view [page 1059]
Each row in the SYSOPTIONS view describes one option created using the SET command. Each user
can have their own setting for each option. In addition, settings for the PUBLIC user define the default
settings to be used for users that do not have their own setting.

SYSOPTSTAT system view [page 1060]


The SYSOPTSTAT system view stores the cost model calibration information as computed by the
ALTER DATABASE CALIBRATE statement. The contents of this view are for internal use only and are
best accessed via the sa_get_dtt system procedure. The underlying system table for this view is
ISYSOPTSTAT.

SYSPARTITION System View [page 1060]


Presents group information from ISYSPARTITION in a readable format.

SYSPARTITIONKEY System View [page 1061]


Presents group information from ISYSPARTITIONKEY in a readable format.

SYSPARTITIONS System View [page 1062]


Presents group information from the ISYSPARTITIONS system table in a readable format

SYSPARTITIONSCHEME System View [page 1062]


Presents group information from ISYSPARTITIONSCHEME in a readable format.

SYSPHYSIDX system view [page 1063]


Each row in the SYSPHYSIDX system view defines a physical index in the database. The underlying
system table for this view is ISYSPHYSIDX.

SYSPROCAUTH consolidated view [page 1064]


Each row in the SYSPROCAUTH view describes a set of privileges granted on a procedure. As an
alternative, you can also use the SYSPROCPERM system view.

SYSPROCEDURE system view [page 1064]


Each row in the SYSPROCEDURE system view describes one procedure in the database. The underlying
system table for this view is ISYSPROCEDURE.

SYSPROCPARM system view [page 1066]


Each row in the SYSPROCPARM system view describes one parameter, result set column, or return
value of a procedure or function in the database. The underlying system table for this view is
ISYSPROCPARM.

SYSPROCPARMS consolidated view [page 1067]


Each row in the SYSPROCPARMS view describes a parameter to a procedure in the database.

SYSPROCPERM system view [page 1068]


Each row of the SYSPROCPERM system view describes a user who has been granted EXECUTE
privilege on a procedure. The underlying system table for this view is ISYSPROCPERM.

SYSPROCS consolidated view [page 1068]


The SYSPROCS view shows the procedure or function name, the name of its creator and any
comments recorded for the procedure or function.

SYSPROXYTAB system view [page 1068]


Each row of the SYSPROXYTAB system view describes the remote parameters of one proxy table. The
underlying system table for this view is ISYSPROXYTAB.

SYSPUBLICATION system view [page 1069]


Each row in the SYSPUBLICATION system view describes a publication. The underlying system table
for this view is ISYSPUBLICATION.

SAP IQ SQL Reference


System Tables and Views INTERNAL 995
SYSPUBLICATIONS consolidated view [page 1070]
Each row in the SYSPUBLICATIONS view describes a publication.

SYSREMARK system view [page 1070]


Each row in the SYSREMARK system view describes a remark (or comment) for an object. The
underlying system table for this view is ISYSREMARK.

SYSREMOTEOPTION system view [page 1070]


Each row in the SYSREMOTEOPTION system view describes the value of a message link parameter. The
underlying system table for this view is ISYSREMOTEOPTION.

SYSREMOTEOPTION2 consolidated view [page 1071]


Joins together, and presents in a more readable format, the columns from SYSREMOTEOPTION and
SYSREMOTEOPTIONTYPE system views.

SYSREMOTEOPTIONS consolidated view [page 1071]


Each row of the SYSREMOTEOPTIONS view describes the values of a message link parameter.

SYSREMOTEOPTIONTYPE system view [page 1072]


Each row in the SYSREMOTEOPTIONTYPE system view describes one of the message link parameters.
The underlying system table for this view is ISYSREMOTEOPTIONTYPE.

SYSREMOTETYPE system view [page 1072]


The SYSREMOTETYPE system view contains information about remote tables. The underlying system
table for this view is ISYSREMOTETYPE.

SYSREMOTETYPES consolidated view [page 1073]


Each row of the SYSREMOTETYPES view describes one remote message type, including the publisher
address.

SYSREMOTEUSER system view [page 1073]


Each row in the SYSREMOTEUSER system view describes a user ID with the REMOTE system privilege
(a subscriber), together with the status of messages that were sent to and from that user. The
underlying system table for this view is ISYSREMOTEUSER.

SYSREMOTEUSERS consolidated view [page 1074]


Each row of the SYSREMOTEUSERS view describes a user ID with the REMOTE system privilege (a
subscriber), together with the status of messages that were sent to and from that user.

SYSROLEGRANT System View [page 1075]


The SYSROLEGRANT system view contains one row for each grant of a system or user defined role.
The underlying system table for this view is ISYSROLEGRANT.

SYSROLEGRANTEXT System View [page 1076]


The SYSROLEGRANTEXT system view contains syntax extensions pertaining to the SET USER and
CHANGE PASSWORD system privilege and is related to the SYSROLEGRANT system view.

SYSROLEGRANTS System View [page 1076]


The SYSROLEGRANTS system view is the same as the SYSROLEGRANT system view but includes two
additional columns: the name of the role (not just the role ID) and the name of the grantee (not just
user ID).

SYSSCHEDULE system view [page 1078]


Each row in the SYSSCHEDULE system view describes a time at which an event is to fire, as specified
by the SCHEDULE clause of CREATE EVENT. The underlying system table for this view is
ISYSSCHEDULE.

SYSSERVER system view [page 1079]

SAP IQ SQL Reference


996 INTERNAL System Tables and Views
Each row in the SYSSERVER system view describes a remote server. The underlying system table for
this view is ISYSSERVER.

SYSSOURCE system view [page 1079]


Each row in the SYSSOURCE system view contains the source code, if applicable, for an object listed in
the SYSOBJECT system view. The underlying system table for this view is ISYSSOURCE.

SYSSPATIALREFERENCESYSTEM System View [page 1079]


Each row of the SYSSPATIALREFERENCESYSTEM system view describes an SRS defined in the
database. The underlying system table for this view is ISYSSPATIALREFERENCESYSTEM.

SYSSQLSERVERTYPE system view [page 1082]


The SYSSQLSERVERTYPE system view contains information relating to compatibility with Adaptive
Server Enterprise. The underlying system table for this view is ISYSSQLSERVERTYPE.

SYSSUBPARTITIONKEY System View [page 1082]


Presents group information from the ISYSSUBPARTITIONKEY system table in a readable format.

SYSSUBSCRIPTION system view [page 1083]


Each row in the SYSSUBSCRIPTION system view describes a subscription from one user ID (which
must have the REMOTE system privilege) to one publication. The underlying system table for this view
is ISYSSUBSCRIPTION.

SYSSUBSCRIPTIONS consolidated view [page 1083]


Each row describes a subscription from one user ID (which must have the REMOTE system privilege) to
one publication.

SYSSYNC system view [page 1084]


The SYSSYNC system view contains information relating to synchronization.

SYSSYNC2 consolidated view [page 1085]


The SYSSYNC2 view provides public access to the data found in the SYSSYNC system view
(information related to synchronization) without exposing potentially sensitive data.

SYSSYNCPUBLICATIONDEFAULTS consolidated view [page 1086]


The SYSSYNCPUBLICATIONDEFAULTS view provides the default synchronization settings associated
with publications involved in synchronization.

SYSSYNCS consolidated view [page 1086]


The SYSSYNCS view contains information relating to synchronization.

SYSSYNCSCRIPT system view [page 1086]


Each row in the SYSSYNCSCRIPT system view identifies a stored procedure for scripted upload. This
view is almost identical to the SYSSYNCSCRIPTS view, except that the values in this view are in their
raw format.

SYSSYNCSCRIPTS consolidated view [page 1087]


Each row in the SYSSYNCSCRIPTS view identifies a stored procedure for scripted upload. This view is
almost identical to the SYSSYNCSCRIPT system view, except that the values are in human-readable
format, as opposed to raw data.

SYSSYNCSUBSCRIPTIONS consolidated view [page 1087]


The SYSSYNCSUBSCRIPTIONS view contains the synchronization settings associated with
synchronization subscriptions.

SYSSYNCUSERS consolidated view [page 1088]


A view of synchronization settings associated with synchronization users.

SYSTAB system view [page 1088]

SAP IQ SQL Reference


System Tables and Views INTERNAL 997
Each row of the SYSTAB system view describes one table or view in the database. Additional
information for views can be found in the SYSVIEW system view. The underlying system table for this
view is ISYSTAB.

SYSTABAUTH consolidated view [page 1091]


The SYSTABAUTH view contains information from the SYSTABLEPERM system view, but in a more
readable format.

SYSTABCOL system view [page 1092]


The SYSTABCOL system view contains one row for each column of each table and view in the database.
The underlying system table for this view is ISYSTABCOL.

SYSTABLE compatibility view (deprecated) [page 1094]


The SYSTABLE view is provided for compatibility with older versions of the software that offered a
SYSTABLE system table. However, the SYSTABLE system table has been replaced by the ISYSTAB
system table, and its corresponding SYSTAB system view, which you should use instead.

SYSTABLEPERM system view [page 1095]


Privileges granted on tables and views by the GRANT statement are stored in the SYSTABLEPERM
system view. Each row in this view corresponds to one table, one user ID granting the privilege
(grantor) and one user ID granted the privilege (grantee). The underlying system table for this view is
ISYSTABLEPERM.

SYSTEXTCONFIG system view [page 1097]


Each row in the SYSTEXTCONFIG system view describes one text configuration object, for use with the
full text search feature. The underlying system table for this view is ISYSTEXTCONFIG.

SYSTEXTIDX system view [page 1098]


Each row in the SYSTEXTIDX system view describes one text index. The underlying system table for
this view is ISYSTEXTIDX.

SYSTEXTIDXTAB system view [page 1099]


Each row in the SYSTEXTIDXTAB system view describes a generated table that is part of a text index.
The underlying system table for this view is ISYSTEXTIDXTAB.

SYSTRIGGER system view [page 1100]


Each row in the SYSTRIGGER system view describes one trigger in the database. This view also
contains triggers that are automatically created for foreign key definitions which have a referential
triggered action (such as ON DELETE CASCADE). The underlying system table for this view is
ISYSTRIGGER.

SYSTRIGGERS consolidated view [page 1102]


Each row in the SYSTRIGGERS view describes one trigger in the database. This view also contains
triggers that are automatically created for foreign key definitions which have a referential triggered
action (such as ON DELETE CASCADE).

SYSTYPEMAP system view [page 1103]


The SYSTYPEMAP system view contains the compatibility mapping values for entries in the
SYSSQLSERVERTYPE system view. The underlying system table for this view is ISYSTYPEMAP.

SYSTYPES ASE Compatibility View [page 1103]


systypes contains one row for each system-supplied and user-defined datatype. Domains (defined by
rules) and defaults are given, if they exist.

SYSUSER system view [page 1104]


Each row in the SYSUSER system view describes a user in the system.

SAP IQ SQL Reference


998 INTERNAL System Tables and Views
SYSUSERAUTH compatibility view (deprecated) [page 1106]
Each row of the SYSUSERAUTH view describes a user, without exposing their user ID and password
hash. Instead, each user is identified by their user name.

SYSUSERAUTHORITY compatibility view (deprecated) [page 1106]


The SYSUSERAUTHORITY view is provided for compatibility with older versions of the software. Use
the SYSROLEGRANTS consolidated view instead.

SYSUSERLIST compatibility view (deprecated) [page 1107]


The SYSUSERAUTH view is provided for compatibility with older versions of the software.

SYSUSERMESSAGE system view [page 1107]


Each row in the SYSUSERMESSAGE system view holds a user-defined message for an error condition.
The underlying system table for this view is ISYSUSERMESSAGE.

SYSUSEROPTIONS consolidated view [page 1107]


The SYSUSEROPTIONS view contains the option settings that are in effect for each user. If a user has
no setting for an option, this view displays the public setting for the option.

SYSUSERPERM compatibility view (deprecated) [page 1108]


Each row of the SYSUSERPERM view describes one user ID.

SYSUSERPERMS compatibility view (deprecated) [page 1109]


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.

SYSUSERS ASE Compatibility View [page 1109]


sysusers contains one row for each user allowed in the database, and one row for each group or roles.

SYSUSERTYPE system view [page 1110]


Each row in the SYSUSERTYPE system view holds a description of a user-defined data type. The
underlying system table for this view is ISYSUSERTYPE.

SYSVIEW System View [page 1110]


Each row in the SYSVIEW system view describes a view in the database.

SYSVIEWS consolidated view [page 1112]


Each row of the SYSVIEWS view describes one view, including its view definition.

SYSWEBSERVICE system view [page 1112]


Each row in the SYSWEBSERVICE system view holds a description of a web service. The underlying
system table for this view is ISYSWEBSERVICE.

Transact-SQL Compatibility Views [page 1113]


SAP Adaptive Server Enterprise and SAP IQ have different system catalogs, reflecting the different uses
for the two products.

SAP IQ SQL Reference


System Tables and Views INTERNAL 999
8.2.3.1 GTSYSPERFCACHEPLAN system view

Each row in the GTSYSPERFCACHEPLAN system view contains a graphical plan string for an execution plan of
the specified statement.

Column name Data type Description

stmt_hash UNSIGNED BIGINT Unique identifier assigned to each


query.

plan_hash UNSIGNED BIGINT ID assigned to each plan for a given


statement.

plan_text XML NOT NULL XML representation of the query execu­


tion plan.

Remarks

A statement can have multiple execution plans represented in the system view. If statement performance
summary data is not collected, then no statement plans are reported.

Plans are not recorded for statements with short (0.005 seconds or less) execution times.

Privileges

You must have the MONITOR system privilege to access this view.

Related Information

MONITOR System Privilege (Database)

SAP IQ SQL Reference


1000 INTERNAL System Tables and Views
8.2.3.2 GTSYSPERFCACHESTMT system view

Each row in the GTSYSPERFCACHESTMT system view represents SQL text for a statement with the constants
removed.

Column name Data type Description

stmt_hash UNSIGNED BIGINT Unique identifier assigned to each


query.

stmt_text LONG VARCHAR SQL representation of the statement.

Remarks

The statement performance summary feature uses the SQL statement stored in this view.

The SQL for short running statements (0.005 seconds or less) is not recorded.

Privileges

You must have the MONITOR system privilege to access this view.

Related Information

MONITOR System Privilege (Database)

8.2.3.3 ST_GEOMETRY_COLUMNS Consolidated View

Each row of the ST_GEOMETRY_COLUMNS system view describes a spatial column defined in the database.

 Note

Spatial data, spatial references systems, and spatial units of measure can be used only in the catalog store.

Column Name Data Type Description

table_catalog VARCHAR(128) For internal use.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1001
Column Name Data Type Description

table_schema CHAR(128) The name of the schema to which the


table containing the spatial column be­
longs. This is equivalent to the table
owner.

table_name CHAR(128) The name of the table containing the


spatial column.

column_name CHAR(128) The name of the spatial column.

srs_name CHAR(128) The name of the SRS that is associated


with the spatial column. If an SRS is not
associated with the column, then
srs_name is NULL.

srs_id INTEGER The SRID for the SRS associated with


the spatial column.

table_id UNSIGNED INT The numeric identifier for the table con­
taining the column.

column_id UNSIGNED INT The numeric identifier for the column.

geometry_type_name VARCHAR(32767) The spatial data type of the geometries


contained in the column (for example,
ST_Point, ST_Geometry, and so on.)

8.2.3.4 ST_SPATIAL_REFERENCE_SYSTEMS Consolidated


View

Each row of the ST_SPATIAL_REFERENCE_SYSTEMS system view describes an SRS defined in the database.
This view offers a slightly different amount of information than the SYSSPATIALREFERENCESYSTEM system
view.

 Note

Spatial data, spatial references systems, and spatial units of measure can be used only in the catalog store.

Column Name Data Type Description

object_id UNSIGNED BI­ For system use only.


GINT

owner UNSIGNED INT The owner of the SRS.

srs_name CHAR(128) The name of the SRS.

srs_id INTEGER The numeric identifier (SRID) for the spatial reference system.

SAP IQ SQL Reference


1002 INTERNAL System Tables and Views
Column Name Data Type Description

srs_type CHAR(11) he type of SRS as defined by the SQL/MM standard. Values can be one of:

● GEOGRAPHIC – this is for SRSs based on georeferenced coordinate systems with


axes of latitude, longitude (and elevation). These SRSs are of type PLANAR or
ROUND EARTH.
● PROJECTED – this is for SRSs based on georeferenced coordinate systems that do
not have axes of latitude and longitude. These SRSs are of type PLANAR.
● ENGINEERING –this is for SRSs based on non-georeferenced coordinate systems.
These SRSs are of type PLANAR.
● GEOCENTRIC – unsupported.
● COMPOUND – unsupported.
● VERTICAL –unsupported

If srs_type is empty, the type is unspecified.

round_earth CHAR(1) Whether the SRS type is ROUND EARTH (Y) or PLANAR (N).

axis_order CHAR(12) Describes how the database server interprets points with regards to latitude and longi­
tude (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 used when performing calculations.

tolerance DOUBLE Defines the precision to use when comparing points.

semi_ma­ DOUBLE Distance from center of the ellipsoid to the equator for a ROUND EARTH SRS.
jor_axis

semi_mi­ DOUBLE Distance from center of the ellipsoid to the poles for a ROUND EARTH SRS.
nor_axis

inv_flattening DOUBLE The inverse flattening used for the ellipsoid in a ROUND EARTH SRS. This is a ratio cre­
ated by the following equation: 1/f = (semi-major-axis) / (semi-
major-axis - semi-minor-axis)

min_x DOUBLE The minimum x value allowed in coordinates.

max_x DOUBLE The maximum x value allowed in coordinates.

min_y DOUBLE The minimum y value allowed in coordinates.

max_y DOUBLE The maximum y value allowed in coordinates.

min_z DOUBLE The minimum z value allowed in coordinates.

max_z DOUBLE The maximum z value allowed in coordinates.

min_m DOUBLE The minimum m value allowed in coordinates.

max_m DOUBLE The maximum m value allowed in coordinates.

min_lat DOUBLE The minimum latitude value allowed for coordinates.

max_lat DOUBLE The maximum latitude value allowed for coordinates.

min_long DOUBLE The minimum longitude value allowed in coordinates.

max_long DOUBLE The maximum longitude value allowed in coordinates.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1003
Column Name Data Type Description

organization LONG VAR­ The name of the organization that created the coordinate system used by the spatial
CHAR reference system.

organiza­ INTEGER The ID given to the coordinate system by the organization that created it.
tion_coord­
sys_id

lin­ CHAR(128) The linear unit of measurement used by the SRS.


ear_unit_of_me
asure

angu­ CHAR(128) The angular unit of measurement used by the SRS.


lar_unit_of_mea
sure

polygon_format LONG VAR­ The orientation of the rings in a polygon. One of CounterClockwise, ClockWise, or Even­
CHAR Odd.

storage_format LONG VAR­ Whether the data is stored in normalized format (Internal), unnormalized format (Origi­
CHAR nal), or both (Mixed).

definition LONG VAR­ Additional definition settings.


CHAR

transform_defi- LONG VAR­ Transform definition settings for use when transforming data from this SRS to another.
nition CHAR

description LONG VAR­ Description of the SRS.


CHAR

8.2.3.5 ST_UNITS_OF_MEASURE Consolidated View

Each row of the ST_UNITS_OF_MEASURE system view describes a unit of measure defined in the database.
This view offers more information than the SYSUNITOFMEASURE system view.

 Note

Spatial data, spatial references systems, and spatial units of measure can be used only in the catalog store.

Column Name Data Type Description

object_id UNSIGNED BIGINT For system use only.

owner UNSIGNED INT The owner of the unit of measure.

unit_name CHAR(128) The name of the unit of measure.

unit_type CHAR(7) Angular or linear.

conversion_factor DOUBLE The conversion factor for the unit of


measure.

description LONG VARCHAR Description for the unit of measure.

SAP IQ SQL Reference


1004 INTERNAL System Tables and Views
8.2.3.6 SYSARTICLE system view

Each row of the SYSARTICLE system view describes an article in a publication. The underlying system table for
this view is ISYSARTICLE.

Column name Data type Description

publication_id UNSIGNED INT The publication of which the article is a


part.

table_id UNSIGNED INT Each article consists of columns and


rows from a single table. This column
contains the table ID for this table.

where_expr LONG VARCHAR For articles that contain a subset of


rows defined by a WHERE clause, this
column contains the search condition.

subscribe_by_expr LONG VARCHAR For articles that contain a subset of


rows defined by a SUBSCRIBE BY ex­
pression, this column contains the ex­
pression.

query CHAR(1) Indicates information about the article


type to the database server.

alias VARCHAR(256) The alias for the article.

schema_change_active BIT 1 if the table and publication are part of


a synchronization schema change.

Related Information

SYSARTICLECOL system view [page 1005]


SYSARTICLECOLS consolidated view [page 1006]

8.2.3.7 SYSARTICLECOL system view

Each row of the SYSARTICLECOL system view identifies a column in an article. The underlying system table for
this view is ISYSARTICLECOL.

Column name Data type Description

publication_id UNSIGNED INT A unique identifier for the publication of


which the column is a part.

table_id UNSIGNED INT The table to which the column belongs.

column_id UNSIGNED INT The column identifier, from the SYS­


TABCOL system view.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1005
8.2.3.8 SYSARTICLECOLS consolidated view

Each row in the SYSARTICLECOLS view identifies a column in an article.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSARTICLECOLS"


as select p.publication_name,t.table_name,c.column_name
from SYS.ISYSARTICLECOL as ac
join SYS.ISYSPUBLICATION as p on p.publication_id = ac.publication_id
join SYS.ISYSTAB as t on t.table_id = ac.table_id
join SYS.ISYSTABCOL as c on c.table_id = ac.table_id
and c.column_id = ac.column_id

8.2.3.9 SYSARTICLES consolidated view

Each row in the SYSARTICLES view describes an article in a publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSARTICLES"


as select u1.user_name as publication_owner,p.publication_name,
u2.user_name as table_owner,t.table_name,
a.where_expr,a.subscribe_by_expr,a.alias
from SYS.ISYSARTICLE as a
join SYS.ISYSPUBLICATION as p on(a.publication_id = p.publication_id)
join SYS.ISYSTAB as t on(a.table_id = t.table_id)
join SYS.ISYSUSER as u1 on(p.creator = u1.user_id)
join SYS.ISYSUSER as u2 on(t.creator = u2.user_id)

8.2.3.10 SYSCAPABILITIES consolidated view

Each row in the SYSCAPABILITIES view specifies the status of a capability for a remote database server. This
view gets its data from the ISYSCAPABILITY system table.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSCAPABILITIES"


as select
ISYSCAPABILITY.capid,ISYSCAPABILITY.srvid,property('RemoteCapability',ISYSCAPABIL
ITY.capid) as capname,ISYSCAPABILITY.capvalue
from SYS.ISYSCAPABILITY

SAP IQ SQL Reference


1006 INTERNAL System Tables and Views
8.2.3.11 SYSCAPABILITY system view

Each row of the SYSCAPABILITY system view specifies the status of a capability on a remote database server.
The underlying system table for this view is ISYSCAPABILITY.

Column name Data type Description

capid INTEGER The ID of the capability, as listed in the


SYSCAPABILITYNAME system view.

srvid UNSIGNED INT The server to which the capability ap­


plies, as listed in the SYSSERVER sys­
tem view.

capvalue CHAR(128) The value of the capability.

8.2.3.12 SYSCAPABILITYNAME system view

Each row in the SYSCAPABILITYNAME system view provides a name for each capability ID in the
SYSCAPABILITY system view.

Column name Data type Description

capid INTEGER A number uniquely identifying the ca­


pability.

capname VARCHAR(32000) The name of the capability.

Remarks

The SYSCAPABILITYNAME system view is defined using a combination of sa_rowgenerator and the following
server properties:

● RemoteCapability
● MaxRemoteCapability

8.2.3.13 SYSCATALOG consolidated view

Each row in the SYSCATALOG view describes a system table.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSCATALOG"( creator,


tname,dbspacename,tabletype,ncols,primary_key,"check",
remarks )
as select u.user_name,tab.table_name,dbs.dbspace_name,
if tab.table_type_str = 'BASE' then 'TABLE' else tab.table_type_str endif,

SAP IQ SQL Reference


System Tables and Views INTERNAL 1007
(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)

8.2.3.14 SYSCERTIFICATE System View

Each row of the SYSCERTIFICATE system view stores a certificate in text PEM-format. The underlying system
table for this view is ISYSCERTIFICATE.

Column Name Data Type Description

object_id UNSIGNED BIGINT The ID of the certificate.

cert_name CHAR(128) The certificate name.

contents LONG BINARY The certificate contents in a com­


pressed form.

update_time TIMESTAMP The local date and time of the last cre­
ate or replace.

update_time_utc TIMESTAMP WITH TIME ZONE The UTC date and time of the last cre­
ate or replace.

Constraints on Underlying System Table

PRIMARY KEY (object_id)

UNIQUE INDEX (cert_name)

8.2.3.15 SYSCOLLATION compatibility view (deprecated)

The SYSCOLLATION compatibility view contains the collation sequence information for the database. It is
obtainable via built-in functions and is not kept in the catalog. Following is definition for this view:

ALTER VIEW "SYS"."SYSCOLLATION"


as select 1 as collation_id,
DB_PROPERTY('Collation') as collation_label,
DB_EXTENDED_PROPERTY('Collation','Description') as collation_name,
cast(DB_EXTENDED_PROPERTY('Collation','LegacyData') as binary(1280)) as
collation_order

SAP IQ SQL Reference


1008 INTERNAL System Tables and Views
8.2.3.16 SYSCOLLATIONMAPPINGS compatibility view
(deprecated)

The SYSCOLLATIONMAPPINGS compatibility view contains only one row with the database collation mapping.
It is obtainable via built-in functions and is not kept in the catalog. Following is definition for this view:

ALTER VIEW "SYS"."SYSCOLLATIONMAPPINGS"


as select DB_PROPERTY('Collation') as collation_label,
DB_EXTENDED_PROPERTY('Collation','Description') as collation_name,
DB_PROPERTY('Charset') as cs_label,
DB_EXTENDED_PROPERTY('Collation','ASESensitiveSortOrder') as so_case_label,
DB_EXTENDED_PROPERTY('Collation','ASEInsensitiveSortOrder') as
so_caseless_label,
DB_EXTENDED_PROPERTY('Charset','java') as jdk_label

8.2.3.17 SYSCOLPERM system view

The GRANT statement can give UPDATE, SELECT, or REFERENCES privileges to individual columns in a table.
Each column with UPDATE, SELECT, or REFERENCES privileges is recorded in one row of the SYSCOLPERM
system view. The underlying system table for this view is ISYSCOLPERM.

Column name Data type Description

table_id UNSIGNED INT The table number for the table contain­
ing the column.

grantee UNSIGNED INT The ID of the user that has been given
the privilege on the column. If the user
ID is the PUBLIC role, then all users
have the privilege on the column.

grantor UNSIGNED INT The ID of the user that granted the priv­
ilege.

column_id UNSIGNED INT This column number, together with the


table_id, identifies the column for which
privilege has been granted.

privilege_type SMALLINT The number in this column indicates


the kind of column privilege (16=REF­
ERENCES, 1=SELECT, or 8=UPDATE).

is_grantable CHAR(1) Indicates if the privilege on the column


was granted WITH GRANT OPTION.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1009
8.2.3.18 SYSCOLSTAT system view
The SYSCOLSTAT system view contains the column statistics, including histograms, that are used by the
optimizer. The contents of this view are best retrieved using the sa_get_histogram stored procedure or the
Histogram utility. The underlying system table for this view is ISYSCOLSTAT.

Column name Data type Description

table_id UNSIGNED INT A number that uniquely identifies the


table or materialized view to which the
column belongs.

column_id UNSIGNED INT A number that, together with table_id,


uniquely identifies the column.

format_id SMALLINT For system use only.

update_time TIMESTAMP The local 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 selectivi­
ties stored in the row.

max_steps SMALLINT For system use only.

actual_steps SMALLINT For system use only.

step_values LONG BINARY For system use only.

frequencies LONG BINARY For system use only.

update_time_utc TIMESTAMP WITH TIME ZONE The UTC time of the last update of the
column statistics.

 Note

For databases created using SAP IQ 16 or later, the underlying system table for this view is always
encrypted to protect the data from unauthorized access.

8.2.3.19 SYSCOLSTATS consolidated view


The SYSCOLSTATS view contains the column statistics that are stored as histograms and used by the
optimizer.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSCOLSTATS" AS SELECT u.user_name, t.table_name,


c.column_name, s.format_id,
dateadd(mi, PROPERTY('TimeZoneAdjustment'), s.update_time) as update_time,
s.density, s.max_steps, s.actual_steps,
s.step_values, s.frequencies , TODATETIMEOFFSET( s.update_time, 0 ) as
update_time_utc
FROM SYS.ISYSCOLSTAT s
JOIN SYS.ISYSTABCOL c on (s.table_id = c.table_id and s.column_id =
c.column_id)

SAP IQ SQL Reference


1010 INTERNAL System Tables and Views
JOIN SYS.ISYSTAB t on (t.table_id = c.table_id)
JOIN SYS.ISYSUSER u on (u.user_id = t.creator)

8.2.3.20 SYSCOLUMN compatibility view (deprecated)

The SYSCOLUMN view is provided for compatibility with older versions of the software that offered a
SYSCOLUMN system table.

However, the previous SYSCOLUMN table has been replaced by the ISYSTABCOL system table, and its
corresponding SYSTABCOL system view. Use the SYSTABCOL system view instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSCOLUMN"


as select b.table_id,
b.column_id,
if c.sequence is null then 'N' else 'Y' endif as pkey,
b.domain_id,
b.nulls,
b.width,
b.scale,
b.object_id,
b.max_identity,
b.column_name,
r.remarks,
b."default",
b.user_type,
b.column_type
from SYS.SYSTABCOL as b
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)
left outer join SYS.ISYSIDXCOL as c on(b.table_id = c.table_id and
b.column_id = c.column_id and c.index_id = 0)

8.2.3.21 SYSCOLUMNS consolidated view

Each row in the SYSCOLUMNS view describes one column of each table and view in the catalog.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSCOLUMNS"( creator,cname,tname,coltype,nulls,length,


syslength,in_primary_key,colno,default_value,
column_kind,remarks )
as select u.user_name,col.column_name,tab.table_name,dom.domain_name,
col.nulls,col.width,col.scale,if ixcol.sequence is null then 'N' else '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)

SAP IQ SQL Reference


System Tables and Views INTERNAL 1011
8.2.3.22 SYSCOLUMNS ASE Compatibility View

This view is owned by user DBO. syscolumns contains one row for every column in every table and view, and a
row for each parameter in a procedure.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.23 SYSCOMMENTS ASE Compatibility View

syscomments contains entries for each view, rule, default, trigger, table constraint, partition, procedure,
computed column, function-based index key, and other forms of compiled objects.

This view is owned by user DBO.

The text column contains the original definition statements. If the text column is longer than 255 bytes, the
entries span rows. Each object can occupy as many as 65,025 rows.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

SAP IQ SQL Reference


1012 INTERNAL System Tables and Views
8.2.3.24 SYSCONSTRAINT system view

Each row in the SYSCONSTRAINT system view describes a named constraint in the database. The underlying
system table for this view is ISYSCONSTRAINT.

Column name Data type Description

constraint_id UNSIGNED INT The unique ID for the constraint.

constraint_type CHAR(1) The type of constraint:

column check constraint


T

table constraint
P

primary key
F

foreign key
U

unique constraint

ref_object_id UNSIGNED BIGINT The object ID of the column, table, or


index to which the constraint applies.

table_object_id UNSIGNED BIGINT The object ID of the table to which the


constraint applies.

constraint_name CHAR(128) The name of the constraint.

8.2.3.25 SYSDATABASEVARIABLE system view

Each row in the SYSDATABASEVARIABLE system view describes one database-scope variable in the database.
The underlying system table for this view is ISYSDATABASEVARIABLE.

Column name Data type Description

variable_id UNSIGNED INT The ID of the database variable.

object_id UNSIGNED BIGINT The internal ID for the database-scope


variable, uniquely identifying it in the
database.

owner UNSIGNED INT The owner of the database variable.

variable_name CHAR(128) The name of the database variable.

domain_id SMALLINT The ID of the data type as listed in the


SYSDOMAIN system view.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1013
Column name Data type Description

width UNSIGNED INT The length of a string the database vari­


able can hold, the precision of numeric
values for the column, or the number of
bytes of storage needed for any other
data type.

scale SMALLINT The number of digits after the decimal


point for NUMERIC or DECIMAL data
type variables. For a database variable
containing a string, a value of 1 indi­
cates character-length semantics and 0
indicates byte-length semantics.

user_type SMALLINT The data type of the database variable,


or NULL if no type value is present.

initial_value LONG BINARY The initial value of the database varia­


ble. If no value is specified, NULL is
used.

If the initial value was set using an ex­


pression, the expression is evaluated at
creation time and the resulting con­
stant is stored in this column (not the
expression).

base_type_str VARCHAR(32767) The annotated type string representing


the physical type of the database varia­
ble.

initial_value_string LONG VARCHAR The string representation of the initial


value of the database variable.

Remarks

Updates to database-scope variable values, for example using the SET statement, do not persist after a
database restart. Also, updated values are not reflected in this view; only the initial/default value is visible in
this view.

Privileges

None.

SAP IQ SQL Reference


1014 INTERNAL System Tables and Views
8.2.3.26 SYSDBFILE system view

Each row in the SYSDBFILE system view describes a dbspace file. The underlying system table for this view is
ISYSDBFILE.

Column name Data type Description

dbfile_id SMALLINT For internal use only.

dbspace_id SMALLINT Each dbspace file in a database is as­


signed a unique number. The system
dbspace contains all system objects
and has a dbspace_id of 0.

dbfile_name CHAR(128) A unique name for the dbspace. It is


used in the CREATE TABLE command.

file_name LONG VARCHAR The file name for the dbspace.

lob_map LONG VARBIT For internal use only.

server_id UNSIGNED INT (nullable) The ID of the physical server where the
DAS dbfile exists. Applies to shared-
nothing multiplex architecture.

8.2.3.27 SYSDBSPACE system view

Each row in the SYSDBSPACE system view describes a dbspace file. The underlying system table for this view
is ISYSDBSPACE.

Column name Data type Description

dbspace_id SMALLINT Unique number identifying the


dbspace. The system dbspace contains
all system objects and has a
dbspace_id of 0.

object_id UNSIGNED BIGINT The object ID of the dbspace.

dbspace_name CHAR(128) A unique name for the dbspace. It is


used in the CREATE TABLE command.

store_type TINYINT For internal use only.

saved_cache_pages LONG VARBIT The pages of the dbspace that were


present in the cache when the ALTER
DATABASE SAVE CACHE statement
was most recently executed. The value
is NULL if the statement has never been
executed.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1015
8.2.3.28 SYSDBSPACEPERM system view

Each row in the SYSDBSPACEPERM system view describes a privilege on a dbspace file. The underlying system
table for this view is ISYSDBSPACEPERM.

Column name Data type Description

dbspace_id SMALLINT Unique number identifying the


dbspace. The system dbspace contains
all system objects and has a
dbspace_id of 0.

grantee UNSIGNED INT The user ID of the user getting the privi­
lege.

privilege_type SMALLINT The privilege that is granted to the


grantee. For example, CREATE gives the
grantee privilege to create objects on
the dbspace.

8.2.3.29 SYSDEPENDENCY system view

Each row in the SYSDEPENDENCY system view describes a dependency between two database objects. The
underlying system table for this view is ISYSDEPENDENCY.

A dependency exists between two database objects when one object references another object in its definition.
For example, if the query specification for a view references a table, the view is dependent on the table. The
database server tracks dependencies of views on tables, views, materialized views, and columns.

Column name Data type Description

ref_object_id UNSIGNED BIGINT The object ID of the referenced object.

dep_object_id UNSIGNED BIGINT The ID of the referencing object.

8.2.3.30 SYSDOMAIN system view

The SYSDOMAIN system view records information about built-in data types (also called domains). The
contents of this view does not change during normal operation. The underlying system table for this view is
ISYSDOMAIN.

Column name Data type Description

domain_id SMALLINT The unique number assigned to each


data type. These numbers cannot be
changed.

SAP IQ SQL Reference


1016 INTERNAL System Tables and Views
Column name Data type Description

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 corre­


sponds to the value for data_type in the
Transact-SQL compatibility dbo.SYS­
TYPES 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.

8.2.3.31 SYSEVENT system view

Each row in the SYSEVENT system view describes an event created with CREATE EVENT. The underlying
system table for this view is ISYSEVENT.

Column name Data type Description

event_id UNSIGNED INT The unique number assigned to each


event.

object_id UNSIGNED BIGINT The internal ID for the event, uniquely


identifying it in the database.

creator UNSIGNED INT The user number of the owner of the


event. The name of the user can be
found by looking in the SYSUSER sys­
tem view.

event_name VARCHAR(128) The name of the event.

enabled CHAR(1) Indicates whether the event is allowed


to fire.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1017
Column name Data type Description

location CHAR(1) The location where the event is to fire:

● Y = AT ALL clause and FOR PRI­


MARY clause specified
● E = AT CONSOLIDATED clause and
FOR PRIMARY clause specified
● T = AT REMOTE clause and FOR
PRIMARY clause specified
● P = (AT clause not specified) FOR
PRIMARY clause specified
● B = AT ALL clause and FOR ALL
clause specified
● D = AT CONSOLIDATED clause and
FOR ALL clause specified
● S = AT REMOTE clause and FOR
ALL clause specified
● M = (AT clause not specified) FOR
ALL clause specified
● C = AT CONSOLIDATED (FOR
clause not specified)
● R = AT REMOTE (FOR clause not
specified)
● A = AT ALL clause (FOR clause not
specified)

event_type_id UNSIGNED INT For system events, the event type as


listed in the SYSEVENTTYPE system
view.

action LONG VARCHAR The event handler definition. An obfus­


cated value indicates a hidden event.

external_action LONG VARCHAR For system use only.

condition LONG VARCHAR The condition used to control firing of


the event handler.

remarks LONG VARCHAR Remarks for the event; this column


comes from ISYSREMARK.

source LONG VARCHAR The original source for the event; this
column comes from ISYSSOURCE.

8.2.3.32 SYSEVENTTYPE system view

The SYSEVENTTYPE system view defines the system event types that can be referenced by CREATE EVENT.

Column name Data type Description

event_type_id INT The unique number assigned to each


event type.

SAP IQ SQL Reference


1018 INTERNAL System Tables and Views
Column name Data type Description

name VARCHAR(32000) The name of the system event type.

description VARCHAR(32000) A description of the system event type.

Remarks

The SYSEVENTTYPE system view is defined using a combination of sa_rowgenerator and the following server
properties:

● EventTypeName
● EventTypeDesc
● MaxEventType

8.2.3.33 SYSEXTERNENV system view

Each row in the SYSEXTERNENV system view describes the information needed to identify and launch each of
the external environments. The underlying system table for this view is ISYSEXTERNENV.

Column name Data type Description

object_id UNSIGNED BIGINT A unique identifier for the external envi­


ronment.

name CHAR(128) This column identifies the name of the


external environment or language. It is
one of java, perl, php, and so on.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1019
Column name Data type Description

scope CHAR(1) This column is either C for CONNEC­


TION or D for DATABASE respectively.
The scope column identifies if the ex­
ternal environment is launched as one-
per-connection or one-per-database.

For one-per-connection external envi­


ronments (like PERL, PHP, JS,
C_ESQL32, C_ESQL64, C_ODBC32,
and C_ODBC64), there is one instance
of the external environment for each
connection using the external environ­
ment. For a one-per-connection, the ex­
ternal environment terminates when
the connection terminates.

For one-per-database external environ­


ments (such as JAVA), there is one in­
stance of the external environment for
each database using the external envi­
ronment. The one-per-database exter­
nal environment terminates when the
database is stopped.

support_result_sets CHAR(1) This column identifies those external


environments that can return result
sets. All external environments can re­
turn result sets except PERL, PHP, and
JS.

location LONG VARCHAR This column identifies 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 executa­
ble/binary must be in a location where
the database server can find it.

options LONG VARCHAR This column identifies any options re­


quired on the command line to launch
the executable associated with the ex­
ternal environment. Do not modify this
column.

SAP IQ SQL Reference


1020 INTERNAL System Tables and Views
Column name Data type Description

user_id UNSIGNED INT When the external environment is ini­


tially launched, it must make a connec­
tion back to the database to set things
up for the external environment's us­
age. By default, this connection is made
using the DBA user ID, but if the data­
base administrator prefers to have the
external environment use a different
user ID with MANAGE ANY EXTERNAL
OBJECT system privilege, then the
user_id column would indicate that dif­
ferent user ID instead. Typically, this
column is NULL and the database
server, by default, uses the DBA user ID.

8.2.3.34 SYSEXTERNENVOBJECT system view

Each row in the SYSEXTERNENVOBJECT system view describes an installed external object. The underlying
system table for this view is ISYSEXTERNENVOBJECT.

Column name Data type Description

object_id UNSIGNED BIGINT A unique identifier for the external ob­


ject.

extenv_id UNSIGNED BIGINT The unique identifier for the external


environment (SYSEXTERNENV.ob­
ject_id).

owner UNSIGNED INT This column identifies the creator/


owner of the external object.

name LONG VARCHAR This column identifies the name of the


external object as specified in the IN­
STALL EXTERNAL OBJECT statement.

contents LONG BINARY The contents of the external object.

update_time TIMESTAMP This column identifies the last local


time the object was modified (or instal­
led).

update_time_utc TIMESTAMP WITH TIME ZONE This column identifies the last UTC time
the object was modified (or installed).

SAP IQ SQL Reference


System Tables and Views INTERNAL 1021
8.2.3.35 SYSEXTERNLOGIN system view

Each row in the SYSEXTERNLOGIN system view describes an external login for remote data access. The
underlying system table for this view is ISYSEXTERNLOGIN.

Column name Data type Description

user_id UNSIGNED INT The user ID on the local database.

srvid UNSIGNED INT The remote server, as listed in the SYS­


SERVER system view.

remote_login VARCHAR(128) The login name for the user, for the re­
mote server.

remote_password CHAR(3) Whether a password is stored. Three


asterisks (***) indicate that a password
is stored. NULL indicates that no pass­
word is stored. You can obtain the pass­
word hash by querying the SYSEX­
TERNLOGINPASSWORD system view.

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.

8.2.3.36 SYSFILE compatibility view (deprecated)

Each row in the SYSFILE system view describes a dbspace for a database. Every database consists of one or
more dbspaces; each dbspace corresponds to an operating system file.

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)

SAP IQ SQL Reference


1022 INTERNAL System Tables and Views
8.2.3.37 SYSFKCOL compatibility view (deprecated)

Each row of SYSFKCOL describes the association between a foreign column in the foreign table of a
relationship and the primary column in the primary table. This view is deprecated; use the SYSIDX and
SYSIDXCOL system views instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSFKCOL"


as select a.table_id as foreign_table_id,
a.index_id as foreign_key_id,
a.column_id as foreign_column_id,
a.primary_column_id
from SYS.ISYSIDXCOL as a
,SYS.ISYSIDX as b
where a.table_id = b.table_id
and a.index_id = b.index_id
and b.index_category = 2

8.2.3.38 SYSFKEY system view

Each row in the SYSFKEY system view describes a foreign key constraint in the system. The underlying system
table for this view is ISYSFKEY.

Column name Data type Description

foreign_table_id UNSIGNED INT The table number of the foreign table.

foreign_index_id UNSIGNED INT The index number for the foreign key.

primary_table_id UNSIGNED INT The table number of the primary table.

primary_index_id UNSIGNED INT The index number of the primary key.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1023
Column name Data type Description

match_type TINYINT The matching type for the constraint.


Matching types include:

Use the default matching


1

SIMPLE
2

FULL
129

SIMPLE UNIQUE
130

FULL UNIQUE

For more information about match


types, see the MATCH clause of the
CREATE TABLE statement.

check_on_commit CHAR(1) Indicates whether INSERT and UPDATE


statements should wait until the COM­
MIT to check if foreign keys are still
valid. Values are 'Y' for wait or 'N' for do
not wait.

nulls CHAR(1) Indicates whether the columns in the


foreign key are allowed to contain the
NULL value. This setting is independent
of the nulls setting in the columns con­
tained in the foreign key. Values are 'Y'
for allowed or 'N' for not allowed.

8.2.3.39 SYSFOREIGNKEY compatibility view (deprecated)

The SYSFOREIGNKEY view is provided for compatibility with older versions of the software that offered a
SYSFOREIGNKEY system table. However, the previous SYSFOREIGNKEY system table has been replaced by
the ISYSFKEY system table, and its corresponding SYSFKEY system view, which you should use instead.

A foreign key is a relationship between two tables: the foreign table and the primary table. Every foreign key is
defined by one row in SYSFOREIGNKEY and one or more rows in SYSFKCOL. SYSFOREIGNKEY contains
general information about the foreign key while SYSFKCOL identifies the columns in the foreign key and
associates each column in the foreign key with a column in the primary key of the primary table.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSFOREIGNKEY"


as select b.foreign_table_id,
b.foreign_index_id as foreign_key_id,
a.object_id,

SAP IQ SQL Reference


1024 INTERNAL System Tables and Views
b.primary_table_id,
p.root,
b.check_on_commit,
b.nulls,
a.index_name as role,
r.remarks,
b.primary_index_id,
a.not_enforced as fk_not_enforced,
10 as hash_limit
from(SYS.ISYSIDX as a left outer join SYS.ISYSPHYSIDX as p on(a.table_id =
p.table_id and a.phys_index_id = p.phys_index_id))
left outer join SYS.ISYSREMARK as r on(a.object_id = r.object_id)
,SYS.ISYSFKEY as b
where a.table_id = b.foreign_table_id
and a.index_id = b.foreign_index_id

8.2.3.40 SYSFOREIGNKEYS consolidated view

Each row in the SYSFOREIGNKEYS view describes one foreign key for each table in the catalog.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSFOREIGNKEYS"( foreign_creator,


foreign_tname,
primary_creator,primary_tname,role,columns )
as select fk_up.user_name,fk_tab.table_name,pk_up.user_name,
pk_tab.table_name,ix.index_name,
(select list(string(fk_col.column_name,' IS ',
pk_col.column_name)
order by fkc.table_id,fkc.index_id,fkc."sequence")
from SYS.ISYSIDXCOL as fkc
join SYS.ISYSTABCOL as fk_col on(
fkc.table_id = fk_col.table_id
and fkc.column_id = fk_col.column_id)
,SYS.ISYSTABCOL as pk_col
where fkc.table_id = fk.foreign_table_id
and fkc.index_id = fk.foreign_index_id
and pk_col.table_id = fk.primary_table_id
and pk_col.column_id = fkc.primary_column_id)
from SYS.ISYSFKEY as fk
join SYS.ISYSTAB as fk_tab on fk_tab.table_id = fk.foreign_table_id
join SYS.ISYSUSER as fk_up on fk_up.user_id = fk_tab.creator
join SYS.ISYSTAB as pk_tab on pk_tab.table_id = fk.primary_table_id
join SYS.ISYSUSER as pk_up on pk_up.user_id = pk_tab.creator
join SYS.ISYSIDX as ix on ix.table_id = fk.foreign_table_id and
ix.index_id = fk.foreign_index_id

SAP IQ SQL Reference


System Tables and Views INTERNAL 1025
8.2.3.41 SYSGROUP compatibility view

There is one row in the SYSGROUP system view for each member of each group. This view describes the many-
to-many relationship between groups and members. A group may have many members, and a user may be a
member of many groups.

Column name Data type Description

group_id UNSIGNED INT The user number of the group.

group_member UNSIGNED INT The user number of a member.

8.2.3.42 SYSGROUPS compatibility view

There is one row in the SYSGROUPS view for each member of each group. This view describes the many-to-
many relationship between groups and members. A group may have many members, and a user may be a
member of many groups.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSGROUPS"( group_name,


member_name )
as select g.user_name,u.user_name
from SYS.ISYSROLEGRANT,SYS.ISYSUSER as g,SYS.ISYSUSER as u
where ISYSROLEGRANT.role_id = g.user_id and ISYSROLEGRANT.grantee =
u.user_id and(
u.user_name in( 'SYS_SPATIAL_ADMIN_ROLE' )
or u.user_id <= 2147483648) and(
g.user_type = (0x02|0x04|0x08)
or g.user_name in( 'SYS','PUBLIC','dbo','diagnostics',
'rs_systabgroup','SA_DEBUG','SYS_SPATIAL_ADMIN_ROLE' ) )

SAP IQ SQL Reference


1026 INTERNAL System Tables and Views
8.2.3.43 SYSHISTORY system view

Each row in the SYSHISTORY system view records a system operation on the database, such as a database
start, a database calibration, and so on. The underlying system table for this view is ISYSHISTORY.

Column name Data type Description

operation CHAR(128) The type of operation performed on the


database file. The operation must be
one of the following values:

INIT

Information about when the data­


base was created.
UPGRADE

Information about when the data­


base was upgraded.
START

Information about when the data­


base was started using a specific
version of the database server on a
particular operating system.
LAST_START

Information about the most recent


time the database server was
started. A LAST_START operation
is converted to a START operation
when the database is started with
a different version of the database
server and/or on a different oper­
ating system than those values
currently stored in the
LAST_START row.
DTT

Information about the second to


last Disk Transfer Time (DTT) cali­
bration operation performed on
the dbspace. That is, information
about the second to last execution
of either an ALTER DATABASE
CALIBRATE or ALTER DATABASE
RESTORE DEFAULT CALIBRATION
statement.
LAST_DTT

Information about the most recent


DTT calibration operation per­

SAP IQ SQL Reference


System Tables and Views INTERNAL 1027
Column name Data type Description

formed on the dbspace. That is, in­


formation about the most recent
execution of either an ALTER DA­
TABASE CALIBRATE or ALTER DA­
TABASE RESTORE DEFAULT CALI­
BRATION statement.
LAST_BACKUP

Information about the last backup,


including date and time of the
backup, the backup type, the files
that were backed up, and the ver­
sion of database server that per­
formed the backup.

object_id UNSIGNED INT For any operation other than DTT and
LAST_DTT, the value in this column will
be 0. For DTT and LAST_DTT opera­
tions, this is the dbspace_id of the
dbspace as defined in the SYSDB­
SPACE system view.

sub_operation CHAR(128) For any operation other than DTT and


LAST_DTT, the value in this column will
be a set of empty single quotes ("). For
DTT and LAST_DTT operations, this col­
umn contains the type of sub-operation
performed on the dbspace. Values in­
clude:

DTT_SET

The dbspace calibration has been


set.
DTT_UNSET

The dbspace calibration has been


restored to the default setting.

version CHAR(128) The version and build number of the da­


tabase server used to perform the oper­
ation.

platform CHAR(128) The operating system on which the op­


eration was carried out.

first_time TIMESTAMP The local date and time the database


was first started on a particular operat­
ing system with a particular version of
the software.

SAP IQ SQL Reference


1028 INTERNAL System Tables and Views
Column name Data type Description

last_time TIMESTAMP The most recent local date and time the
database was started on a particular
operating system with a particular ver­
sion of the software.

details LONG VARCHAR This column stores information such as


command line options used to start the
database server or the capability bits
enabled for the database. This informa­
tion is for use by Technical Support.

first_time_utc TIMESTAMP WITH TIME ZONE The UTC date and time the database
was first started on a particular operat­
ing system with a particular version of
the software.

last_time_utc TIMESTAMP WITH TIME ZONE The most recent UTC date and time the
database was started on a particular
operating system with a particular ver­
sion of the software.

8.2.3.44 SYSIDX system view

Each row in the SYSIDX system view defines a logical index in the database. The underlying system table for
this view is ISYSIDX.

Column name Data type Description

table_id UNSIGNED INT Uniquely identifies the table to which


this index applies.

index_id UNSIGNED INT A unique number identifying the index


within its table.

object_id UNSIGNED BIGINT The internal ID for the index, uniquely


identifying it in the database.

phys_index_id UNSIGNED INT Identifies the underlying physical index


used to implement the logical index.
This value is NULL for indexes on tem­
porary tables or remote tables. Other­
wise, the value corresponds to the ob­
ject_id of a physical index in the SY­
SPHYSIDX system view.

dbspace_id SMALLINT The ID of the file in which the index is


contained. This value corresponds to an
entry in the SYSDBSPACE system view.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1029
Column name Data type Description

index_category TINYINT The type of index. Values include:

Primary key
2

Foreign key
3

Secondary index (includes unique


constraints)
4

Text indexes

"unique" TINYINT Indicates whether the index is a unique


index (1), a unique constraint (2), re­
served (3), a non-unique index (4), or a
unique index WITH NULLS NOT DIS­
TINCT (5).

index_name CHAR(128) The name of the index.

not_enforced CHAR(1) For internal use only.

file_id SMALLINT DEPRECATED. This column is present in


SYSVIEW, but not in the underlying sys­
tem table ISYSIDX. The contents of this
column are the same as dbspace_id,
and it is provided for compatibility. Use
dbspace_id instead.

8.2.3.45 SYSIDXCOL system view

Each row in the SYSIDXCOL system view describes one column of an index described in the SYSIDX system
view. The underlying system table for this view is ISYSIDXCOL.

Column name Data type Description

table_id UNSIGNED INT Identifies the table to which the index


applies.

index_id UNSIGNED INT Identifies the index to which the column


applies. Together, table_id and index_id
identify one index described in the SY­
SIDX system view.

sequence SMALLINT Each column in an index is assigned a


unique number starting at 0. The order
of these numbers determines the rela­
tive significance of the columns in the
index. The most important column has
sequence number 0.

SAP IQ SQL Reference


1030 INTERNAL System Tables and Views
Column name Data type Description

column_id UNSIGNED INT Identifies which column of the table is


indexed. Together, table_id and col­
umn_id identify one column described
in the SYSCOLUMN system view.

"order" CHAR(1) Indicates whether the column in the in­


dex is kept in ascending(A) or descend­
ing(D) order. This value is NULL for text
indexes.

primary_column_id UNSIGNED INT The ID of the primary key column that


corresponds to this foreign key column.
The value is NULL for non foreign key
columns.

8.2.3.46 SYSINDEX compatibility view (deprecated)

The SYSINDEX view is provided for compatibility with older versions of the software that offered a SYSINDEX
system table. However, the SYSINDEX system table has been replaced by the ISYSIDX system table, and its
corresponding SYSIDX system view, which you should use instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSINDEX"


as select b.table_id,
b.index_id,
b.object_id,
p.root,
b.dbspace_id,
case b."unique"
when 1 then 'Y'
when 2 then 'U'
when 3 then 'M'
when 4 then 'N'
when 5 then 'Y'
else 'I'
end as "unique",
t.creator,
b.index_name,
r.remarks,
10 as hash_limit,
b.dbspace_id as file_id
from(SYS.ISYSIDX as b left outer join SYS.ISYSPHYSIDX as p on(b.table_id =
p.table_id and b.phys_index_id = p.phys_index_id))
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)
,SYS.ISYSTAB as t
where t.table_id = b.table_id
and b.index_category = 3

SAP IQ SQL Reference


System Tables and Views INTERNAL 1031
8.2.3.47 SYSINDEXES consolidated view

Each row in the SYSINDEXES view describes one index in the database. As an alternative to this view, you could
also use the SYSIDX and SYSIDXCOL system views.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSINDEXES"( icreator,


iname,fname,creator,tname,indextype,
colnames,interval,level_num )
as select u.user_name,idx.index_name,dbs.dbspace_name,u.user_name,
tab.table_name,
case idx.index_category
when 1 then 'Primary Key'
when 2 then 'Foreign Key'
when 3 then(
if idx."unique" = 4 then 'Non-unique'
else if idx."unique" = 2 then 'UNIQUE constraint'
else if idx."unique" = 5 then 'UNIQUE NULLS NOT DISTINCT'
else 'UNIQUE'
endif
endif
endif) when 4 then 'Text Index' end,(select list(string(c.column_name,
if ixc."order" = 'A' then ' ASC' else ' DESC' endif) order by
ixc.table_id asc,ixc.index_id asc,ixc.sequence asc)
from SYS.ISYSIDXCOL as ixc
join SYS.ISYSTABCOL as c on(
c.table_id = ixc.table_id
and c.column_id = ixc.column_id)
where ixc.index_id = idx.index_id
and ixc.table_id = idx.table_id),
0,0
from SYS.ISYSTAB as tab
join SYS.ISYSDBSPACE as dbs on(tab.dbspace_id = dbs.dbspace_id)
join SYS.ISYSIDX as idx on(idx.table_id = tab.table_id)
join SYS.ISYSUSER as u on u.user_id = tab.creator

8.2.3.48 SYSINDEXES ASE Compatibility View

sysindexes contains one row for each clustered index, one row for each nonclustered index, one row for each
table that has no clustered index, and one row for each table that contains text or image columns.

This table also contains one row for each function-based index or index created on a computed column.

This view is owned by user DBO.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSIQOBJECTS ASE Compatibility View [page 1046]

SAP IQ SQL Reference


1032 INTERNAL System Tables and Views
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.49 SYSINFO compatibility view (deprecated)

The SYSINFO view indicates the database characteristics, as defined when the database was created. It always
contains only one row. This view is obtainable via built-in functions and is not kept in the catalog. Following is
the definition for the SYSINFO view:

ALTER VIEW "SYS"."SYSINFO"( page_size,


encryption,
blank_padding,
case_sensitivity,
default_collation,
database_version )
as select db_property('PageSize'),
if db_property('Encryption') <> 'None' then 'Y' else 'N' endif,
if db_property('BlankPadding') = 'On' then 'Y' else 'N' endif,
if db_property('CaseSensitive') = 'On' then 'Y' else 'N' endif,
db_property('Collation'),
NULL

8.2.3.50 SYSIQBACKUPHISTORY System View

This view presents group information from ISYSIQBACKUPHISTORY in a readable format. Each row in this view
describes a particular backup operation that finished successfully.

Column
Column Name Column Type Constraint Description

bu_id UNSIGNED BIGINT NOT NULL Transaction identifier of the checkpoint of the opera­
tion. Backup ID for backup operations.

bu_time TIMESTAMP NOT NULL Time of backup operation that is recorded in backup
record.

type TINYINT NOT NULL Backup type:

● 0 = FULL
● 1 = INCREMENTAL
● 2 = INCREMENTAL SINCE FULL

selective_type TINYINT NOT NULL Backup subtype:

● 0 = ALL (backs up all dbfiles)


● 1 = READ/WRITE ONLY (backs up all read-write
files)
● 2 = READ ONLY (backs up a particular read-only
file)

SAP IQ SQL Reference


System Tables and Views INTERNAL 1033
Column
Column Name Column Type Constraint Description

virtual_type TINYINT NOT NULL Backup virtual type:

● 0 = NONE
● 1 = DECOUPLED
● 2 = ENCAPSULATED

dependson_id UNSIGNED BIGINT NULL NULL for FULL backup.

cmd LONG VARCHAR NOT NULL Full text of command.

creator CHAR(128) NOT NULL User who issued backup command.

version UNSIGNED INT NOT NULL Backup version.

Remarks

The view SYSIQBACKUP projects equivalent string values for columns type, subtype, and bkp_virtual.

Constraints on Underlying System Table

Primary key (bu_id)

Related Information

sp_iqbackupdetails Procedure [page 588]

8.2.3.51 SYSIQBACKUPHISTORYDETAIL System View

This view describes all the dbfile records present in the database at backup time. Each row in this view
describes a particular backup operation that finished successfully.

Column Name Column Type Description.

bu_id UNSIGNED BIGINT Transaction identifier of the checkpoint of the operation.


Backup ID for backup operation.

dbspace_id SMALLINT The dbspace ID of which this dbfile record is associated.

dbfile_id SMALLINT The dbfile ID present in dbspace during ongoing backup op­
eration.

SAP IQ SQL Reference


1034 INTERNAL System Tables and Views
Column Name Column Type Description.

dbspace_rwstatus CHAR(1) T indicates read-write.

dbspace_createid UNSIGNED BIGINT The transaction ID of the transaction that created the
dbspace.

dbspace_alterid UNSIGNED BIGINT Transaction ID that marked the dbspace RO. If not marked,
then the create ID.

dbspace_online CHAR(1) T indicates online.

dbfile_rwstatus CHAR(1) T indicates read-write.

dbfile_createid UNSIGNED BIGINT The transaction ID of the transaction that created this dbfile.

dbfile_alterid UNSIGNED BIGINT The transaction ID of the transaction that last altered the
read-write status of this dbfile.

is_backed_up CHAR(1) Indicates that the dbfile is backed up in this backup.

start_block UNSIGNED BIGINT Start block for the dbfile.

num_blocks UNSIGNED BIGINT Total number of blocks in dbfile.

num_blocks_backed_u UNSIGNED BIGINT Total number of blocks backed up.


p

dbspace_name CHAR(128) Dbspace name.

dbfile_name CHAR(128) Logical file name of the dbfile.

dbfile_path LONG VARCHAR Physical path of the file.

Remarks

It presents group information from ISYSIQBACKUPHISTORYDETAIL in a readable format. The column


constraint for each column is NOT NULL.

Constraints on Underlying System Table

Primary key (bu_id, dbfile_id)

Foreign key (txn_id) references SYS.ISYSBACKUPHISTORY

SAP IQ SQL Reference


System Tables and Views INTERNAL 1035
8.2.3.52 SYSIQCOLUMN System View (Deprecated)

SYSIQCOLUMN has been replaced by the SYSIQTABCOL system view.

Related Information

SYSIQTABCOL System View [page 1050]

8.2.3.53 SYSIQDBFILE System View

Presents group information from ISYSIQDBFILE in a readable format.

 Note

This view replaces the deprecated system view SYSIQFILE.

Column Name Column Type Description

dbfile_id SMALL INT Unique ID for the dbfile.

start_block ROWID Number of the first block.

block_count ROWID Number of blocks for this file (dbspace).

reserve_size ROWID Pre-allocated file system space for the dbspace.

allocated CHAR(1) Defines whether the segment is pre-allocated (T) or auto-al­


located (F).

data_offset UNSIGNED INT Identifies the byte location of where the SAP IQ data starts,
relative to the beginning of the raw partition.

create_time TIMESTAMP Date and time the file was created.

last_modified TIMESTAMP Date and time the file was last modified.

read_write CHAR(1) T indicates read-write.

online CHAR(1) T indicates online.

create_txn_id UNSIGNED BIGINT Transaction ID that created the dbfile.

alter_txn_id UNSIGNED BIGINT Transaction ID that last modified read_write status.

server_id UNSIGNED INT Multiplex server name.

Constraints on Underlying System Table

Foreign key (server_id) references SYS.ISYSIQMPXSERVER

SAP IQ SQL Reference


1036 INTERNAL System Tables and Views
Unique (server_id, file_name)

Related Information

SYSIQFILE System View (Deprecated) [page 1038]

8.2.3.54 SYSIQDBSPACE System View

Presents group information from ISYSIQDBSPACE in a readable format.

Column Name Column Type Description

dbspace_id SMALL INT Each dbspace in a database is assigned a unique number


(dbspace ID).

last_modified TIMESTAMP Time at which the dbspace's read-write status was last
modified.

segment_type CHAR(8) Segment type:

● Main
● Temp
● Msg

read_write CHAR(1) Values:

● 'T' – read writable


● 'F' – read only

online CHAR(1) Values:

● 'T' – online
● 'F' – offline

create_txn_id UNSIGNED BIGINT Transaction ID that create the dbspace.

alter_txn_id UNSIGNED BIGINT Transaction ID that last modified read_write status.

striping_on CHAR(1) Disk striping:

● 'T' – on
● 'F' – off

stripe_size_kb UNSIGNED INT Number of kilobytes written to each file of the dbspace be­
fore the disk striping algorithm moves to the next dbfile.

is_rlv_store CHAR(1) Values:

● 'T' – is the RLV store dbspace


● 'F' – is not the RLV store dbspace

SAP IQ SQL Reference


System Tables and Views INTERNAL 1037
Constraints on Underlying System Table

Primary key (dbspace_id)

Foreign key (dbspace_id) references SYS.ISYSDBSPACE(dbspace_id)

8.2.3.55 SYSIQFILE System View (Deprecated)

SYSIQFILE has been replaced by the SYSIQDBFILE system view.

Related Information

SYSIQDBFILE System View [page 1036]

8.2.3.56 SYSIQIDX System View

Presents group information from ISYSIQIDX in a readable format. Each row in the SYSIQIDX view describes
an IQ index.

 Note

This view replaces the deprecated system view SYSIQINDEX.

Column Name Column Type Description

table_id UNSIGNED INT The table number uniquely identifies the table to which this
index applies.

index_id UNSIGNED INT Each index for one particular table is assigned a unique in­
dex number.

index_type CHAR(4) Index type.

index_owner CHAR(4) Index owner.

max_key UNSIGNED INT For internal use.

identity_location HS_VDORECID For internal use.

identity_size UNSIGNED INT For internal use.

identity_location_size UNSIGNED INT For internal use.

link_index_id UNSIGNED INT For internal use.

SAP IQ SQL Reference


1038 INTERNAL System Tables and Views
Column Name Column Type Description

delimited_by VARCHAR(1024) (WD indexes only) List of separators used to parse a col­
umn’s string into the words to be stored in that column’s WD
index.

limit UNSIGNED INT (WD indexes only) Maximum word length for WD index.

Constraints on Underlying System Table

Primary key (table_id, index_id)

Foreign key (table_id, index_id) references SYS.ISYIDX

Foreign key (link_table_id, link_index_id, table_id, index_id) references


SYS.ISYSIDX

8.2.3.57 SYSIQINFO System View

Presents group information from ISYSIQINFO in a readable format.

The ISYSIQINFO system table indicates the database characteristics as defined when the SAP IQ database was
created using CREATE DATABASE. It always contains only one row.

Column Name Column Type Description

create_time TIMESTAMP NOT NULL Date and time that the database was cre­
ated

update_time TIMESTAMP NOT NULL Date and time of the last update

file_format_version UNSIGNED INT NOT NULL File format number of files for this data­
base

cat_format_version UNSIGNED INT NOT NULL Catalog format number for this database

sp_format_version UNSIGNED INT NOT NULL Stored procedure format number for this
database

block_size UNSIGNED INT NOT NULL Block size specified for the database

chunk_size UNSIGNED INT NOT NULL Number of blocks per page as determined
by the block size and page size specified
for the database

file_format_date CHAR(10) NOT NULL Date when file format number was last
changed

dbsig BINARY(136) NOT NULL Used internally by catalog

commit_txn_id UNSIGNED BIGINT Used internally

rd_commit_txn_id UNSIGNED BIGINT Used internally

SAP IQ SQL Reference


System Tables and Views INTERNAL 1039
Column Name Column Type Description

multiplex name CHAR(128) NULL Name of the multiplex that this database is
a member of

last_multiplex_mode TINYINT NULL (Column unused in SAP IQ 16.1) Mode of


the server that last opened the catalog
read-write. One of the following values.

● 0 – single node
● 1 – reader
● 2 – coordinator
● 3 – writer

8.2.3.58 SYSIQLOGICALSERVER System View

Presents a readable version of the ISYSIQLOGICALSERVER system table.

Column
Name Column Type Description

ls_id UNSIGNED BIGINT NOT NULL The ID number of the logical server.

ls_object_id UNSIGNED BIGINT NOT NULL The logical server object ID number.

ls_policy_id UNSIGNED BIGINT NOT NULL The ID number of the logical server policy.

ls_name CHAR(128) NOT NULL UNIQUE The logical server name.

Remarks

The ISYSIQLOGICALSERVER system table stores logical server information and associated logical server policy
information.

Constraints on Underlying System Table

Primary key(ls_id)

object_id foreign key(ISYSOBJECT)

ls_policy_id foreign key(ISYSIQLSPOLICY)

SAP IQ SQL Reference


1040 INTERNAL System Tables and Views
8.2.3.59 SYSIQLOGINPOLICYLSINFO System View

Presents a readable version of the table ISYSIQLOGINPOLICYLSINFO.

Column Name Column Type Description

login_policy_id UNSIGNED BIGINT NOT NULL The ID number of the login policy.

ls_id UNSIGNED BIGINT NOT NULL The ID number of the logical server.

Remarks

The ISYSIQLOGINPOLICYLSINFO system table stores the login policy logical server assignment information.

Constraints on Underlying System Table

Primary key(login_policy_id, ls_id)

login_policy_id foreign key(ISYSLOGINPOLICY)

ls_id foreign key(ISYSIQLOGICALSERVER)

8.2.3.60 SYSIQLSLOGINPOLICIES Consolidated View

Describes all the logical server assignments from the login policies.

This consolidated system view shows information from SYSIQLOGICALSERVER, ISYSIQLOGINPOLICYLSINFO,


and ISYSLOGINPOLICY.

Column Name Column Type Description

ls_id UNSIGNED BIGINT NOT NULL Logical server identifier.

ls_name CHAR(128) Logical server name.

login_policy_id UNSIGNED BIGINT NOT NULL The ID number of the login policy.

login_policy_name CHAR(128) The name of the login policy.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1041
8.2.3.61 SYSIQLSLOGINPOLICYOPTION System View

Presents a version of the table ISYSIQLSLOGINPOLICYOPTION in a readable format.

Column Name Column Type Description

login_policy_id UNSIGNED BIGINT NOT NULL The ID number of the login policy.

ls_id UNSIGNED BIGINT NOT NULL Logical server identifier.

login_option_name CHAR(128) NOT NULL The name of the login policy option.

login_option_value LONG VARCHAR NOT NULL The value of the login policy option.

Remarks

The ISYSIQLSLOGINPOLICYOPTION table stores the logical server level settings for login policy option values.

Constraints on Underlying System Table

Primary key(login_policy_id,ls_id, login_option_name)

login_policy_id foreign key(ISYSLOGINPOLICY)

ls_id foreign key(ISYSIQLOGICALSERVER)

8.2.3.62 SYSIQLSMEMBER System View

Presents group information from the ISYSIQLSMEMBER table, which stores logical server membership
information.

Column Name Column Type Description

ls_id UNSIGNED BIGINT NOT NULL The ID number of the logical server.

logical_member­ TINYNT NOT NULL The type of the logical membership.


ship_type

mpx_server_id UNSIGNED INT NOT NULL The ID number of the multiplex server.

membership_info UNSIGNED INT NOT NULL The membership information.

Remarks

ISYSIQLSMEMBER stores the logical servers and their corresponding multiplex servers.

SAP IQ SQL Reference


1042 INTERNAL System Tables and Views
For logical server memberships that are defined using the multiplex server name, the value of
logical_membership_type is 0 and mpx_server_id is the server id of the multiplex server.

For the logical membership of the coordinator, mpx_server_id is 0 and logical_membership_type is 1.

Constraints on Underlying System Table

Primary key(ls_id, logical_membership_id, mpx_server_id)

ls_id foreign key(ISYSIQLOGICALSERVER)

8.2.3.63 SYSIQLSMEMBERS Consolidated View

Describes all user-defined logical server memberships.

Column Name Column Type Description

ls_id UNSIGNED BIGINT NOT NULL The ID number of the logical server.

ls_name CHAR(128) NOT NULL The name of the logical server.

server_id UNSIGNED INT NOT NULL Values:

● The multiplex server identifier of the member, for the


membership defined using server name, or
● 0 – for the logical membership of the coordinator.

server_name CHAR(128) NOT NULL Values:

● The multiplex server name of the member for the mem­


bership defined using the server name, or
● 'LOGICAL COORDINATOR' – for the logical membership of
the coordinator.

membership_type TINYINT NOT NULL Values:

● 0 – the membership defined using the server name


● 1 – the logical membership of the coordinator

8.2.3.64 SYSIQLSPOLICY System View

Presents a version of the table ISYSIQLSPOLICY in a readable format.

The ISYSIQLSPOLICY system table stores the logical server policies.

Column Name Column Type Description

ls_policy_Id UNSIGNED BIGINT NOT NULL The ID number of the logical server policy.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1043
Column Name Column Type Description

ls_policy_name CHAR(128) NOT NULL UNIQUE The logical server policy name.

Constraints on Underlying System Table

Primary key(ls_policy_id)

object_id foreign key(ISYSOBJECT)

8.2.3.65 SYSIQLSPOLICYOPTION System View

Presents a version of the table ISYSIQLSPOLICYOPTION in a readable format.

The ISYSIQLSPOLICYOPTION table stores the logical server policy options.

Column Name Column Type Description

ls_policy_id UNSIGNED BIGINT NOT NULL The ID number of the login policy.

ls_policy_option_name CHAR(128) NOT NULL The logical server policy option name.

ls_policy_option_value LONG VARCHAR NOT NULL The logical server policy option value.

Constraints on Underlying System Table

Primary key(ls_policy_id, ls_policy_option_name)

ls_policy_id foreign key(ISYSIQLSPOLICY)

8.2.3.66 SYSIQMPXSERVER System View

Presents a readable version of the table ISYSIQMPXSERVER. The ISYSIQMPXSERVER system table stores
membership properties and version status data for the given multiplex node.

Column Name Column Type Description

server_id UNSIGNED INT NOT NULL The ID number of the server.

server_name CHAR(128) NOT NULL The server name; case-insensitive unique.

SAP IQ SQL Reference


1044 INTERNAL System Tables and Views
Column Name Column Type Description

role TINYINT NOT NULL ● 0 – coordinator


● 1 – reader
● 2 – writer

status TINYINT NOT NULL ● 0 – included


● 1 – excluded

current_version UNSIGNED BIGINT NULL Current version ID of the server.

active_version LONG BINARY NULL The list of active versions on the server (encoded).

connection_info LONG VARCHAR NULL String containing host name and port pairs for public
domain connections, delimited by semicolons.

db_path LONG VARCHAR NOT NULL Full path to the database file for the server.

private_connection_info LONG VARCHAR NULL String containing host name and port pairs for private
network connections, delimited by semicolons.

rlvstore TINYINT Existence of RLV store on multiplex.

● 0 – disabled
● 1 – enabled

Constraints on Underlying System Table

Primary key(server_id)

8.2.3.67 SYSIQMPXSERVERAGENT System View

Presents a readable version of the table ISYSIQMPXSERVERAGENT, which stores agent connection definitions
for the specified multiplex server.

Column Name Column Type Description

server_id UNSIGNED INT NOT NULL The ID number of the server.

agent_connection_info LONG VARCHAR NOT NULL String containing host name and port pairs for SAP IQ
Cockpit agent connections on each multiplex node, sep­
arated by semicolons.

agent_user_name LONG VARCHAR NOT NULL String containing user name for the SAP IQ Cockpit
agent.

agent_pwd VARBINARY(1024) NOT NULL String containing encrypted password for the SAP IQ
Cockpit agent.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1045
Constraints on Underlying System Table

Primary key(server_id)

Foreign key(server_id) references SYS.SYSIQMPXSERVER

8.2.3.68 SYSIQOBJECTS ASE Compatibility View

sysiqobjects presents one row for each system table, user table, view, procedure, trigger, event, constraint,
domain (sysdomain), domain (sysusertype), column, and index. This view is owned by user DBO.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.69 SYSIQPARTITIONCOLUMN System View

Presents group information from ISYSIQPARTITIONCOLUMN in a readable format.

ALTER VIEW "SYS"."SYSIQPARTITIONCOLUMN"


as select * from SYS.ISYSIQPARTITIONCOLUMN

Each row in the SYSIQPARTITIONCOLUMN view describes a column in a partition described in the
SYSIQPARTITION view in a partitioned table described in the SYSPARTITIONSCHEME view.
SYSIQPARTITIONCOLUMN only describes partitions of columns that are not stored on the dbspace of the
partition.

Column Name Column Type Description

partitioned_object_id UNSIGNED BIGINT Unique ID assigned to each partitioned


object (table)

partition_id UNSIGNED INT Identifies a partition in a partitioned table.

column_id UNSIGNED INT The column ID of the column.

SAP IQ SQL Reference


1046 INTERNAL System Tables and Views
Column Name Column Type Description

dbspace_id SMALLINT The dbspace ID of the dbspace where this


column of the partition is stored.

Constraints on Underlying System Table

Primary key (partitioned_object_id, partition_id, column_id)

Foreign key (partitioned_object_id, partition_id) references SYS.ISYSPARTITION

Foreign key (dbspace_id) references SYS.ISYSDBSPACE

8.2.3.70 SYSIQRVLOG System View

Presents group information from ISYSIQRVLOG in a readable format. Each row in the SYSIQRVLOG view
corresponds to a log for a RLV-enabled table . The row with table_id 0 represents the server-wide commit log.

Column Name Column Type Description

stream_id UNSIGNED INT The log stream identifier.

table_id UNSIGNED INT Indicates the table the log stream be­
longs to. NULL indicates a commit log
stream.

partition_low UNSIGNED INT Corresponds to the partition map in use


when that log was last active.

partition_high INT Corresponds to the partition map in use


when that log was last active.

identity_location UNSIGNED BIGINT Location of the log stream identity


block.

8.2.3.71 SYSIQRLVMERGEHISTORY System View

A log entry is added for each row-level versioning (RLV) enabled table each time a merge between the RLV
store and the IQ main store begins. Log entries are updated when the merge is complete.

Column Name Column Type Description

merge_id UNSIGNED BIGINT Unique log entry identifier

table_id UNSIGNED INT Foreign key to the sys.systable


system table

SAP IQ SQL Reference


System Tables and Views INTERNAL 1047
Column Name Column Type Description

start_time TIMESTAMP Time the merge started

end_time TIMESTAMP Time the merge ended

status CHAR(9) Values:

● STARTED
● COMPLETED
● FAILED

return_code TINYINT SQL code of the merge once completed

merge_type CHAR(9) The cause of the merge trigger:

● AUTOMATIC
● DML
● DDL
● SHUTDOWN
● USER

merge_mode CHAR(12) Values:

● BLOCKING
● NON-BLOCKING

merge_detail VARCHAR(255) Additional information, if provided,


such as error information

rows_inserted UNSIGNED BIGINT Number of rows that were inserted as a


result of the merge

rows_updated UNSIGNED BIGINT Number of rows that were updated as a


result of the merge

rows_deleted UNSIGNED BIGINT Number of rows that were deleted as a


result of the merge

rows_forwarded UNSIGNED BIGINT Number of rows that were uncommit­


ted at the time of the merge

8.2.3.72 SYSIQTAB System View

Presents group information from ISYSIQTAB in a readable format. Each row in the SYSIQTAB view describes
an IQ table.

ALTER VIEW "SYS"."SYSIQTAB"


as select * from SYS.ISYSIQTAB

 Note

This view replaces the deprecated system view SYSIQTABLE.

SAP IQ SQL Reference


1048 INTERNAL System Tables and Views
Column Name Column Type Description

table_id UNSIGNED INT Each table is assigned a unique number


(the table number) that is the primary
key.

block_map HS_BLOCKMAPIDENTITY For internal use.

block_map_size UNSIGNED INT For internal use.

vdo HS_VDOIDENTITY For internal use.

vdoid_size UNSIGNED INT For internal use.

info_location hs_vdorecid Not used. Always zero.

info_recid_size UNSIGNED INT Not used. Always zero.

info_location_size UNSIGNED INT Not used. Always zero.

commit_txn_id UNSIGNED BIGINT For internal use.

txn_id UNSIGNED BIGINT For internal use.

update_time TIMESTAMP Last date and time the IQ table was


modified.

is_rlv CHAR(1) Values:

● 'T' – RLV storage is enabled on the


table
● 'F' – RLV storage is not enabled on
the table

affinity_map LONG BINARY Affinity map ID.

affinity_map_size UNSIGNED INT Size of the affinity map.

Constraints on Underlying System Table

Primary key (table_id)

Related Information

SYSIQTABLE System View (Deprecated) [page 1051]

SAP IQ SQL Reference


System Tables and Views INTERNAL 1049
8.2.3.73 SYSIQTABCOL System View

Presents group information from ISYSIQTABCOL in a readable format. Each row in the SYSIQTABCOL view
describes a column in an IQ table.

 Note

This view replaces the deprecated system view SYSIQCOLUMN.

Column Name Column Type Description

link_table_id UNSIGNED INT For internal use.

link_column_id UNSIGNED INT For internal use.

max_length UNSIGNED INT Indicates the maximum length allowed by the column.

approx_unique_count ROWID Approximate number of unique values (cardinality) of this


column.

cardinality ROWID The actual number of unique values (cardinality) of this col­
umn.

has_data CHAR(1) Indicates that the column contains data (T/F).

is_nbit CHAR(1) Indicates whether the column is NBit (T) or Flat FP (F).

Remarks

ALTER VIEW "SYS"."SYSIQTABCOL"


as select * from SYS.ISYSIQTABCOL

Constraints on Underlying System Table

Primary key (table_id)

Related Information

SYSIQCOLUMN System View (Deprecated) [page 1036]

SAP IQ SQL Reference


1050 INTERNAL System Tables and Views
8.2.3.74 SYSIQTABLE System View (Deprecated)

SYSIQTABLE has been replaced by the SYSIQTAB system view.

Related Information

SYSIQTAB System View [page 1048]

8.2.3.75 SYSIQVINDEX ASE Compatibility View

sysiqvindex provides one row for each non-FP IQ index.

This view is owned by user DBO.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.76 SYSIXCOL compatibility view (deprecated)

Each row of the SYSIXCOL describes a column in an index, and is provided for compatibility with older versions
of the software that offered a SYSIXCOL system table.

The SYSIXCOL system table has been replaced by the ISYSIDXCOL system table, and its corresponding
SYSIDXCOL system view. You should switch to using the SYSIDXCOL system view.

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,

SAP IQ SQL Reference


System Tables and Views INTERNAL 1051
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

8.2.3.77 SYSJAR system view

Each row in the SYSJAR system view defines a JAR file stored in the database. The underlying system table for
this view is ISYSJAR.

Column name Data type Description

jar_id INTEGER A unique number identifying the JAR


file.

object_id UNSIGNED BIGINT The internal ID for the JAR file, uniquely
identifying it in the database.

creator UNSIGNED INT The user number of the creator of the


JAR file. Can be set by the AS USER
clause of the INSTALL JAVA statement.

jar_name LONG VARCHAR The name of the JAR file.

jar_file LONG VARCHAR This column is no longer used and con­


tains NULL.

update_time TIMESTAMP The local time the JAR file was last up­
dated.

update_time_utc TIMESTAMP WITH TIME ZONE The UTC time the JAR file was last up­
dated.

8.2.3.78 SYSJARCOMPONENT system view

Each row in the SYSJARCOMPONENT system view defines a JAR file component, which includes class files,
manifest files, and any other JAR resource. The underlying system table for this view is ISYSJARCOMPONENT.

Column name Data type Description

component_id INTEGER The primary key containing the id of the


component.

jar_id INTEGER If the row describes a JAR, the value is


the ID number of the JAR. Otherwise,
the value is NULL.

component_name LONG VARCHAR The name of the component.

component_type CHAR(1) This column is no longer used and con­


tains NULL.

contents LONG BINARY The byte code of the JAR file.

SAP IQ SQL Reference


1052 INTERNAL System Tables and Views
8.2.3.79 SYSJAVACLASS system view

Each row in the SYSJAVACLASS system view describes one Java class stored in the database. The underlying
system table for this view is ISYSJAVACLASS.

Column name Data type Description

class_id INTEGER The unique number for the Java class.


Also the primary key for the table.

object_id UNSIGNED BIGINT The internal ID for the Java class,


uniquely identifying it in the database.

creator UNSIGNED INT The user number of the creator of the


class. Can be set by the AS USER
clause of the INSTALL JAVA statement.

jar_id INTEGER The id of the JAR file from which the


class came.

class_name LONG VARCHAR The name of the Java class.

public CHAR(1) Indicates whether the class is public (Y)


or private (N).

component_id INTEGER The id of the component in the SYSJAR­


COMPONENT system view.

update_time TIMESTAMP The local last update time of the class.

update_time_utc TIMESTAMP WITH TIME ZONE The UTC last update time of the class.

8.2.3.80 SYSLDAPSERVER System View

Presents information on the ISYSLDAPSERVER system table in a readable format.

The ISYSLDAPSERVER system table defines a set of attributes for the LDAP server.

Column Name Column Type Description

ldsrv_id UNSIGNED BIGINT NOT NULL A unique identifier for the LDAP server that is
the primary key and is used by the login policy
to refer to the LDAP server.

ldsrv_name CHAR(128) NOT NULL The name assigned to the LDAP server.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1053
Column Name Column Type Description

ldsrv_state CHAR(9) NOT NULL Read-only state of the LDAP server:

● 1 – RESET
● 2 – READY
● 3 – ACTIVE
● 4 – FAILED
● 5 – SUSPENDED

 Note
A numeric value is stored in system table; a
corresponding text value appears in the
system view.

ldsrv_start_tls TINYINT NOT NULL Controls whether Transport Layer Security


(TLS) is used to connect to the LDAP server.
This provides encrypted communication for
connections and searches with the LDAP
server in conjunction with TRUSTED_CERTIF­
CATE_FILE.

Valid range:

● 1 – ON
● 0 – OFF (default)

ldsrv_num_retries TINYINT NOT NULL Controls the number of authenticate attempts


allowed with the LDAP server before returning
a failure or initiating a failover (if specified).

Valid range: 1–60

Default value: 3

ldsrv_timeout UNSIGNED INT NOT NULL Controls the timeout value (in milliseconds) for
connections or searches.

Valid range: 1–3600000 (1 hour)

Default value: 10000

ldsrv_last_state_change TIMESTAMP NOT NULL Indicates the time the last state change occur­
red. The value is stored in Coordinated Univer­
sal Time (UTC), regardless of the local time
zone of the LDAP server.

ldsrv_search_url CHAR(1024) NULL The LDAP URL to be used to find the Distin­
guished Name (DN) for a user based on their
user ID.

ldsrv_auth_url CHAR(1024) NULL The LDAP search string to be used to find the
DN for a user given their user ID.

ldsrv_access_dn CHAR(1024) NULL The DN used to access the LDAP server for
searches to obtain the DN for a user ID.

SAP IQ SQL Reference


1054 INTERNAL System Tables and Views
Column Name Column Type Description

ldsrv_access_dn_pwd VARBINARY(1024) NULL The password for the access account. The
password is symmetrically encrypted when
stored on disk.

8.2.3.81 SYSLOGINMAP system view

The SYSLOGINMAP system view contains one row for each user that can connect to the database using either
an integrated login, or Kerberos login. For that reason, access to this view is restricted. The underlying system
table for this view is ISYSLOGINMAP.

Column name Data type Description

login_mode TINYINT The type of login: 1 for integrated logins,


2 for Kerberos logins.

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 map­


ping between user ID and database
user ID.

database_uid UNSIGNED INT The database user ID to which the login


ID is mapped.

8.2.3.82 SYSLOGINPOLICY system view

The underlying system table for this view is ISYSLOGINPOLICY.

Column name Data type Description

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

login_policy_name CHAR(128) The name of the login policy.

8.2.3.83 SYSLOGINPOLICYOPTION system view

The underlying system table for this view is ISYSLOGINPOLICYOPTION.

Column name Data type Description

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

login_option_name CHAR(128) The name of the login policy.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1055
Column name Data type Description

login_option_value LONG VARCHAR The value of the login policy at the time
it was created.

8.2.3.84 SYSLOGINS ASE Compatibility View

This view is owned by user DBO. SYSLOGINS contains one row for each valid SAP Adaptive Server Enterprise
user account.

8.2.3.85 SYSMUTEXSEMAPHORE system view

Each row in the SYSMUTEXSEMAPHORE system view provides information about a user-defined mutex or
semaphore in the database. The underlying system table for this view is ISYSMUTEXSEMAPHORE.

You must have the SELECT ANY TABLE privilege to access this view.

Column Data type Description

mutex_semaphore_id UNSIGNED INT A unique ID for the mutex or sema­


phore.

object_id UNSIGNED INT The object ID of the mutex or sema­


phore in the ISYSOBJECT system table.

owner UNSIGNED INT The owner of the mutex or semaphore.

name CHAR(128) The name of the mutex or semaphore.

obj_type CHAR(9) The type of object: either MUTEX or


SEMAPHORE.

scope CHAR(11) The scope for the mutex or semaphore.


For mutexes, CONNECTION indicates a
connection-level scope, and TRANSAC­
TION indicates a transaction-level
scope. For semaphores, this value is al­
ways CONNECTION.

start_with UNSIGNED INT The initial counter value for a sema­


phore. This value is NULL for mutexes.

SAP IQ SQL Reference


1056 INTERNAL System Tables and Views
8.2.3.86 SYSMVOPTION system view

Each row in the SYSMVOPTION system view describes the setting of one option value for a materialized view or
text index at the time of its creation. The name of the option can be found in the SYSMVOPTIONNAME system
view. The underlying system table for this view is ISYSMVOPTION.

Column name Data type Description

view_object_id UNSIGNED BIGINT The object ID of the materialized view.

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 VARCHAR The value of the option when the mate­
rialized view was created.

8.2.3.87 SYSMVOPTIONNAME system view

Each row in the SYSMVOPTION system view gives the name option value for a materialized view or text index at
the time of its creation. The value for the option can be found in the SYSMVOPTION system view. The
underlying system table for this view is ISYSMVOPTIONNAME.

Column name Data type Description

option_id UNSIGNED INT A number uniquely identifying the op­


tion in the database.

option_name CHAR(128) The name of the option.

8.2.3.88 SYSOBJECT system view

Each row in the SYSOBJECT system view describes a database object. The underlying system table for this
view is ISYSOBJECT.

Column name Data type Description

object_id UNSIGNED BIGINT The internal ID for the object, uniquely


identifying it in the database.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1057
Column name Data type Description

status TINYINT The status of the object. Values include:

1 (valid)

The object is available for use by


the database server. This status is
synonymous with ENABLED. That
is, if you ENABLE an object, the
status changes to VALID.
2 (invalid)

An attempt to recompile the object


after an internal operation has
failed, for example, after a schema-
altering modification to an object
on which it depends. The database
server continues to try to recom­
pile the object whenever it is refer­
enced in a statement.
4 (disabled)

The object has been explicitly disa­


bled by the user, for example using
an ALTER TABLE...DISABLE VIEW
DEPENDENCIES statement.

object_type TINYINT Type of object.

creation_time TIMESTAMP The local date and time when the object
was created.

object_type_str CHAR (128) Type of object.

creation_time_utc TIMESTAMP WITH TIME ZONE The UTC date and time when the object
was created.

8.2.3.89 SYSOBJECTS ASE Compatibility View

sysobjects contains one row for each table, view, stored procedure, extended stored procedure, log, rule,
default, trigger, check constraint, referential constraint, computed column, function-based index key, and
temporary object, and other forms of compiled objects.

This view is owned by user DBO.

It also contains one row for each partition condition ID when object type is N.

Related Information

Tables in Each SAP ASE Database [page 1114]

SAP IQ SQL Reference


1058 INTERNAL System Tables and Views
SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.90 SYSOPTION system view

The SYSOPTION system view contains the options one row for each option setting stored in the database.

Each user can have their own setting for a given option. In addition, settings for the PUBLIC role define the
default settings to be used for users that do not have their own setting. The underlying system table for this
view is ISYSOPTION.

Column name Data type Description

user_id UNSIGNED INT The user number to whom the option


setting applies.

"option" CHAR(128) The name of the option.

"setting" LONG VARCHAR The current setting for the option.

8.2.3.91 SYSOPTIONS consolidated view

Each row in the SYSOPTIONS view describes one option created using the SET command. Each user can have
their own setting for each option. In addition, settings for the PUBLIC user define the default settings to be
used for users that do not have their own setting.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSOPTIONS"( user_name,"option",setting )


as select u.user_name,opt."option",opt.setting
from SYS.ISYSOPTION as opt
join SYS.ISYSUSER as u on opt.user_id = u.user_id

SAP IQ SQL Reference


System Tables and Views INTERNAL 1059
8.2.3.92 SYSOPTSTAT system view

The SYSOPTSTAT system view stores the cost model calibration information as computed by the ALTER
DATABASE CALIBRATE statement. The contents of this view are for internal use only and are best accessed via
the sa_get_dtt system procedure. The underlying system table for this view is ISYSOPTSTAT.

Column name Data type Description

stat_id UNSIGNED INT For system use only.

group_id UNSIGNED INT For system use only.

format_id SMALLINT For system use only.

data LONG BINARY For system use only.

8.2.3.93 SYSPARTITION System View

Presents group information from ISYSPARTITION in a readable format.

Column Name Column Type Description

partitioned_object_id UNSIGNED BIGINT Unique number assigned to each partitioned object (table).

partition_id UNSIGNED INT Identifies a partition in a partitioned table.

partition_object_id UNSIGNED BIGINT Each table partition is an object itself and is assigned a
unique number from the table object or index object.

partition_values LONG VARCHAR Contains partitioning criteria for range or list partitioning:

● For range partitioning, values contain the upper bound


for this partition.
● For list partitioning, values contain list of values sepa­
rated by ','. Position is the ordinal number of partition.

position UNSIGNED INT Ordinal number of partition. For ranged partition, for position
2 and above, the partition at (position-1) contains its exclu­
sive lower bound.

partition_name CHAR(128) Name of partition.

Remarks

Each row in the SYSPARTITION view describes a partitioned object (table or index) in the database. The
underlying system table for this view is ISYSPARTITION.

Constraints on Underlying System Table

Primary key (partitioned_object_id, partition_id)

SAP IQ SQL Reference


1060 INTERNAL System Tables and Views
Unique (partition_object_id, position)

Foreign key (partition_object_id) references SYS.ISYSOBJECT

Foreign key (partitioned_object_id) references SYS.ISYSOBJECT

8.2.3.94 SYSPARTITIONKEY System View

Presents group information from ISYSPARTITIONKEY in a readable format.

Column Name Column Type Description

partitioned_object_id UNSIGNED BIGINT Each partitioned object (table) is assigned a unique object
number.

column_id UNSIGNED INT The column ID identifies the table column as part of the par­
titioning key.

position SMALLINT Position of this column in the partitioning key. Position is 0


based. A position of 0 indicates the 1st column in the parti­
tioning key.

Remarks

Each row in the SYSPARTITIONKEY view describes a partitioned object (table or index) in the database.

ALTER VIEW "SYS"."SYSPARTITIONKEY"


as select * from SYS.ISYSPARTITIONKEY

Constraints on Underlying System Table

Primary key (partitioned_object_id, column_id)

Foreign key (partitioned_object_id) references SYS.ISYSOBJECT

SAP IQ SQL Reference


System Tables and Views INTERNAL 1061
8.2.3.95 SYSPARTITIONS System View

Presents group information from the ISYSPARTITIONS system table in a readable format

Column Name Data Type Description

table_id UNSIGNED INT The object ID of the table to which the index corresponds.

partition_id UNSIGNED INT Identifies a partition in a partitioned table.

partition_object_id UNSIGNED BIGINT Each table partition is an object itself and is assigned a
unique number from the table object or index object.

partition_dbspace_id SMALLINT Object ID of the dbspace where the partition is located.

partition_values LONG VARCHAR Contains the upper bound for this range partition.

position UNSIGNED INT Ordinal number of partition.

partition_name CHAR(128) Name of partition

Remarks

Each row in the SYSPARTITIONS view describes a partitioned object (table or index) in the database. The
underlying system table for this view is ISYSPARTITIONS.

ALTER VIEW "SYS"."SYSPARTITIONS"


as select * from SYS.ISYSPARTITIONS

Constraints on Underlying System Table

primary key (partitioned_object_id, partition_id)

foreign key (partitioned_object_id) references SYS.ISYSOBJECT

foreign key (partition_object_id) references SYS.ISYSOBJECT

8.2.3.96 SYSPARTITIONSCHEME System View

Presents group information from ISYSPARTITIONSCHEME in a readable format.

Column Name Column Type Description

partitioned_object_id UNSIGNED BIGINT Each partitioned object (table) is assigned a unique number.

SAP IQ SQL Reference


1062 INTERNAL System Tables and Views
Column Name Column Type Description

partition_method TINYINT Partitioning method for this table. Valid values:

● 1 – for range
● 3 – for hash (2 is unused)

subpartition_method TINYINT Subpartitioning method for this table. Valid values:

● NULL - no subpartitioning
● 1 – for range partitioning
● 3 – for hash partitioning (2 is unused)

Remarks

Each row in the SYSPARTITIONSCHEME view describes a partitioned object (table or index) in the database.

ALTER VIEW "SYS"."SYSPARTITIONSCHEME"


as select * from SYS.ISYSPARTITIONSCHEME

Constraints on Underlying System Table

Primary key (partitioned_object_id)

Foreign key (partitioned_object_id) references SYS.ISYSOBJECT

8.2.3.97 SYSPHYSIDX system view

Each row in the SYSPHYSIDX system view defines a physical index in the database. The underlying system
table for this view is ISYSPHYSIDX.

Column name Data type Description

table_id UNSIGNED INT The object ID of the table to which the


index corresponds.

phys_index_id UNSIGNED INT The unique number of the physical in­


dex within its table.

root INTEGER Identifies the location of the root page


of the physical index in the database
file.

key_value_count UNSIGNED INT The number of distinct key values in the


index.

leaf_page_count UNSIGNED INT The number of leaf index pages.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1063
Column name Data type Description

depth UNSIGNED SMALLINT The depth (number of levels) of the


physical index.

max_key_distance UNSIGNED INT For system use only.

seq_transitions UNSIGNED INT For system use only.

rand_transitions UNSIGNED INT For system use only.

rand_distance UNSIGNED INT For system use only.

allocation_bitmap LONG VARBIT For system use only.

long_value_bitmap LONG VARBIT For system use only.

8.2.3.98 SYSPROCAUTH consolidated view

Each row in the SYSPROCAUTH view describes a set of privileges granted on a procedure. As an alternative,
you can also use the SYSPROCPERM system view.

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

8.2.3.99 SYSPROCEDURE system view

Each row in the SYSPROCEDURE system view describes one procedure in the database. The underlying system
table for this view is ISYSPROCEDURE.

Column name Data type Description

proc_id UNSIGNED INT The internal procedure number for the


procedure, uniquely identifying it in the
database.

creator UNSIGNED INT The owner of the procedure.

object_id UNSIGNED BIGINT The internal ID for the procedure,


uniquely identifying it in the database.

proc_name CHAR(128) The name of the procedure. One crea­


tor cannot have two procedures with
the same name.

SAP IQ SQL Reference


1064 INTERNAL System Tables and Views
Column name Data type Description

proc_defn LONG VARCHAR The definition of the procedure after it


has been parsed and unparsed by the
database server

remarks LONG VARCHAR Remarks about the procedure. This


value is stored in the ISYSREMARK sys­
tem table.

replicate CHAR(1) Internal use only.

srvid UNSIGNED INT If the procedure is a proxy for a proce­


dure on a remote database server, then
this value indicates the remote server.

source LONG VARCHAR The preserved source for the proce­


dure. This value is stored in the ISYS­
SOURCE system table. Content is only
stored in this column when the pre­
serve_source_format option is set to
On.

avg_num_rows FLOAT Information collected for use in query


optimization when the procedure ap­
pears in the FROM clause.

avg_cost FLOAT Information collected for use in query


optimization when the procedure ap­
pears in the FROM clause.

stats LONG BINARY Information collected for use in query


optimization when the procedure ap­
pears in the FROM clause.

dialect CHAR(1) Returns W for Watcom SQL procedures


and functions, and T for Transact SQL
procedures and functions.

is_deterministic CHAR(1) Returns NULL for procedures. Returns


Y if a function is marked as determinis­
tic, N if it is marked as not determinis­
tic, and U if it is not marked either way.

is_external CHAR(1) Returns Y if the function is external and


N if it is not.

external_language VARCHAR(128) Returns NULL if the procedure is not


external and 'native' if the procedure
uses the original interface. Otherwise, it
contains the language of the procedure.

external_name VARCHAR(32767) Returns NULL if the procedure is not


external. Otherwise, it contains the ex­
ternal name of the procedure.

sql_security CHAR(1) Returns I if the procedure is SQL SE­


CURITY INVOKER and D if the proce­
dure is SQL SECURITY DEFINER.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1065
8.2.3.100 SYSPROCPARM system view

Each row in the SYSPROCPARM system view describes one parameter, result set column, or return value of a
procedure or function in the database. The underlying system table for this view is ISYSPROCPARM.

Column name Data type Description

proc_id UNSIGNED INT Uniquely identifies the procedure or


function to which the parameter be­
longs.

parm_id SMALLINT Each procedure starts numbering pa­


rameters at 1. The order of parameter
numbers corresponds to the order in
which they were defined. For functions,
the first parameter has the name of the
function and represents the return
value for the function.

parm_type SMALLINT The type of parameter is one of the fol­


lowing:

Normal parameter (variable)


1

Result column - used with a proce­


dure that returns result sets
2

SQLSTATE error value


3

SQLCODE error value


4

Return value from function

parm_mode_in CHAR(1) Indicates whether the parameter sup­


plies a value to the procedure or func­
tion (IN or INOUT parameters).

parm_mode_out CHAR(1) Indicates whether the parameter re­


turns a value from the procedure or
function (OUT or INOUT parameters) or
columns in the RESULT clause.

domain_id SMALLINT Identifies the data type for the parame­


ter, by the data type number listed in
the SYSDOMAIN system view.

width BIGINT Contains the length of a string parame­


ter, the precision of a numeric parame­
ter, or the number of bytes of storage
for any other data type.

SAP IQ SQL Reference


1066 INTERNAL System Tables and Views
Column name Data type Description

scale SMALLINT For numeric data types, the number of


digits after the decimal point. For all
other data types, the value of this col­
umn is 1.

user_type SMALLINT The user type of the parameter, if appli­


cable.

parm_name CHAR(128) The name of the parameter.

"default" LONG VARCHAR Default value of the parameter. Pro­


vided for informational purposes only.

remarks LONG VARCHAR Always returns NULL. Provided to allow


the use of previous versions of ODBC
drivers with newer personal database
servers.

base_type_str VARCHAR(32767) The annotated type string representing


the physical type of the parameter.

Remarks

The SYSPROCPARM system view is updated when a procedure or function is created or altered, including using
the ALTER PROCEDURE...RECOMPILE statement.

Additionally, SYSPROCPARM is updated whenever a checkpoint is run if the out-of-date procedure or function
meets the following conditions:

● The procedure or function has been referenced since it was altered.


● The procedure either has a RESULT clause or is not a recursive procedure with calls nested ten deep to
other procedures that do not have RESULT clauses.

8.2.3.101 SYSPROCPARMS consolidated view

Each row in the SYSPROCPARMS view describes a parameter to a procedure in the database.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSPROCPARMS"( creator,


procname,parmname,parm_id,parmtype,parmmode,parmdomain,
length,scale,"default",user_type )
as select up.user_name,p.proc_name,pp.parm_name,pp.parm_id,pp.parm_type,
if pp.parm_mode_in = 'Y' and pp.parm_mode_out = 'N' then 'IN'
else if pp.parm_mode_in = 'N' and pp.parm_mode_out = 'Y' then 'OUT'
else 'INOUT'
endif
endif,dom.domain_name,pp.width,pp.scale,pp."default",ut.type_name
from SYS.SYSPROCPARM as pp
join SYS.ISYSPROCEDURE as p on p.proc_id = pp.proc_id
join SYS.ISYSUSER as up on up.user_id = p.creator

SAP IQ SQL Reference


System Tables and Views INTERNAL 1067
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

8.2.3.102 SYSPROCPERM system view

Each row of the SYSPROCPERM system view describes a user who has been granted EXECUTE privilege on a
procedure. The underlying system table for this view is ISYSPROCPERM.

Column name Data type Description

proc_id UNSIGNED INT The procedure number uniquely identi­


fies the procedure for which EXECUTE
privilege has been granted.

grantee UNSIGNED INT The user number of the privilege


grantee.

8.2.3.103 SYSPROCS consolidated view

The SYSPROCS view shows the procedure or function name, the name of its creator and any comments
recorded for the procedure or function.

The tables and columns that make up this view are provided in the ALTER VIEW statement below.

ALTER VIEW "SYS"."SYSPROCS"( creator,


procname,remarks )
as select u.user_name,p.proc_name,r.remarks
from SYS.ISYSPROCEDURE as p
join SYS.ISYSUSER as u on u.user_id = p.creator
left outer join SYS.ISYSREMARK as r on(p.object_id = r.object_id)

8.2.3.104 SYSPROXYTAB system view

Each row of the SYSPROXYTAB system view describes the remote parameters of one proxy table. The
underlying system table for this view is ISYSPROXYTAB.

Column name Data type Description

table_object_id UNSIGNED BIGINT The object ID of the proxy table.

existing_obj CHAR(1) Indicates whether the proxy table previ­


ously existed on the remote server.

srvid UNSIGNED INT The unique ID for the remote server as­
sociated with the proxy table.

remote_location LONG VARCHAR The location of the proxy table on the


remote server.

SAP IQ SQL Reference


1068 INTERNAL System Tables and Views
Column name Data type Description

location_escape_char CHAR(1) The escape character that is used to es­


cape the location delimiter.

8.2.3.105 SYSPUBLICATION system view

Each row in the SYSPUBLICATION system view describes a publication. The underlying system table for this
view is ISYSPUBLICATION.

Column name Data type Description

publication_id UNSIGNED INT A number uniquely identifying the pub­


lication.

object_id UNSIGNED BIGINT The internal ID for the publication,


uniquely identifying it in the database.

creator UNSIGNED INT The owner of the publication.

publication_name CHAR(128) The name of the publication.

remarks LONG VARCHAR Remarks about the publication. This


value is stored in the ISYSREMARK sys­
tem table.

type CHAR(1) This column is deprecated.

sync_type UNSIGNED INT The type of synchronization for the


publication. Values include:

0 (logscan)

This is a regular publication that


uses the transaction log to upload
all relevant data that has changed
since the last upload.
1 (scripted upload)

For this publication, the transac­


tion log is ignored and the upload is
defined by the user using stored
procedures. Information about the
stored procedures is stored in the
ISYSSYNCSCRIPT system table.
2 (download only)

This is a download-only publica­


tion; no data is uploaded.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1069
8.2.3.106 SYSPUBLICATIONS consolidated view

Each row in the SYSPUBLICATIONS view describes a publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."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)

8.2.3.107 SYSREMARK system view

Each row in the SYSREMARK system view describes a remark (or comment) for an object. The underlying
system table for this view is ISYSREMARK.

Column Data type Description

object_id UNSIGNED BIGINT The internal ID for the object that has
an associated remark.

remarks LONG VARCHAR The remark or comment associated


with the object.

8.2.3.108 SYSREMOTEOPTION system view

Each row in the SYSREMOTEOPTION system view describes the value of a message link parameter. The
underlying system table for this view is ISYSREMOTEOPTION.

Some columns in this view contain potentially sensitive data. The SYSREMOTEOPTION2 view provides public
access to the data in this view except for the potentially sensitive columns.

Column Data type Description

option_id UNSIGNED INT An identification number for the mes­


sage link parameter.

user_id UNSIGNED INT The user ID for which the parameter is


set.

SAP IQ SQL Reference


1070 INTERNAL System Tables and Views
Column Data type Description

"setting" VARCHAR(255) The value of the message link parame­


ter.

8.2.3.109 SYSREMOTEOPTION2 consolidated view

Joins together, and presents in a more readable format, the columns from SYSREMOTEOPTION and
SYSREMOTEOPTIONTYPE system views.

Values in the setting column are hidden from users that do not have the SELECT ANY TABLE system privilege.

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

8.2.3.110 SYSREMOTEOPTIONS consolidated view

Each row of the SYSREMOTEOPTIONS view describes the values of a message link parameter.

Values in the setting column are hidden from users that do not have the SELECT ANY TABLE system privilege.
The SYSREMOTEOPTION2 view provides public access to the insensitive data.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSREMOTEOPTIONS"


as select srt.type_name,
sup.user_name,
srot."option",
SYS.HIDE_FROM_NON_DBA(sro.setting) as setting
from SYS.ISYSREMOTETYPE as srt
,SYS.ISYSREMOTEOPTIONTYPE as srot
,SYS.ISYSREMOTEOPTION as sro
,SYS.ISYSUSER as sup
where srt.type_id = srot.type_id
and srot.option_id = sro.option_id
and sro.user_id = sup.user_id

SAP IQ SQL Reference


System Tables and Views INTERNAL 1071
8.2.3.111 SYSREMOTEOPTIONTYPE system view

Each row in the SYSREMOTEOPTIONTYPE system view describes one of the message link parameters. The
underlying system table for this view is ISYSREMOTEOPTIONTYPE.

Column Data type Description

option_id UNSIGNED INT An identification number for the mes­


sage link parameter.

type_id SMALLINT An identification number for the mes­


sage type that uses the parameter.

option VARCHAR(128) The name of the message link parame­


ter.

Constraints on underlying system table

PRIMARY KEY (option_id)

FOREIGN KEY (type_id) REFERENCES SYS.ISYSREMOTETYPE (type_id)

8.2.3.112 SYSREMOTETYPE system view

The SYSREMOTETYPE system view contains information about remote tables. The underlying system table for
this view is ISYSREMOTETYPE.

Column name Data type Description

type_id SMALLINT Identifies which of the message sys­


tems is to be used to send messages to
the user.

object_id UNSIGNED BIGINT The internal ID for the remote type,


uniquely identifying it in the database.

type_name CHAR(128) The name of the message system.

publisher_address LONG VARCHAR The address of the remote database


publisher.

remarks LONG VARCHAR Remarks about the remote type. This


value is stored in the ISYSREMARK sys­
tem table.

SAP IQ SQL Reference


1072 INTERNAL System Tables and Views
8.2.3.113 SYSREMOTETYPES consolidated view

Each row of the SYSREMOTETYPES view describes one remote message type, including the publisher address.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSREMOTETYPES"


as select rt.type_id,rt.type_name,rt.publisher_address,rm.remarks
from SYS.ISYSREMOTETYPE as rt
left outer join SYS.ISYSREMARK as rm on(rt.object_id = rm.object_id)

8.2.3.114 SYSREMOTEUSER system view

Each row in the SYSREMOTEUSER system view describes a user ID with the REMOTE system privilege (a
subscriber), together with the status of messages that were sent to and from that user. The underlying system
table for this view is ISYSREMOTEUSER.

Column name Data type Description

user_id UNSIGNED INT The user number of the user with RE­
MOTE privilege.

consolidate CHAR(1) Indicates whether the user was granted


CONSOLIDATE privilege (Y) or REMOTE
privileges (N).

type_id SMALLINT Identifies which of the message sys­


tems is used to send messages to the
user.

address LONG VARCHAR The address to which messages are to


be sent. The address must be appropri­
ate for the address_type.

frequency CHAR(1) How frequently messages are sent.

send_time TIME The next time messages are to be sent


to this user.

log_send UNSIGNED BIGINT Messages are sent only to subscribers


for whom log_send is greater than
log_sent.

time_sent TIMESTAMP The local time the most recent message


was sent to this subscriber.

log_sent UNSIGNED BIGINT The log offset for the most recently sent
operation.

confirm_sent UNSIGNED BIGINT The log offset for the most recently
confirmed operation from this sub­
scriber.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1073
Column name Data type Description

send_count INTEGER How many messages have been sent.

resend_count INTEGER Counter to ensure that messages are


applied only once at the subscriber da­
tabase.

time_received TIMESTAMP The local time when the most recent


message was received from this sub­
scriber.

log_received UNSIGNED BIGINT The log offset in the database of the


subscriber for the operation that was
most recently received at the current
database.

confirm_received UNSIGNED BIGINT The log offset in the database of the


subscriber for the most recent opera­
tion for which a confirmation message
has been sent.

receive_count INTEGER How many messages have been re­


ceived.

rereceive_count INTEGER Counter to ensure that messages are


applied only once at the current data­
base.

time_sent_utc TIMESTAMP WITH TIME ZONE The UTC time the most recent message
was sent to this subscriber.

time_received_utc TIMESTAMP WITH TIME ZONE The UTC time when the most recent
message was received from this sub­
scriber.

8.2.3.115 SYSREMOTEUSERS consolidated view

Each row of the SYSREMOTEUSERS view describes a user ID with the REMOTE system privilege (a subscriber),
together with the status of messages that were sent to and from that user.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSREMOTEUSERS" AS SELECT u.user_name, r.consolidate,


t.type_name, r.address, r.frequency, r.send_time,
(if r.frequency = 'A' then NULL
else if r.frequency = 'P' then
if r.time_sent IS NULL then CURRENT TIMESTAMP
else (select min( minutes( dateadd(mi, PROPERTY('TimeZoneAdjustment'),
a.time_sent),
60*hour(a.send_time) + minute( seconds( a.send_time, 59 ) ) ) )
FROM SYS.ISYSREMOTEUSER a WHERE a.frequency = 'P' AND a.send_time =
r.send_time ) endif
else if CURRENT DATE + r.send_time > coalesce( dateadd(mi,
PROPERTY('TimeZoneAdjustment'), 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 ,

SAP IQ SQL Reference


1074 INTERNAL System Tables and Views
dateadd(mi, PROPERTY('TimeZoneAdjustment'), r.time_sent)
as time_sent , r.log_sent, r.confirm_sent, r.send_count, r.resend_count,
dateadd(mi, PROPERTY('TimeZoneAdjustment'), r.time_received) as time_received ,
r.log_received, r.confirm_received, r.receive_count, r.rereceive_count ,
TODATETIMEOFFSET( r.time_sent, 0 ) as time_sent_utc ,
TODATETIMEOFFSET( r.time_received, 0 ) as time_received_utc
FROM SYS.ISYSREMOTEUSER r JOIN SYS.ISYSUSER u ON ( u.user_id = r.user_id ) JOIN
SYS.ISYSREMOTETYPE t ON ( t.type_id = r.type_id )

8.2.3.116 SYSROLEGRANT System View

The SYSROLEGRANT system view contains one row for each grant of a system or user defined role. The
underlying system table for this view is ISYSROLEGRANT.

Column Name Data Type Description

grant_id UNSIGNED INT ID used to identify each GRANT statement.

role_id UNSIGNED INT ID of the role being granted, as per ISYSUSER.

grantee UNSIGNED INT ID of the user being granted the role, as per ISYSUSER.

grant_type TINYINT Describes type of grant using three digits. The first digit is
whether privilege has been granted. The second digit is
whether administration rights have been given. The third
digit is whether system privileges are inheritable.

● 001 – privilege granted, with no inheritance, and no ad­


ministration rights. Applicable only for legacy non-inher­
itable authorities except SYS_AUTH_DBA_ROLE and
SYS_AUTH_REMOVE_DBA_ROLE.
● 101 – privilege granted, with inheritance, but no admin­
istration rights.
● 110 – only administration rights have been granted.
● 111 – privilege granted, with inheritance, and with ad­
ministration rights
● 001 – privilege granted, with administration rights, but
no inheritance. Applicable only for legacy authorities
SYS_AUTH_DBA_ROLE and SYS_AUTH_RE­
MOVE_DBA_ROLE.

grant_scope TINYINT Used by SET USER and CHANGE PASSWORD to set the
scope of the grant. Values can be one or more of the follow­
ing:

● 001 – user list.


● 101 – ANY WITH ROLES.
● 110 – ANY.

grantor CHAR (128) The unique identifier of the grantor of the role.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1075
Constraints on Underlying System Table

PRIMARY KEY (grant_ID)

UNIQUE Index (role_id, grantee, grant_scope)

8.2.3.117 SYSROLEGRANTEXT System View

The SYSROLEGRANTEXT system view contains syntax extensions pertaining to the SET USER and CHANGE
PASSWORD system privilege and is related to the SYSROLEGRANT system view.

Column Name Data Type Description

grant_id UNSIGNED INT ID used to identify each GRANT statement.

user_id UNSIGNED INT The user_ids specified in user-list or role-list in a


particular extended grant.

Remarks

When you grant or revoke the SET USER or CHANGE PASSWORD privilege, either with the user-list option or
with ANY WITH ROLES role-list option, this view is updated with the values from the extended syntax.

Constraints on Underlying System Table

PRIMARY KEY (grant_id, user_id)

8.2.3.118 SYSROLEGRANTS System View

The SYSROLEGRANTS system view is the same as the SYSROLEGRANT system view but includes two
additional columns: the name of the role (not just the role ID) and the name of the grantee (not just user ID).

Column name Data type Description

grant_id UNSIGNED INT A unique identifier for each grant statement issued.

role_id UNSIGNED INT The unique identifier for the role granted to a user (as defined in the
ISYSUSER table).

role_name CHAR(128) The name of the role corresponding to the role_id value.

SAP IQ SQL Reference


1076 INTERNAL System Tables and Views
Column name Data type Description

grantee UNSIGNED INT The unique identifier for the user granted the role.

grantee_name CHAR(128) The name of the grantee corresponding to the grantee value.

grant_type TINYINT Identifies how the role and its underlying privileges were granted. Val­
ues:

● 1 – Underlying privileges are granted with no administrative rights


and no privilege inheritance.

 Note
This value is applicable to all legacy, non-inheritable roles ex­
cept SYS_AUTH_DBA_ROLE and SYS_AUTH_RE­
MOVE_DBA_ROLE.

● 3 – Underlying privileges are granted with administrative rights,


but with no privilege inheritance.

 Note
This value is applicable only to the legacy, non-inheritable
roles SYS_AUTH_DBA_ROLE and SYS_AUTH_RE­
MOVE_DBA_ROLE.

● 5 – Underlying privileges are granted with no administrative


rights, but with privilege inheritance.
● 6 – Only administrative rights to the underlying privileges are
granted.
● 7 – Underlying privileges are granted with administrative rights
and privilege inheritance.

grant_scope TINYINT Defines the range to which the grant applies. Values include:

● 1 – User list
● 2 – Any users granted membership in the specified roles
● 3 – All users

 Note
This value is applicable to the SET USER and CHANGE PASS­
WORD system privileges only and can store any valid combination
of these values.

grantor CHAR (128) The unique identifier of the grantor of the role.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1077
8.2.3.119 SYSSCHEDULE system view

Each row in the SYSSCHEDULE system view describes a time at which an event is to fire, as specified by the
SCHEDULE clause of CREATE EVENT. The underlying system table for this view is ISYSSCHEDULE.

Column name Data type Description

event_id UNSIGNED INT The unique number assigned to each


event.

sched_name VARCHAR(128) The name associated with the schedule


for the event.

recurring TINYINT Indicates if the schedule is repeating.

start_time TIME The schedule start time.

stop_time TIME The schedule stop time if BETWEEN


was used.

start_date DATE The first date on which the event is


scheduled to execute.

days_of_week TINYINT A bit mask indicating the days of the


week on which the event is scheduled:

● x01 = Sunday
● x02 = Monday
● x04 = Tuesday
● x08 = Wednesday
● x10 = Thursday
● x20 = Friday
● x40 = Saturday

days_of_month UNSIGNED INT A bit mask indicating the days of the


month on which the event is scheduled.
Some examples include:

● x01 = first day


● x02 = second day
● x40000000 = 31st day
● x80000000 = last day of month

interval_units CHAR(10) The interval unit specified by EVERY:

● HH = hours
● NN = minutes
● SS = seconds

interval_amt INTEGER The period specified by EVERY.

SAP IQ SQL Reference


1078 INTERNAL System Tables and Views
8.2.3.120 SYSSERVER system view

Each row in the SYSSERVER system view describes a remote server. The underlying system table for this view
is ISYSSERVER.

 Note

Previous versions of the catalog contained a SYSSERVERS system table. That table has been renamed to
be ISYSSERVER (without an 'S'), and is the underlying table for this view.

Column name Data type Description

srvid UNSIGNED INT An identifier for the remote server.

srvname VARCHAR(128) The name of the remote server.

srvclass LONG VARCHAR The server class, as specified in the


CREATE SERVER statement.

srvinfo LONG VARCHAR Server information.

srvreadonly CHAR(1) Whether the server is read-only.

8.2.3.121 SYSSOURCE system view

Each row in the SYSSOURCE system view contains the source code, if applicable, for an object listed in the
SYSOBJECT system view. The underlying system table for this view is ISYSSOURCE.

Column name Data type Description

object_id UNSIGNED BIGINT The internal ID for the object whose


source code is being defined.

source LONG VARCHAR This column contains the original


source code for the object if the pre­
serve_source_format database option
is On when the object was created.

8.2.3.122 SYSSPATIALREFERENCESYSTEM System View

Each row of the SYSSPATIALREFERENCESYSTEM system view describes an SRS defined in the database. The
underlying system table for this view is ISYSSPATIALREFERENCESYSTEM.

Column Name Data Type Description

object_id UNSIGNED BIGINT For system use only.

owner UNSIGNED INT The owner of the SRS.

srs_name CHAR(128) The name of the SRS.

srs_id INTEGER The numeric identifier (SRID) for the spatial reference system.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1079
Column Name Data Type Description

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 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 order is long/lat/z/m; lat/long/z/m is also sup­
ported.

snap_to_grid DOUBLE Defines the size of the grid used when performing calculations.

tolerance DOUBLE Defines the precision to use when comparing points.

semi_major_axis DOUBLE Distance from center of the ellipsoid to the equator for a ROUND
EARTH SRS.

semi_minor_axis DOUBLE Distance from center of the ellipsoid to the poles for a ROUND
EARTH SRS.

inv_flattening The inverse flattening used for the ellipsoid in a ROUND EARTH
SRS.

Inverse flattening (f) is a mathematical value that defines the de­


gree of squashing of the pole of a spheroid towards its equator. The
value ranges from no flattening (a perfect circle) to complete flat-
tening (a straight line). Inverse flattening is the value of 1/f, as fol­
lows: 1/f = (semi_major_axis) /
(semi_major_axis - semi_minor_axis)

min_x DOUBLE The minimum x value allowed in coordinates.

max_x DOUBLE The maximum x value allowed in coordinates.

min_y DOUBLE The minimum y value allowed in coordinates.

max_y DOUBLE The maximum y value allowed in coordinates.

min_z DOUBLE The minimum z value allowed in coordinates.

max_z DOUBLE The maximum z value allowed in coordinates.

min_m DOUBLE The minimum m value allowed in coordinates.

max_m DOUBLE The maximum m value allowed in coordinates.

organization LONG VARCHAR The name of the organization that created the coordinate system
used by the spatial reference system.

organization_coordsys_id INTEGER The ID given to the coordinate system by the organization that cre­
ated it.

SAP IQ SQL Reference


1080 INTERNAL System Tables and Views
Column Name Data Type Description

srs_type CHAR(11) The type of SRS as defined by the SQL/MM standard. Values can
be one of:

● GEOGRAPHIC – This is for SRSs based on georeferenced coor­


dinate systems with axes of latitude, longitude (and elevation).
These SRSs are of type PLANAR or ROUND EARTH.
● PROJECTED – This is for SRSs based on georeferenced coordi­
nate systems that do not have axes of latitude and longitude.
These SRSs are of type PLANAR.
● ENGINEERING – This is for SRSs based on non-georeferenced
coordinate systems. These SRSs are of type PLANAR.
● GEOCENTRIC – Unsupported.
● COMPOUND – Unsupported.
● VERTICAL – Unsupported.

If srs_type is empty, the type is unspecified.

linear_unit_of_measure UNSIGNED BIGINT The linear unit of measure used by the spatial reference system.

angular_unit_of_measure UNSIGNED BIGINT The angular unit of measure used by the spatial reference system.

count_in_use UNSIGNED BIGINT For internal use only.

polygon_format LONG VARCHAR The orientation of the rings in a polygon. One of CounterClockwise,
ClockWise, or EvenOdd.

storage_format LONG VARCHAR Whether the data is stored in normalized format (Internal), unnor­
malized format (Original), or both (Mixed).

definition LONG VARCHAR The WKT definition of the spatial reference system in the format de­
fined by the OGC standard.

transform_definition LONG VARCHAR Transform definition settings for use when transforming data from
this SRS to another.

Remarks

This view offers slightly different amount of information than the ST_SPATIAL_REFERENCE_SYSTEMS system
view.

 Note

Spatial data, spatial references systems, and spatial units of measure can be used only in the catalog store.

Constraints on Underlying System Table

PRIMARY KEY (object_id)

FOREIGN KEY (object_id) REFERENCES SYS.ISYSOBJECT (object_id)

SAP IQ SQL Reference


System Tables and Views INTERNAL 1081
FOREIGN KEY (linear_unit_of_measure) REFERENCES SYS.ISYSUNITOFMEASURE (object_id)

FOREIGN KEY (angular_unit_of_measure) REFERENCES SYS.ISYSUNITOFMEASURE


(object_id)

FOREIGN KEY (owner) REFERENCES SYS.ISYSUSER (user_id)

UNIQUE CONSTRAINT (srs_name)

UNIQUE CONSTRAINT (srs_id)

8.2.3.123 SYSSQLSERVERTYPE system view

The SYSSQLSERVERTYPE system view contains information relating to compatibility with Adaptive Server
Enterprise. The underlying system table for this view is ISYSSQLSERVERTYPE.

Column name Data type Description

ss_user_type SMALLINT The Adaptive Server Enterprise user


type.

ss_domain_id SMALLINT The Adaptive Server Enterprise domain


ID.

ss_type_name VARCHAR (30) The Adaptive Server Enterprise type


name.

primary_sa_domain_id SMALLINT The corresponding SAP IQ primary do­


main ID.

primary_sa_user_type SMALLINT The corresponding SAP IQ primary user


type.

8.2.3.124 SYSSUBPARTITIONKEY System View

Presents group information from the ISYSSUBPARTITIONKEY system table in a readable format.

Column Name Data Type Description

partitioned_object_id UNSIGNED BIGINT Unique number assigned to each partitioned object (table or in­
dex).

column_id UNSIGNED INT Identifies which column of the table as part of the partitioning key,
Together, partitioned_object_id and column_id identify one column
described in the SYSTABCOL system view.

position SMALLINT Position of the column in the partitioning key. A value of 0 indicates
the 1st column in the partitioning key. A value of 1 indicates the 2nd
column in the partitioning key.

SAP IQ SQL Reference


1082 INTERNAL System Tables and Views
Remarks

The SYSSUBPARTITIONKEY system view contains one row for each column of a partition described in
ISYSPARTITION view in a partitioned table described in the ISYSPARTITIONSCHEME view.

Constraints on Underlying System Table

Primary key (partitioned_object_id, column_id)

Foreign Key (partitioned_object_id) references SYS.ISYSOBJECT

8.2.3.125 SYSSUBSCRIPTION system view

Each row in the SYSSUBSCRIPTION system view describes a subscription from one user ID (which must have
the REMOTE system privilege) to one publication. The underlying system table for this view is
ISYSSUBSCRIPTION.

Column name Data type Description

publication_id UNSIGNED INT The identifier for the publication to


which the user ID is subscribed.

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 ex­


pression, 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.

8.2.3.126 SYSSUBSCRIPTIONS consolidated view

Each row describes a subscription from one user ID (which must have the REMOTE system privilege) to one
publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSUBSCRIPTIONS"


as select p.publication_name,u.user_name,s.subscribe_by,s.created,
s.started
from SYS.ISYSSUBSCRIPTION as s
join SYS.ISYSPUBLICATION as p on(p.publication_id = s.publication_id)

SAP IQ SQL Reference


System Tables and Views INTERNAL 1083
join SYS.ISYSUSER as u on u.user_id = s.user_id

8.2.3.127 SYSSYNC system view

The SYSSYNC system view contains information relating to synchronization.

The "option" and server_connect columns of the underlying table, ISYSSYNC, contain sensitive information
such as passwords. You must have the SELECT ANY TABLE and ACCESS USER PASSWORD system privileges
to select from this view. The SYSSYNC2 consolidated view provides public access to the same data without the
sensitive data.

The underlying system table for this view is ISYSSYNC.

Column name Data type Description

sync_id UNSIGNED INT A number that uniquely identifies the


row.

type CHAR(1) This value is always D.

publication_id UNSIGNED INT A publication_id found in the SYSPU­


BLICATION system view.

progress UNSIGNED BIGINT The log offset of the last successful up­
load.

site_name CHAR(128) A user name.

"option" LONG VARCHAR Synchronization options.

server_connect LONG VARCHAR The address or URL of the server.

server_conn_type LONG VARCHAR The communication protocol, such as


TCP/IP, to use when synchronizing.

last_download_time TIMESTAMP Indicates the last time a download


stream was received from the server.

last_upload_time TIMESTAMP Indicates the last time (measured at the


server) that information was success­
fully uploaded. The default is
jan-1-1900.

created UNSIGNED BIGINT The log offset at which the subscription


was created.

log_sent UNSIGNED BIGINT The log progress up to which informa­


tion has been uploaded. It is not neces­
sary that an acknowledgment of the up­
load be received for the entry in this col­
umn to be updated.

generation_number INTEGER For file-base downloads, the last gener­


ation number received for this sub­
scription. The default is 0.

SAP IQ SQL Reference


1084 INTERNAL System Tables and Views
Column name Data type Description

extended_state VARCHAR(1024) For internal use only.

script_version CHAR(128) Indicates the script version used by the


CREATE and ALTER SYNCHRONIZA­
TION SUBSCRIPTION statements and
the START SYNCHRONIZATION
SCHEMA CHANGE statement.

subscription_name CHAR (128) The name of the subscription.

server_protocol UNSIGNED BIGINT For internal use only. Contains a value


used internally to identify the version of
the synchronization server.

8.2.3.128 SYSSYNC2 consolidated view

The SYSSYNC2 view provides public access to the data found in the SYSSYNC system view (information
related to synchronization) without exposing potentially sensitive data.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular column, use the links provided beneath the view definition.

The server_connect and option columns display three asterisks (***) if a value is present in the database and
NULL if no value is present.

ALTER VIEW "SYS"."SYSSYNC2"


as select "ISYSSYNC"."sync_id",
"ISYSSYNC"."type",
"ISYSSYNC"."publication_id",
"ISYSSYNC"."progress",
"ISYSSYNC"."site_name",
if "ISYSSYNC"."option" is null then null else '***' endif as "option",
if "ISYSSYNC"."server_connect" is null then null else '***' endif as
"server_connect",
"ISYSSYNC"."server_conn_type",
"ISYSSYNC"."last_download_time",
"ISYSSYNC"."last_upload_time",
"ISYSSYNC"."created",
"ISYSSYNC"."log_sent",
"ISYSSYNC"."generation_number",
"ISYSSYNC"."extended_state",
"ISYSSYNC"."script_version",
"ISYSSYNC"."subscription_name",
"ISYSSYNC"."server_protocol"
from "SYS"."ISYSSYNC"

SAP IQ SQL Reference


System Tables and Views INTERNAL 1085
8.2.3.129 SYSSYNCPUBLICATIONDEFAULTS consolidated
view

The SYSSYNCPUBLICATIONDEFAULTS view provides the default synchronization settings associated with
publications involved in synchronization.

The tables and columns that make up this view are provided in the SQL statement below.

The server_connect and option columns display three asterisks (***) if a value is present in the database and
NULL if no value is present.

ALTER VIEW "SYS"."SYSSYNCPUBLICATIONDEFAULTS"


as select "s"."sync_id",
"p"."publication_name",
"s"."option",
"s"."server_connect",
"s"."server_conn_type"
from "SYS"."SYSSYNC2" as "s" join "SYS"."SYSPUBLICATION" as "p"
on("p"."publication_id" = "s"."publication_id") where
"s"."site_name" is null

8.2.3.130 SYSSYNCS consolidated view

The SYSSYNCS view contains information relating to synchronization.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

The server_connect and option columns display three asterisks (***) if a value is present in the database and
NULL if no value is present.

The underlying view for this consolidated view is SYSSYNC2.

ALTER VIEW "SYS"."SYSSYNCS"


as select "p"."publication_name","s"."progress","s"."site_name",
"s"."option",
"s"."server_connect",
"s"."server_conn_type","s"."last_download_time",
"s"."last_upload_time","s"."created","s"."log_sent","s"."generation_number",
"s"."extended_state"
from "SYS"."SYSSYNC2" as "s"
left outer join "SYS"."SYSPUBLICATION" as "p"
on "p"."publication_id" = "s"."publication_id"

8.2.3.131 SYSSYNCSCRIPT system view

Each row in the SYSSYNCSCRIPT system view identifies a stored procedure for scripted upload. This view is
almost identical to the SYSSYNCSCRIPTS view, except that the values in this view are in their raw format.

The underlying system table for this view is ISYSSYNCSCRIPT.

SAP IQ SQL Reference


1086 INTERNAL System Tables and Views
Column name Data type Description

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.

type UNSIGNED INT The type of upload procedure.

proc_object_id UNSIGNED BIGINT The object ID of the stored procedure to


use for the publication.

8.2.3.132 SYSSYNCSCRIPTS consolidated view

Each row in the SYSSYNCSCRIPTS view identifies a stored procedure for scripted upload. This view is almost
identical to the SYSSYNCSCRIPT system view, except that the values are in human-readable format, as
opposed to raw data.

ALTER VIEW "SYS"."SYSSYNCSCRIPTS"


as select p.publication_name,
t.table_name,
case s.type
when 0 then 'upload insert'
when 1 then 'upload delete'
when 2 then 'upload update'
else 'unknown'
end as type,
c.proc_name
from SYS.ISYSSYNCSCRIPT as s
join SYS.ISYSPUBLICATION as p on p.object_id = s.pub_object_id
join SYS.ISYSTAB as t on t.object_id = s.table_object_id
join SYS.ISYSPROCEDURE as c on c.object_id = s.proc_object_id

8.2.3.133 SYSSYNCSUBSCRIPTIONS consolidated view

The SYSSYNCSUBSCRIPTIONS view contains the synchronization settings associated with synchronization
subscriptions.

The tables and columns that make up this view are provided in the SQL statement below.

The server_connect and option columns display three asterisks (***) if a value is present in the database and
NULL if no value is present.

ALTER VIEW "SYS"."SYSSYNCSUBSCRIPTIONS"


as select "s"."sync_id",
"p"."publication_name",
"s"."progress",
"s"."site_name",
"s"."option",
"s"."server_connect",
"s"."server_conn_type",
"s"."last_download_time",
"s"."last_upload_time",
"s"."created",

SAP IQ SQL Reference


System Tables and Views INTERNAL 1087
"s"."log_sent",
"s"."generation_number",
"s"."extended_state"
from "SYS"."SYSSYNC2" as "s" join "SYS"."SYSPUBLICATION" as "p"
on("p"."publication_id" = "s"."publication_id")
where "s"."publication_id" is not null and
"s"."site_name" is not null and exists
(select 1 from "SYS"."SYSSYNCUSERS" as "u"
where "s"."site_name" = "u"."site_name")

8.2.3.134 SYSSYNCUSERS consolidated view

A view of synchronization settings associated with synchronization users.

The tables and columns that make up this view are provided in the SQL statement below.

The server_connect and option columns display three asterisks (***) if a value is present in the database and
NULL if no value is present.

ALTER VIEW "SYS"."SYSSYNCUSERS"


as select "SYSSYNC2"."sync_id",
"SYSSYNC2"."site_name",
"SYSSYNC2"."option",
"SYSSYNC2"."server_connect",
"SYSSYNC2"."server_conn_type"
from "SYS"."SYSSYNC2" where
"SYSSYNC2"."publication_id" is null

8.2.3.135 SYSTAB system view

Each row of the SYSTAB system view describes one table or view in the database. Additional information for
views can be found in the SYSVIEW system view. The underlying system table for this view is ISYSTAB.

Column name Data type Description

table_id UNSIGNED INT Each table is assigned a unique number


(the table number).

dbspace_id SMALLINT A value indicating which dbspace con­


tains the table.

count UNSIGNED BIGINT The number of rows in the table or ma­


terialized view. This value is updated
during each successful checkpoint.
This number is used to optimize data­
base access. The count is always 0 for a
non-materialized view or remote table.

creator UNSIGNED INT The user number of the owner of the ta­
ble or view.

table_page_count INTEGER The total number of main pages used


by the underlying table.

SAP IQ SQL Reference


1088 INTERNAL System Tables and Views
Column name Data type Description

ext_page_count INTEGER The total number of extension pages


used by the underlying table.

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 ta­
bles), and 3 indicates that the NOT
TRANSACTIONAL clause was specified
when the table was created. For non-
temporary tables, commit_action is al­
ways 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 indicates 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 speci­
fied when creating non-temporary ta­
bles.

object_id UNSIGNED BIGINT The object ID of the table.

last_modified_at TIMESTAMP The local 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 cre­


ator cannot have two tables or views
with the same name.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1089
Column name Data type Description

table_type TINYINT The type of table or view. Values in­


clude:

Base table
2

Materialized view
3

Global temporary table


4

Local temporary table


5

Text index base table


6

Text index global temporary table


21

View

replicate CHAR(1) This value is for internal use only.

server_type TINYINT The location of the data for the underly­


ing table. Values include:

Local server
2

IQ table
3

Remote server

tab_page_list LONG VARBIT For internal use only. The set of pages
that contain information for the table,
expressed as a bitmap.

ext_page_list LONG VARBIT For internal use only. The set of pages
that contain row extensions and large
object (LOB) pages for the table, ex­
pressed as a bitmap.

pct_free UNSIGNED INT The PCT_FREE specification for the ta­


ble, if one has been specified; other­
wise, NULL.

clustered_index_id UNSIGNED INT The ID of the clustered index for the ta­
ble. If none of the indexes are clustered,
then this field is NULL.

encrypted CHAR(1) Whether the table or materialized view


is encrypted.

SAP IQ SQL Reference


1090 INTERNAL System Tables and Views
Column name Data type Description

last_modified_tsn UNSIGNED BIGINT A sequence number assigned to the


transaction that modified the table.
This column is only updated at check­
point time.

current_schema UNSIGNED INT The current schema version of the ta­


ble.

file_id SMALLINT DEPRECATED. This column is present in


SYSVIEW, but not in the underlying sys­
tem table ISYSTAB. The contents of this
column is the same as dbspace_id and
is provided for compatibility. Use
dbspace_id instead.

table_type_str CHAR(13) Readable value for table_type. Values


include:

BASE

Base table
MAT VIEW

Materialized view
GBL TEMP

Global temporary table


VIEW

View

last_modified_at_utc TIMESTAMP WITH TIME ZONE The UTC time at which the data in the
table was last modified. This column is
only updated at checkpoint time.

8.2.3.136 SYSTABAUTH consolidated view

The SYSTABAUTH view contains information from the SYSTABLEPERM system view, but in a more readable
format.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSTABAUTH"( grantor,


grantee,screator,stname,tcreator,ttname,
selectauth,insertauth,deleteauth,
updateauth,updatecols,alterauth,referenceauth,
loadauth,truncateauth )
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,tp.loadauth,tp.truncateauth
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

SAP IQ SQL Reference


System Tables and Views INTERNAL 1091
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

8.2.3.137 SYSTABCOL system view

The SYSTABCOL system view contains one row for each column of each table and view in the database. The
underlying system table for this view is ISYSTABCOL.

Column name Data type Description

table_id UNSIGNED INT The object ID of the table or view to


which the column belongs.

column_id UNSIGNED INT The ID of the column. For each table,


column numbering starts at 1.

The column_id value determines the or­


der of columns in the result set when
SELECT * is used. It also determines
the column order for an INSERT state­
ment when a list of column names is
not provided.

domain_id SMALLINT The data type for the column, indicated


by a data type number listed in the SYS­
DOMAIN system view.

nulls CHAR(1) Indicates whether NULL values are al­


lowed in the column.

width BIGINT The length of a string column, the preci­


sion of numeric columns, or the num­
ber 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 se­
mantics and 0 indicates byte-length se­
mantics.

object_id UNSIGNED BIGINT The object ID of the table column.

max_identity BIGINT The largest value of the column, if it is


an AUTOINCREMENT, IDENTITY, or
GLOBAL AUTOINCREMENT column.

column_name CHAR(128) The name of the column.

"default" LONG VARCHAR The default value for the column. This
value, if specified, is only used when an
INSERT statement does not specify a
value for the column.

SAP IQ SQL Reference


1092 INTERNAL System Tables and Views
Column name Data type Description

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 col­


umn, and R=other columns).

compressed TINYINT Whether this column is stored in a com­


pressed format.

collect_stats TINYINT Whether the system automatically col­


lects and updates statistics on this col­
umn.

inline_max SMALLINT The maximum number of bytes of a


BLOB to store in a row. A NULL value in­
dicates that either the default value has
been applied, or that the column is not
a character or binary type. A non-NULL
inline_max value corresponds to the IN­
LINE value specified for the column us­
ing the CREATE TABLE or ALTER TA­
BLE statement.

inline_long SMALLINT The number of duplicate bytes of a


BLOB to store in a row if the BLOB size
exceeds the inline_max value. A NULL
value indicates that either the default
value has been applied, or that the col­
umn is not a character or binary type. A
non-NULL inline_long value corre­
sponds to the PREFIX value specified
for the column using the CREATE TA­
BLE or ALTER TABLE statement.

lob_index TINYINT Whether to build indexes on BLOB val­


ues in the column that exceed an inter­
nal threshold size (approximately eight
database pages). A NULL value indi­
cates either that the default is applied,
or that the column is not BLOB type. A
value of 1 indicates that indexes will be
built. A value of 0 indicates that no in­
dexes will be built. A non-NULL lob_in­
dex value corresponds to whether IN­
DEX or NO INDEX was specified for the
column using the CREATE TABLE or AL­
TER TABLE statement.

base_type_str VARCHAR(32,767) The annotated type string representing


the physical type of the column.

nonmaterialized_value LONG BINARY Internal use only.

start_schema UNSIGNED INT The first version of the table schema in


which this column exists.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1093
8.2.3.138 SYSTABLE compatibility view (deprecated)

The SYSTABLE view is provided for compatibility with older versions of the software that offered a SYSTABLE
system table. However, the SYSTABLE system table has been replaced by the ISYSTAB system table, and its
corresponding SYSTAB system view, which you should use instead.

Each row of SYSTABLE view describes one table in the database.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSTABLE"


as select b.table_id,
b.file_id,
b.count,
0 as first_page,
b.commit_action as last_page,
COALESCE(ph.root,0) as primary_root,
b.creator,
0 as first_ext_page,
0 as last_ext_page,
b.table_page_count,
b.ext_page_count,
b.object_id,
b.table_name,
b.table_type_str as table_type,
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)

SAP IQ SQL Reference


1094 INTERNAL System Tables and Views
8.2.3.139 SYSTABLEPERM system view

Privileges granted on tables and views by the GRANT statement are stored in the SYSTABLEPERM system view.
Each row in this view corresponds to one table, one user ID granting the privilege (grantor) and one user ID
granted the privilege (grantee). The underlying system table for this view is ISYSTABLEPERM.

Column name Data type Description

stable_id UNSIGNED INT The table number of the table or view to


which the privileges apply.

grantee UNSIGNED INT The user number of the user ID receiv­


ing the privilege.

grantor UNSIGNED INT The user number of the user ID grant­


ing the privilege.

selectauth CHAR(1) Indicates whether SELECT privileges


have been granted. Possible values are
Y, N, or G. See the Remarks area below
for more information about what these
values mean.

insertauth CHAR(1) Indicates whether INSERT privileges


have been granted. Possible values are
Y, N, or G. See the Remarks area below
for more information about what these
values mean.

deleteauth CHAR(1) Indicates whether DELETE privileges


has been granted. Possible values are Y,
N, or G. See the Remarks area below for
more information about what these val­
ues mean.

updateauth CHAR(1) Indicates whether UPDATE privileges


have been granted for all columns in the
table. Possible values are Y, N, or G. See
the Remarks area below for more infor­
mation about what these values mean.

updatecols CHAR(1) Indicates whether UPDATE privileges


have only been granted for some of the
columns in the underlying table. If up­
datecols has the value Y, there will be
one or more rows in the SYSCOLPERM
system view granting update privileges
for the columns.

alterauth CHAR(1) Indicates whether ALTER privileges


have been granted. Possible values are
Y, N, or G. See the Remarks area below
for more information about what these
values mean.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1095
Column name Data type Description

referenceauth CHAR(1) Indicates whether REFERENCE privi­


leges have been granted. Possible val­
ues are Y, N, or G. See the Remarks
area below for more information about
what these values mean.

loadauth CHAR(1) Indicates whether LOAD privileges have


been granted. Possible values are Y, N,
or G. See the Remarks area below for
more information about what these val­
ues mean.

truncateauth CHAR(1) Indicates whether TRUNCATE privi­


leges have been granted. Possible val­
ues are Y, N, or G. See the Remarks
area below for more information about
what these values mean.

loadauth CHAR(1) Indicates whether LOAD privileges has


been granted. Possible values are Y, N,
or G. See the Remarks area below for
more information about what these val­
ues mean.

truncateauth CHAR(1) Indicates whether TRUNCATE privi­


leges has been granted. Possible values
are Y, N, or G. See the Remarks area be­
low for more information about what
these values mean.

Remarks

There are several types of privileges that can be granted. Each privilege can have one of the following three
values.

No, the grantee has not been granted this privilege by the grantor.
Y

Yes, the grantee has been given this privilege by the grantor.
G

The grantee has been given this privilege and can grant the same privilege to another user.

 Note

The grantee might have been given the privilege for the same table by another grantor. If so, this
information would be found in a different row of the SYSTABLEPERM system view.

SAP IQ SQL Reference


1096 INTERNAL System Tables and Views
Constraints on underlying system table

PRIMARY KEY (stable_id, grantee, grantor)

FOREIGN KEY (stable_id) REFERENCES SYS.ISYSTAB (table_id)

FOREIGN KEY (grantor) REFERENCES SYS.ISYSUSER (user_id)

FOREIGN KEY (grantee) REFERENCES SYS.ISYSUSER (user_id)

8.2.3.140 SYSTEXTCONFIG system view

Each row in the SYSTEXTCONFIG system view describes one text configuration object, for use with the full text
search feature. The underlying system table for this view is ISYSTEXTCONFIG.

Column name Data type Description

object_id UNSIGNED BIGINT The object ID for the text configuration


object.

creator UNSIGNED INT The creator of the text configuration


object.

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 alpha­
numeric characters separated by non-
alphanumerics are treated as a term.
NGRAM is for approximate matching or
for documents that do not use a white­
space to separate terms.

stemmer TINYINT For internal use only.

min_term_length TINYINT The minimum length, in characters, al­


lowed for a term. Terms that are shorter
than min_term_length are ignored.

The MINIMUM TERM LENGTH setting is


only meaningful for the GENERIC term
breaker. For NGRAM text indexes, the
setting is ignored.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1097
Column name Data type Description

max_term_length TINYINT For GENERIC text indexes, the maxi­


mum length, in characters, allowed for
a term. Terms that are longer than
max_term_length are ignored.

For NGRAM text indexes, this is the


length of the n-grams into which terms
are broken.

collation CHAR(128) For internal use only.

text_config_name CHAR(128) The name of the text configuration ob­


ject.

prefilter LONG VARCHAR The function and library name for an ex­
ternal prefilter library.

postfilter LONG VARCHAR For internal use only.

char_stoplist LONG VARCHAR Terms to ignore when performing a full


text search on CHAR columns. These
terms are also omitted from text in­
dexes. This column is used when the
text configuration object is created
from default_char.

nchar_stoplist LONG NVARCHAR Terms to ignore when performing a full


text search on NCHAR columns. These
terms are also omitted from text in­
dexes. This column is used when the
text configuration object is created
from default_nchar.

external_term_breaker LONG VARCHAR The function and library name for an ex­
ternal term breaker library.

8.2.3.141 SYSTEXTIDX system view

Each row in the SYSTEXTIDX system view describes one text index. The underlying system table for this view is
ISYSTEXTIDX.

Column name Data type Description

index_id UNSIGNED BIGINT The object ID of the text index in SY­


SIDX.

sequence UNSIGNED INT For internal use only.

status UNSIGNED INT For internal use only.

text_config UNSIGNED BIGINT The object ID of the text configuration


object in SYSTEXTCONFIG.

next_handle UNSIGNED INT For internal use only.

SAP IQ SQL Reference


1098 INTERNAL System Tables and Views
Column name Data type Description

last_handle UNSIGNED INT For internal use only.

deleted_length UNSIGNED BIGINT The total size of deleted indexed values


in the text index.

pending_length UNSIGNED BIGINT The total size of indexed values that will
be added to the text index at the next
refresh.

refresh_type TINYINT The type of refresh. One of:

MANUAL
2

AUTO
3

IMMEDIATE

refresh_interval UNSIGNED INT The AUTO REFRESH interval, in mi­


nutes.

last_refresh TIMESTAMP The local time of the last refresh.

last_refresh_utc TIMESTAMP WITH TIME ZONE The UTC time of the last refresh.

8.2.3.142 SYSTEXTIDXTAB system view

Each row in the SYSTEXTIDXTAB system view describes a generated table that is part of a text index. The
underlying system table for this view is ISYSTEXTIDXTAB.

Column name Data type Description

index_id UNSIGNED BIGINT For internal use only.

sequence UNSIGNED INT For internal use only.

table_type UNSIGNED INT For internal use only.

table_id UNSIGNED INT For internal use only.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1099
8.2.3.143 SYSTRIGGER system view

Each row in the SYSTRIGGER system view describes one trigger in the database. This view also contains
triggers that are automatically created for foreign key definitions which have a referential triggered action (such
as ON DELETE CASCADE). The underlying system table for this view is ISYSTRIGGER.

Column name Data type Description

trigger_id UNSIGNED INT A unique number for the trigger in the


SYSTRIGGER view.

table_id UNSIGNED INT The table ID of the table to which this


trigger belongs.

object_id UNSIGNED BIGINT The object ID for the trigger in the data­
base.

event CHAR(1) The operation that causes the trigger to


fire.

INSERT, DELETE
B

INSERT, UPDATE
C

UPDATE COLUMNS
D

DELETE
E

DELETE, UPDATE
I

INSERT
M

INSERT, DELETE, UPDATE


U

UPDATE

SAP IQ SQL Reference


1100 INTERNAL System Tables and Views
Column name Data type Description

trigger_time CHAR(1) The time when the trigger fires relative


to the event.

AFTER (row-level trigger)


B

BEFORE (row-level trigger)


I

INSTEAD OF (row-level trigger)


K

INSTEAD OF (statement-level trig­


ger)
R

RESOLVE
S

AFTER (statement-level trigger)

trigger_order SMALLINT The order in which are fired when there


are multiple triggers of the same type
(insert, update, or delete) set to fire at
the same time (applies to BEFORE or
AFTER triggers only, only).

foreign_table_id UNSIGNED INT The ID of the table containing a foreign


key definition that has a referential trig­
gered action (such as ON DELETE CAS­
CADE). The foreign_table_id value re­
flects the value of ISYSIDX.table_id.

foreign_key_id UNSIGNED INT The ID of the foreign key for the table
referenced by foreign_table_id. The for­
eign_key_id value reflects the value of
ISYSIDX.index_id.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1101
Column name Data type Description

referential_action CHAR(1) The action defined by a foreign key.


This single-character value corre­
sponds to the action that was specified
when the foreign key was created.

CASCADE
D

SET DEFAULT
N

SET NULL
R

RESTRICT

trigger_name CHAR(128) The name of the trigger. One table can­


not have two triggers with the same
name.

trigger_defn LONG VARCHAR The command that was used to create


the trigger.

remarks LONG VARCHAR Remarks about the trigger. This value is


stored in the ISYSREMARK system ta­
ble.

source LONG VARCHAR The SQL source for the trigger. This
value is stored in the ISYSSOURCE sys­
tem table.

8.2.3.144 SYSTRIGGERS consolidated view

Each row in the SYSTRIGGERS view describes one trigger in the database. This view also contains triggers that
are automatically created for foreign key definitions which have a referential triggered action (such as ON
DELETE CASCADE).

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSTRIGGERS"( owner,


trigname,tname,event,trigtime,trigdefn )
as select u.user_name,trig.trigger_name,tab.table_name,
if trig.event = 'I' then 'INSERT'
else if trig.event = 'U' then 'UPDATE'
else if trig.event = 'C' then 'UPDATE'
else if trig.event = 'D' then 'DELETE'
else if trig.event = 'A' then 'INSERT,DELETE'
else if trig.event = 'B' then 'INSERT,UPDATE'
else if trig.event = 'E' then 'DELETE,UPDATE'
else 'INSERT,DELETE,UPDATE'
endif
endif
endif

SAP IQ SQL Reference


1102 INTERNAL System Tables and Views
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

8.2.3.145 SYSTYPEMAP system view

The SYSTYPEMAP system view contains the compatibility mapping values for entries in the
SYSSQLSERVERTYPE system view. The underlying system table for this view is ISYSTYPEMAP.

Column name Data type Description

ss_user_type SMALLINT Contains the Adaptive Server Enter­


prise user type.

sa_domain_id SMALLINT Contains the corresponding SAP IQ do­


main_id.

sa_user_type SMALLINT Contains the corresponding SAP IQ


user type.

nullable CHAR(1) Whether the type allows NULL values.

8.2.3.146 SYSTYPES ASE Compatibility View

systypes contains one row for each system-supplied and user-defined datatype. Domains (defined by rules)
and defaults are given, if they exist.

This view is owned by user DBO. You cannot alter the rows that describe system-supplied datatypes.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]

SAP IQ SQL Reference


System Tables and Views INTERNAL 1103
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.147 SYSUSER system view

Each row in the SYSUSER system view describes a user in the system.

Standalone roles are also stored in this view as well, but only the user_id, object_id, user_name, and user_type
columns are meaningful for these roles. The underlying system table for this view is ISYSUSER.

Column name Data type Description

user_id UNSIGNED INT A unique identifier for the user assigned


to the login policy.

object_id UNSIGNED BIGINT A unique identifier for the user in the


database.

user_name CHAR(128) The login name for the user.

password CHAR(3) Whether a password is stored. Three


asterisks (***) indicate that a password
is stored. NULL indicates that no pass­
word is stored. You can return actual
password hash values by querying the
SYSUSERPASSWORD system view.

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

expire_password_on_login TINYINT A value that indicates if the password


for the user expires at the next login.

password_creation_time TIMESTAMP The local time that the password was


created for the user.

failed_login_attempts UNSIGNED INT The number of times that a user can fail
to log in before the account is locked.

last_login_time TIMESTAMP The local time that the user last logged
in.

SAP IQ SQL Reference


1104 INTERNAL System Tables and Views
Column name Data type Description

user_type TINYINT A value that indicates whether the user


is a regular user, or a role, or a user ex­
tended as a role. And whether the user,
role, or extended role can be altered
(mutable) or removed. Possible values:

Immutable system role.


5

Mutable system role


9

Immutable and removable system


role.
12

Mutable and removable user.


13

Mutable and removable role.


14

Mutable and removable user ex­


tended as role.

user_dn CHAR (1024) An LDAP Distinguished Name (DN)


identifier for the user that is unique
within a domain and across domains.
The DN is used to authenticate with an
LDAP server.

user_dn_cached_at TIMESTAMP The time that the user_dn column was


last cached. This value is used to deter­
mine whether to purge an old DN. Re­
gardless of the database server local
time zone, the value is stored in Coordi­
nated Universal Time (UTC).

password_creation_time_utc TIMESTAMP WITH TIME ZONE The UTC time that the password was
created for the user.

last_login_time_utc TIMESTAMP WITH TIME ZONE The UTC time that the user last logged
in.

dual_password CHAR(3) Whether the second part of a dual pass­


word is stored for the user. Three aster­
isks (***) indicate that a second part is
stored. NULL indicates that there is no
second part. You can return actual
password hash values by querying the
SYSUSERPASSWORD system view.

lock_time TIMESTAMP Timestamp at which user was locked


due to failed login attempts.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1105
8.2.3.148 SYSUSERAUTH compatibility view (deprecated)

Each row of the SYSUSERAUTH view describes a user, without exposing their user ID and password hash.
Instead, each user is identified by their user name.

You must have the SELECT ANY TABLE system privilege to access this view.

The SYSUSERAUTH view is provided for compatibility with older versions of the software. Use the
SYSROLEGRANTS consolidated view instead.

The password column displays three asterisks (***) if a value is present in the database and NULL if no value is
present.

Although the title of this view contains the word auth (for authorities), the security model is based on roles and
privileges. The data in the view is therefore compiled using role information from the tables and views
mentioned in the view definition.

ALTER VIEW "SYS"."SYSUSERAUTH"( "name",


"password","resourceauth","dbaauth","scheduleauth","user_group" )
as select
"SYSUSERPERM"."user_name","SYSUSERPERM"."password","SYSUSERPERM"."resourceauth","
SYSUSERPERM"."dbaauth","SYSUSERPERM"."scheduleauth","SYSUSERPERM"."user_group"
from "SYS"."SYSUSERPERM"

8.2.3.149 SYSUSERAUTHORITY compatibility view


(deprecated)

The SYSUSERAUTHORITY view is provided for compatibility with older versions of the software. Use the
SYSROLEGRANTS consolidated view instead.

Each row of SYSUSERAUTHORITY system view describes an authority granted to one user ID.

Although the title of this view contains the word authority, the security model is based on roles and privileges.
The data in the view is therefore compiled using role information from the tables and views mentioned in the
view definition.

ALTER VIEW "SYS"."SYSUSERAUTHORITY" as


select ISYSROLEGRANT.grantee as user_id,
sp_auth_sys_role_info.auth
from SYS.ISYSROLEGRANT
natural join dbo.sp_auth_sys_role_info()
where ISYSROLEGRANT.grant_type <> (0x02|0x04) and
not ISYSROLEGRANT.grantee = any(select sp_auth_sys_role_info.role_id from
dbo.sp_auth_sys_role_info()) union
select ISYSUSER.user_id,
cast('GROUP' as varchar(20)) as auth
from SYS.ISYSUSER
where ISYSUSER.user_name
in( 'SYS','PUBLIC','diagnostics','SYS_SPATIAL_ADMIN_ROLE','rs_systabgroup','SA_DE
BUG','dbo' ) union
select ISYSUSER.user_id,
cast('GROUP' as varchar(20)) as auth
from SYS.ISYSUSER
where ISYSUSER.user_type = (0x02|0x04|0x08) union
select cast(opt.setting as unsigned integer) as user_id,
cast('PUBLISH' as varchar(20)) as auth

SAP IQ SQL Reference


1106 INTERNAL System Tables and Views
from SYS.ISYSOPTION as opt
where opt."option" like '%db_publisher%' and opt.setting not like '%-1%'

8.2.3.150 SYSUSERLIST compatibility view (deprecated)

The SYSUSERAUTH view is provided for compatibility with older versions of the software.

Each row of the SYSUSERLIST view describes a user, without exposing their user_id and password. Each user is
identified by their user name.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSUSERLIST"( name,


resourceauth,dbaauth,scheduleauth,user_group )
as select
SYSUSERPERM.user_name,SYSUSERPERM.resourceauth,SYSUSERPERM.dbaauth,SYSUSERPERM.sc
heduleauth,SYSUSERPERM.user_group
from SYS.SYSUSERPERM

8.2.3.151 SYSUSERMESSAGE system view

Each row in the SYSUSERMESSAGE system view holds a user-defined message for an error condition. The
underlying system table for this view is ISYSUSERMESSAGE.

Previous versions of the catalog contained a SYSUSERMESSAGES system table. That table has been renamed
to be ISYSUSERMESSAGE (without an 'S'), and is the underlying table for this view.

Column name Data type Description

error INTEGER A unique identifying number for the er­


ror condition.

uid UNSIGNED INT The user number that defined the mes­
sage.

description VARCHAR(255) The message corresponding to the er­


ror condition.

langid SMALLINT Reserved.

8.2.3.152 SYSUSEROPTIONS consolidated view

The SYSUSEROPTIONS view contains the option settings that are in effect for each user. If a user has no
setting for an option, this view displays the public setting for the option.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSUSEROPTIONS"( user_name,

SAP IQ SQL Reference


System Tables and Views INTERNAL 1107
"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'

8.2.3.153 SYSUSERPERM compatibility view (deprecated)


Each row of the SYSUSERPERM view describes one user ID.

This view is deprecated because it only shows the authorities and permissions available in previous versions.
Change your application to use the SYSROLEGRANTS consolidated view.

You must have the SELECT ANY TABLE system privilege to access this view.

The password column displays three asterisks (***) if a value is present in the database and NULL if no value is
present. To see actual password information, see the SYSUSERPASSWORD system view.

The tables and columns that make up this view are provided in the SQL statement below.

ALTER VIEW "SYS"."SYSUSERPERM"


as select "b"."user_id",
"b"."object_id",
"b"."user_name",
if "b"."password" is null then null else '***' endif as "password",
if "AA"."resourceauth" is not null and "AA"."resourceauth" > 0 then
'Y' else 'N' endif as "resourceauth",
if "AA"."dbaauth" is not null and "AA"."dbaauth" > 0 then
'Y' else 'N' endif as "dbaauth",
'N' as "scheduleauth",
if exists(select * from "SYS"."ISYSOPTION" as "opt"
where "opt"."option" like '%db_publisher%' and "opt"."setting" not like
'%-1'
and "b"."user_id" = cast("opt"."setting" as integer)) then
'Y' else 'N' endif as "publishauth",
if "AA"."remotedbaauth" is not null and "AA"."remotedbaauth" > 0 then
'Y' else 'N' endif as "remotedbaauth",
if "b"."user_type" = (0x02|0x04|0x08) or "b"."user_name"
in( 'SYS','PUBLIC','diagnostics','SYS_SPATIAL_ADMIN_ROLE','rs_systabgroup','SA_DE
BUG','dbo' ) then
'Y' else 'N' endif as "user_group",
"r"."remarks"
from "SYS"."ISYSUSER" as "b"
left outer join "SYS"."ISYSREMARK" as "r" on("b"."object_id" =
"r"."object_id")
left outer join(select "sum"(if "sp_auth_sys_role_info"."auth" =
'RESOURCE' then 1 else 0 endif) as "resourceauth",
"sum"(if "sp_auth_sys_role_info"."auth" = 'DBA' then 1 else 0 endif) as
"dbaauth",
"sum"(if "sp_auth_sys_role_info"."auth" = 'REMOTE DBA' then 1 else 0
endif) as "remotedbaauth",
"ISYSROLEGRANT"."grantee"
from "SYS"."ISYSROLEGRANT" natural join "dbo"."sp_auth_sys_role_info"()
where "ISYSROLEGRANT"."grant_type" <> (0x02|0x04)
and "sp_auth_sys_role_info"."auth" in( 'DBA','RESOURCE','REMOTE DBA' )
group by "ISYSROLEGRANT"."grantee") as "AA"
on("AA"."grantee" = "b"."user_id")

SAP IQ SQL Reference


1108 INTERNAL System Tables and Views
8.2.3.154 SYSUSERPERMS compatibility view (deprecated)

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.

This view is deprecated because it only shows the authorities and permissions available in previous versions.
Change your application to use the SYSROLEGRANTS consolidated 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,SYSUSERPERM.db
aauth,

SYSUSERPERM.scheduleauth,SYSUSERPERM.user_group,SYSUSERPERM.publishauth,SYSUSERPE
RM.remotedbaauth,SYSUSERPERM.remarks
from SYS.SYSUSERPERM

8.2.3.155 SYSUSERS ASE Compatibility View

sysusers contains one row for each user allowed in the database, and one row for each group or roles.

This view is owned by user DBO.

Related Information

Tables in Each SAP ASE Database [page 1114]


SYSCOLUMNS ASE Compatibility View [page 1012]
SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]

SAP IQ SQL Reference


System Tables and Views INTERNAL 1109
8.2.3.156 SYSUSERTYPE system view

Each row in the SYSUSERTYPE system view holds a description of a user-defined data type. The underlying
system table for this view is ISYSUSERTYPE.

Column name Data type Description

type_id SMALLINT A unique identifying number for the


user-defined data type.

creator UNSIGNED INT The user number of the owner of the


data type.

domain_id SMALLINT The data type on which this user de­


fined data type is based, indicated by a
data type number listed in the SYSDO­
MAIN system view.

nulls CHAR(1) Whether the user-defined data type al­


lows nulls. Possible values are Y, N, or U.
A value of U indicates that nullability is
unspecified.

width BIGINT The length of a string column, the preci­


sion of a numeric column, or the num­
ber of bytes of storage for any other
data type.

scale SMALLINT The number of digits after the decimal


point for numeric data type columns,
and zero for all other data types.

type_name CHAR(128) The name for the data type.

"default" LONG VARCHAR The default value for the data type.

"check" LONG VARCHAR The CHECK condition for the data type.

base_type_str VARCHAR(32767) The annotated type string representing


the physical type of the user type.

8.2.3.157 SYSVIEW System View

Each row in the SYSVIEW system view describes a view in the database.

You can find additional information about views in the SYSTAB system view. The underlying system table for
this view is ISYSVIEW.

You can also use the sa_materialized_view_info system procedure for a readable format of the
information for materialized views. Materialized views are only supported for SAP SQL Anywhere tables in the
IQ catalog store.

Column Name Data Type Description

view_object_id UNSIGNED BIGINT The object ID of the view.

SAP IQ SQL Reference


1110 INTERNAL System Tables and Views
Column Name Data Type Description

view_def LONG VARCHAR The definition (query specification) of


the view.

mv_build_type TINYINT Unused.

mv_refresh_type TINYINT The refresh type defined for the view.


Possible values are IMMEDIATE (1) and
MANUAL (2).

mv_use_in_optimization TINYINT Whether the materialized view can be


used during query optimization (0=can­
not be used in optimization, 1=can be
used in optimization)

mv_last_refreshed_at TIMESTAMP Indicates the local date and time that


the materialized view was last re­
freshed.

mv_known_stale_at TIMESTAMP The local time at which the materialized


view became stale. This value corre­
sponds to the time at which one of the
underlying base tables was detected as
having changed. A value of 0 indicates
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 determine the sta­
tus of a materialized view.

mv_last_refreshed_tsn UNSIGNED BIGINT The sequence number assigned to the


transaction that refreshed the material­
ized view.

mv_last_refreshed_at_utc TIMESTAMP WITH TIME ZONE Indicates the UTC date and time that
the materialized view was last re­
freshed.

mv_known_stale_at_utc TIMESTAMP WITH TIME ZONE The UTC time at which the materialized
view became stale. This value corre­
sponds to the time at which one of the
underlying base tables was detected as
having changed. A value of 0 indicates
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 determine the sta­
tus of a materialized view. This column
contains 0 when mv_last_refreshed_at
is 0 and NULL when mv_last_re­
freshed_at is NULL.

SAP IQ SQL Reference


System Tables and Views INTERNAL 1111
Constraints on Underlying System Table

PRIMARY KEY (view_object_id)

FOREIGN KEY (view_object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

8.2.3.158 SYSVIEWS consolidated view

Each row of the SYSVIEWS view describes one view, including its view definition.

The tables and columns that make up this view are provided in the SQL statement below. To learn more about a
particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSVIEWS"( vcreator,


viewname,viewtext )
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)

8.2.3.159 SYSWEBSERVICE system view

Each row in the SYSWEBSERVICE system view holds a description of a web service. The underlying system
table for this view is ISYSWEBSERVICE.

Column name Data type Description

service_id UNSIGNED INT A unique identifying number for the


web service.

object_id UNSIGNED BIGINT The ID of the webservice.

service_name CHAR(128) The name assigned to the web service.

service_type VARCHAR(40) The type of the service; for example,


RAW, HTTP, XML, SOAP, or DISH.

auth_required CHAR(1) Whether all requests must contain a


valid user name and password.

secure_required CHAR(1) Whether insecure connections, such as


HTTP, are to be accepted, or only se­
cure connections, such as HTTPS.

url_path CHAR(1) Controls the interpretation of URLs.

SAP IQ SQL Reference


1112 INTERNAL System Tables and Views
Column name Data type Description

user_id UNSIGNED INT If authentication is enabled, identifies


the user, or group of users, that have
permission to use the service. If au­
thentication is disabled, specifies the
account to use when processing re­
quests.

parameter LONG VARCHAR A prefix that identifies the SOAP serv­


ices to be included in a DISH service.

statement LONG VARCHAR A SQL statement that is always exe­


cuted in response to a request. If NULL,
arbitrary statements contained in each
request are executed instead. Ignored
for services of type DISH.

remarks LONG VARCHAR Remarks about the webservice. This


value is stored in the ISYSREMARK sys­
tem table.

enabled CHAR(1) Indicates whether the web service is


currently enabled or disabled (see CRE­
ATE SERVICE).

8.2.3.160 Transact-SQL Compatibility Views


SAP Adaptive Server Enterprise and SAP IQ have different system catalogs, reflecting the different uses for the
two products.

In SAP ASE, there is a single master database containing a set of system tables holding information that
applies to all databases on the server. Many databases may exist within the master database, and each has
additional system tables associated with it.

In SAP IQ, each database exists independently, and contains its own system tables. There is no master
database that contains system information on a collection of databases. Each server may run several
databases at a time, dynamically loading and unloading each database as needed.

The SAP ASE and SAP IQ system catalogs are different. The SAP ASE system tables and views are owned by
the special user dbo, and exist partly in the master database, partly in the sybsecurity database, and partly
in each individual database; the SAP IQ system tables and views are owned by the special user SYS and exist
separately in each database.

To assist in preparing compatible applications, SAP IQ provides a set of views owned by the special user dbo,
which correspond to the SAP ASE system tables and views. Where architectural differences make the contents
of a particular SAP ASE table or view meaningless in a SAP IQ context, the view is empty, containing only the
column names and data types.

These topics list the SAP ASE system tables and their implementation in the SAP IQ system catalog. The owner
of all tables is dbo in each DBMS.

In this section:

Tables in Each SAP ASE Database [page 1114]

SAP IQ SQL Reference


System Tables and Views INTERNAL 1113
Not all SAP Adaptive Server Enterprise system tables are implemented in the SAP IQ system catalog.

Tables in the SAP ASE Master Database [page 1115]


Not all SAP Adaptive Server Enterprise master database tables are implemented in the SAP IQ system
catalog.

Tables in the SAP ASE Sybsecurity Database [page 1116]


No SAP Adaptive Server Enterprise sybsecurity database tables are implemented in the SAP IQ system
catalog.

Related Information

SAP ASE T-SQL Compatibility Views [page 988]

8.2.3.160.1 Tables in Each SAP ASE Database

Not all SAP Adaptive Server Enterprise system tables are implemented in the SAP IQ system catalog.

Supported
Table Name Description Data? by SAP IQ?

sysalternates One row for each user mapped to a database user No No

syscolumns One row for each column in a table or view, and for each parameter Yes Yes
in a procedure. In SAP IQ, use the owner name dbo when querying,
i.e. dbo.syscolumns.

syscomments One or more rows for each view, rule, default, and procedure, giving Yes Yes
SQL definition statement.

sysconstraints One row for each referential and check constraint associated with a No No
table or column.

sysdepends One row for each procedure, view, or table that is referenced by a No No
procedure, view.

sysindexes One row for each clustered or nonclustered index, and one row for Yes Yes
each table with no indexes, and an additional row for each table
containing text or image data. In SAP IQ, use the owner name dbo
when querying, i.e. dbo.sysindexes.

sysiqobjects One row for each system table, user table, view, procedure, trigger, Yes Yes
event, constraint, domain (sysdomain), domain (sysusertype), col­
umn, and index.

sysiqvindex One row for each non-fp iq index. Yes Yes

syskeys One row for each primary, foreign, or common key; set by user (not No No
maintained by SAP ASE).

syslogs Transaction log. No No

SAP IQ SQL Reference


1114 INTERNAL System Tables and Views
Supported
Table Name Description Data? by SAP IQ?

sysobjects One row for each table, view, procedure, rule, default, log, and (in Contains Yes
tempdb only) temporary object. compatible
data only

sysprocedures One row for each view, rule, default, and procedure, giving internal No No
definition.

sysprotects User permissions information. No No

sysreferences One row for each referential integrity constraint declared on a table No No
or column.

sysroles Maps server-wide roles to local database groups. No No

syssegments One row for each segment (named collection of disk pieces). No No

systhresholds One row for each threshold defined for the database. No No

systypes One row for each system-supplied and user-defined data type. Yes Yes

sysusers One row for each user allowed in the database. Yes Yes

Related Information

SYSCOLUMNS ASE Compatibility View [page 1012]


SYSCOMMENTS ASE Compatibility View [page 1012]
SYSINDEXES ASE Compatibility View [page 1032]
SYSIQOBJECTS ASE Compatibility View [page 1046]
SYSIQVINDEX ASE Compatibility View [page 1051]
SYSOBJECTS ASE Compatibility View [page 1058]
SYSTYPES ASE Compatibility View [page 1103]
SYSUSERS ASE Compatibility View [page 1109]

8.2.3.160.2 Tables in the SAP ASE Master Database

Not all SAP Adaptive Server Enterprise master database tables are implemented in the SAP IQ system catalog.

Supported
Table Name Description Data? by SAP IQ?

syscharsets One row for each character set or sort order No No

sysconfigures One row for each configuration parameter that can be set by a user No No

syscurconfigs Information about configuration parameters currently being used No No


by the server

sysdatabases One row for each database on the server No No

SAP IQ SQL Reference


System Tables and Views INTERNAL 1115
Supported
Table Name Description Data? by SAP IQ?

sysdevices One row for each tape dump device, disk dump device, disk for da­ No No
tabases, and disk partition for databases

sysengines One row for each server currently online No No

syslanguages One row for each language (except U.S. English) known to the No No
server

syslocks Information about active locks No No

sysloginroles One row for each server login that possesses a system-defined role No No

syslogins One row for each valid user account Yes Yes

sysmessages One row for each system error or warning No No

sysprocesses Information about server processes No No

sysremotelogins One row for each remote user No No

syssrvroles One row for each server-wide role No No

sysservers One row for each remote server No No

sysusages One row for each disk piece allocated to a database No No

8.2.3.160.3 Tables in the SAP ASE Sybsecurity Database

No SAP Adaptive Server Enterprise sybsecurity database tables are implemented in the SAP IQ system
catalog.

Supported
Table Name Description Data? by SAP IQ?

sysaudits One row for each audit record No No

sysauditoptions One row for each global audit option No No

SAP IQ SQL Reference


1116 INTERNAL System Tables and Views
9 SQL Statements

Descriptions of the SQL statements available in SAP IQ, including some that can be used only from Embedded
SQL or Interactive SQL.

In this section:

Common Elements in SQL Syntax [page 1117]


Language elements that are found in the syntax of many SQL statements.

Syntax Conventions [page 1118]


Conventions used in the SQL syntax descriptions.

Statement Applicability Indicators [page 1119]


Some statement titles are followed by an indicator in square brackets that shows where the statement
can be used.

Alphabetical List of Statements [page 1119]


This section describes each SQL statement individually.

9.1 Common Elements in SQL Syntax

Language elements that are found in the syntax of many SQL statements.

● column-name – an identifier that represents the name of a column.


● condition – an expression that evaluates to TRUE, FALSE, or UNKNOWN.
● connection-name – a string representing the name of an active connection.
● data-type – a storage data type.
● expression – an expression.
● filename – a string containing a file name.
● host-variable – a C language variable, declared as a host variable, preceded by a colon.
● indicator-variable – a second host variable of type short int immediately following a normal host
variable. An indicator variable must also be preceded by a colon. Indicator variables are used to pass NULL
values to and from the database.
● number – any sequence of digits followed by an optional decimal part and preceded by an optional
negative sign. Optionally, the number can be followed by an ‘e’ and then an exponent. For example,

42
-4.038
.001
3.4e10
1e-10

● owner – an identifier representing the user ID who owns a database object.


● role-name – an identifier representing the role name of a foreign key.
● savepoint-name – an identifier that represents the name of a savepoint.

SAP IQ SQL Reference


SQL Statements INTERNAL 1117
● search-condition – a condition that evaluates to TRUE, FALSE, or UNKNOWN.
● special-value – one of the special values described in Special Values [page 84]one of the special values
described in Special Values .
● statement-label – an identifier that represents the label of a loop or compound statement.
● table-list – a list of table names, which might include correlation names. For more information, see FROM
clause.
● table-name – an identifier that represents the name of a table.
● userid – an identifier representing a user name. The user ID is not case-sensitive and is unaffected by the
setting of the CASE RESPECT property of the database.
● variable-name – an identifier that represents a variable name.

Related Information

FROM Clause [page 1483]


Identifiers [page 34]
Search Conditions [page 57]
Expressions [page 40]
Strings [page 38]

9.2 Syntax Conventions

Conventions used in the SQL syntax descriptions.

Keywords

All SQL keywords appear in UPPERCASE; however, SQL keywords are case-insensitive, so you can type
keywords in any case. For example, SELECT is the same as Select, which is the same as select.
Placeholders

Items that must be replaced with appropriate identifiers or expressions are shown in <italics>.
Continuation

Lines beginning with an ellipsis ( … ) are a continuation from the previous line.
Optional portions

Optional portions of a statement are enclosed by square brackets. For example:

RELEASE SAVEPOINT [ savepoint-name ]

This example indicates that the <savepoint-name> is optional. Do not type the square brackets.
Repeating items

SAP IQ SQL Reference


1118 INTERNAL SQL Statements
Lists of repeating items are shown with an element of the list followed by an ellipsis. One or more list
elements are allowed. When more than one is specified, they must be separated by commas if indicated as
such. For example:

UNIQUE ( column-name [ , ... ] )

The example indicates that you can specify <column-name> more than once, separated by commas. Do
not type the square brackets.

Alternatives

When one option must be chosen, the alternatives are enclosed in curly braces. For example:

[ QUOTES { ON | OFF } ]

The example indicates that if you choose the QUOTES option, you must provide one of ON or OFF. Do not
type the braces.
One or more options

If you choose more than one, separate your choices by commas. For example:

{ CONNECT, DBA, RESOURCE }

9.3 Statement Applicability Indicators


Some statement titles are followed by an indicator in square brackets that shows where the statement can be
used.

These indicators are as follows:

● [ESQL] – the statement is for use in Embedded SQL.


● [Interactive SQL] – the statement is for use only in Interactive SQL (dbisql).
● [SP] – the statement is for use in stored procedures or batches.
● [T-SQL] – the statement is implemented for compatibility with SAP Adaptive Server Enterprise. In some
cases, the statement cannot be used in stored procedures that are not Transact-SQL format. In other
cases, there is an alternative statement that is closer to the ISO/ANSI SQL standard that is recommended
unless Transact-SQL compatibility is an issue.

If two sets of brackets are used, the statement can be used in both environments. For example, [ESQL] [SP]
means a statement can be used either in Embedded SQL or in stored procedures.

9.4 Alphabetical List of Statements


This section describes each SQL statement individually.

In this section:

ALLOCATE DESCRIPTOR Statement [ESQL] [page 1131]

SAP IQ SQL Reference


SQL Statements INTERNAL 1119
Allocates space for a SQL descriptor area (SQLDA).

ALTER AGENT Statement [page 1133]


Modifies connection information for the SAP IQ agent.

ALTER DATABASE Statement [page 1134]


Upgrades a database created with a previous version of the software, adds or removes jConnect for
JDBC support, or defines management of system procedure execution. Run this statement with
DBISQL Interactive SQL.

ALTER DBSPACE Statement [page 1136]


Changes the read/write mode, changes the size, or extends an existing dbspace.

ALTER DOMAIN Statement [page 1141]


Renames a user-defined domain or data type.

ALTER EVENT Statement [page 1142]


Changes the definition of an event or its associated handler for automating predefined actions. Also
alters the definition of scheduled actions.

ALTER FUNCTION Statement [page 1144]


Modifies an existing function. Include the entire modified function in the ALTER FUNCTION statement.

ALTER INDEX Statement [page 1147]


Renames indexes in base or global temporary tables, foreign key role names of indexes and foreign keys
explicitly created by a user, or changes the clustered nature of an index on a catalog store table. You
cannot rename indexes created to enforce key constraints.

ALTER LDAP SERVER Statement [page 1151]


Any changes to an LDAP server configuration object are applied on subsequent connections. Any
connection already started when the change is applied does not immediately reflect the change.

ALTER LOGICAL SERVER Statement [page 1153]


Modifies configuration for the existing user-defined logical server in the database. This statement
enforces consistent shared system temporary store settings across physical nodes shared by logical
servers.

ALTER LOGIN POLICY Statement [page 1155]


Changes existing login policies or configures logical server access.

ALTER LS POLICY Statement [page 1158]


Modifies some or all option values for the root logical server policy or a user-created logical server
policy. This statement enforces consistent shared system temporary store settings across physical
nodes shared by logical servers.

ALTER MULTIPLEX RENAME Statement [page 1160]


Renames the multiplex and stores the multiplex name in SYS.ISYSIQINFO system table.

ALTER MULTIPLEX SERVER Statement [page 1161]


Changes the name, catalog file path, role, or status of the given server.

ALTER PROCEDURE Statement [page 1163]


Replaces an existing procedure with a modified version. Include the entire modified procedure in the
ALTER PROCEDURE statement, and reassign user permissions on the procedure.

ALTER ROLE Statement [page 1166]


Migrates a compatibility role to a user-defined system role, then automatically drops the compatibility
role.

SAP IQ SQL Reference


1120 INTERNAL SQL Statements
ALTER SEQUENCE statement [page 1168]
Alters a sequence. This statement applies to SAP IQ catalog store tables only.

ALTER SERVER Statement [page 1170]


Modifies the attributes of a remote server. Changes made by ALTER SERVER do not take effect until
the next connection to the remote server.

ALTER SERVICE Statement [page 1173]


Causes the database server to act as a Web server

ALTER SPATIAL REFERENCE SYSTEM Statement [page 1176]


Changes the settings of an existing spatial reference system.

ALTER TABLE Statement [page 1181]


Modifies a table definition.

ALTER TEXT CONFIGURATION Statement [page 1196]


Alters a text configuration object.

ALTER TEXT INDEX Statement [page 1199]


Renames, moves or alters the definition of a TEXT index.

ALTER TRIGGER statement [page 1201]


Replaces a trigger definition with a modified version. You must include the entire new trigger definition
in the ALTER TRIGGER statement. This statement applies to SAP IQ catalog store tables only.

ALTER USER Statement [page 1203]


Changes user settings.

ALTER VIEW Statement [page 1207]


Replaces a view definition with a modified version.

BACKUP DATABASE Statement [page 1212]


Backs up an SAP IQ database on one or more archive devices.

BEGIN … END Statement [page 1218]


Groups SQL statements together.

BEGIN PARALLEL IQ … END PARALLEL IQ Statement [page 1221]


Groups CREATE INDEX statements together for execution at the same time.

BEGIN TRANSACTION Statement [T-SQL] [page 1223]


Use this statement to begin a user-defined transaction.

CALL Statement [page 1225]


Invokes a procedure.

CASE Statement [page 1228]


The CASE statement is a control statement that lets you choose a list of SQL statements to execute
based on the value of an expression.

CHECKPOINT Statement [page 1229]


Checkpoints the database.

CLEAR Statement [Interactive SQL] [page 1230]


Closes any open result sets in Interactive SQL (dbisql).

CLOSE Statement [ESQL] [SP] [page 1231]


Closes a named cursor.

COMMENT Statement [page 1233]

SAP IQ SQL Reference


SQL Statements INTERNAL 1121
Stores a comment, in the system tables, about a database object.

COMMIT Statement [page 1238]


Makes changes to the database permanent, or terminates a user-defined transaction.

CONFIGURE Statement [Interactive SQL] [page 1240]


Activates the Interactive SQL (dbisql) configuration window.

CONNECT Statement [ESQL] [Interactive SQL] [page 1241]


Establishes a connection to the database identified by <database-name> running on the server
identified by <engine-name>.

CREATE AGENT Statement [page 1244]


Associates an SAP IQ agent for SAP IQ Cockpit with the named server to support high availability.

CREATE DATABASE Statement [page 1245]


Creates a database consisting of several operating system files.

CREATE DBSPACE Statement [page 1254]


Creates a new dbspace and the associated dbfiles for the IQ main store, cache dbspace, catalog store,
or RLV store.

CREATE DOMAIN Statement [page 1259]


Creates a user-defined data type in the database.

CREATE EVENT Statement [page 1262]


Defines an event and its associated handler for automating predefined actions. Also defines scheduled
actions.

CREATE EXISTING TABLE Statement [page 1267]


Creates a new proxy table that represents an existing table on a remote server.

CREATE EXTERNLOGIN Statement [page 1271]


Assigns an alternate login name and password to be used when communicating with a remote server.

CREATE FUNCTION Statement [page 1273]


Creates a user-defined function in the database. A function can be created for another user by
specifying an owner name. Subject to permissions, a user-defined function can be used in exactly the
same way as other non-aggregate functions.

CREATE INDEX Statement [page 1294]


Creates an index on a specified table, or pair of tables. Once an index is created, it is never referenced in
a SQL statement again except to delete it using the DROP INDEX statement.

CREATE LDAP SERVER Statement [page 1301]


Creates a new LDAP server configuration object for LDAP user authentication. Parameters defined
during the creation of an LDAP server configuration object are stored in the ISYSLDAPSERVER (system
view SYSLDAPSERVER) system table.

CREATE LOGICAL SERVER Statement [page 1305]


Creates a user-defined logical server. This statement enforces consistent shared system temporary
store settings across physical nodes shared by logical servers.

CREATE LOGIN POLICY Statement [page 1307]


Creates a login policy in the database.

CREATE LS POLICY Statement [page 1313]


Creates a user-defined logical server policy. This statement enforces consistent shared system
temporary store settings across physical nodes shared by logical servers.

SAP IQ SQL Reference


1122 INTERNAL SQL Statements
CREATE MESSAGE Statement [T-SQL] [page 1315]
Adds a user-defined message to the SYSUSERMESSAGES system table for use by PRINT and
RAISERROR statements.

CREATE MULTIPLEX SERVER Statement [page 1317]


Creates a multiplex server.

CREATE MUTEX statement [page 1319]


Creates or replaces a mutex (lock) that can be used to lock a resource such as a file or a procedure.

CREATE PROCEDURE Statement [page 1321]


Creates a new user-defined SQL procedure in the database.

CREATE ROLE Statement [page 1354]


Creates a new role, extends an existing user to act as a role, or manages role administrators on a role.

CREATE SCHEMA Statement [page 1357]


Creates a schema, which is a collection of tables, views, and permissions and their associated
permissions, for a database user.

CREATE SEMAPHORE statement [page 1358]


Creates or replaces a semaphore and establishes the initial value for its counter. A semaphore is a
locking mechanism that uses a counter to communicate and control the availability of a resource such
as an external library or procedure.

CREATE SEQUENCE statement [page 1361]


Creates a sequence that can be used to generate primary key values that are unique across multiple
tables, and for generating default values for a table. This statement applies to SAP IQ catalog store
tables only.

CREATE SERVER Statement [page 1363]


Adds a server to the ISYSSERVER table.

CREATE SERVICE Statement [page 1365]


Permits a database server to act as a Web server.

CREATE SPATIAL REFERENCE SYSTEM Statement [page 1368]


Creates or replaces a spatial reference system.

CREATE SPATIAL UNIT OF MEASURE Statement [page 1375]


Creates or replaces a spatial unit of measurement.

CREATE TABLE Statement [page 1377]


Creates a new table in the database or on a remote server.

CREATE TEXT CONFIGURATION Statement [page 1392]


Creates a text configuration object.

CREATE TEXT INDEX Statement [page 1393]


Creates a TEXT index and specifies the text configuration object to use.

CREATE TRIGGER statement [page 1395]


Creates a trigger on a table. This statement applies to SAP IQ catalog store tables only.

CREATE USER Statement [page 1402]


Creates a user.

CREATE VARIABLE Statement [page 1404]


Creates data type or a connection- or database-scope variable.

SAP IQ SQL Reference


SQL Statements INTERNAL 1123
CREATE VIEW Statement [page 1408]
Creates a view on the database. Views are used to give a different perspective on the data even though
it is not stored that way.

DEALLOCATE DESCRIPTOR Statement [ESQL] [page 1411]


Frees memory associated with a SQL descriptor area.

Declaration Section [ESQL] [page 1412]


Declares host variables in an Embedded SQL program. Host variables are used to exchange data with
the database.

DECLARE Statement [page 1413]


Declares a SQL variable within a compound statement (BEGIN... END).

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


Declares a cursor. Cursors are the primary means for manipulating the results of queries.

DECLARE CURSOR Statement [T-SQL] [page 1420]


Declares a cursor that is compatible with SAP Adaptive Server Enterprise.

DECLARE LOCAL TEMPORARY TABLE Statement [page 1422]


Declares a local temporary table.

DELETE Statement [page 1424]


Deletes all the rows from the named table that satisfy the search condition. If no WHERE clause is
specified, all rows from the named table are deleted.

DELETE (Positioned) Statement [ESQL] [SP] [page 1427]


Deletes the data at the current location of a cursor.

DESCRIBE Statement [ESQL] [page 1429]


Gets information about the host variables required to store data retrieved from the database or host
variables used to pass data to the database.

DISCONNECT Statement [Interactive SQL] [page 1432]


Drops a connection with the database.

DROP Statement [page 1433]


Removes objects from the database.

DROP AGENT Statement [page 1437]


Deletes an SAP IQ agent for SAP IQ Cockpit.

DROP CONNECTION Statement [page 1438]


Drops any user connection to the database.

DROP DATABASE Statement [page 1439]


Drops a database and its associated dbspace segment files.

DROP EXTERNLOGIN Statement [page 1441]


Drops an external login from the SAP IQ system tables.

DROP LDAP SERVER Statement [page 1443]


Removes the named LDAP server configuration object from the SYSLDAPSERVER system view after
verifying that the LDAP server configuration object is not in a READY or ACTIVE state.

DROP LOGICAL SERVER Statement [page 1444]


Drops a user-defined logical server. This statement enforces consistent shared system temporary store
settings across physical nodes shared by logical servers.

SAP IQ SQL Reference


1124 INTERNAL SQL Statements
DROP LOGIN POLICY Statement [page 1445]
Removes a login policy from the database.

DROP LS POLICY Statement [page 1446]


Removes a logical server policy from the multiplex.

DROP MULTIPLEX SERVER Statement [page 1447]


Deletes a server from the multiplex.

DROP MUTEX statement [page 1449]


Drops the specified mutex.

DROP ROLE Statement [page 1450]


Removes a user-defined role from the database or converts a user-extended role to a regular user.

DROP SEMAPHORE statement [page 1452]


Drops a semaphore.

DROP SEQUENCE statement [page 1454]


Drops a sequence. This statement applies to SAP IQ catalog store tables only.

DROP SERVER Statement [page 1455]


Drops a remote server from the SAP IQ system tables.

DROP SERVICE Statement [page 1456]


Deletes a Web service.

DROP SPATIAL REFERENCE SYSTEM Statement [page 1457]


Drops a spatial reference system.

DROP SPATIAL UNIT OF MEASURE Statement [page 1458]


Drops a spatial unit of measurement.

DROP STATEMENT Statement [ESQL] [page 1459]


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.

DROP TEXT CONFIGURATION Statement [page 1460]


Drops a text configuration object.

DROP TEXT INDEX Statement [page 1462]


Removes a TEXT index from the database.

DROP TRIGGER statement [page 1463]


Removes a trigger from the database. This statement applies to SAP IQ catalog store tables only.

DROP USER Statement [page 1464]


Removes a user.

DROP VARIABLE statement [page 1466]


Drops a SQL variable.

EXECUTE Statement [ESQL] [page 1467]


Executes a SQL statement.

EXECUTE Statement [T-SQL] [page 1469]


Invokes a procedure, as an SAP Adaptive Server Enterprise-compatible alternative to the CALL
statement.

EXECUTE IMMEDIATE Statement [ESQL] [SP] [page 1471]

SAP IQ SQL Reference


SQL Statements INTERNAL 1125
Extends the range of statements that can be executed from within procedures. It lets you execute
dynamically prepared statements, such as statements that are constructed using the parameters
passed in to a procedure.

EXIT Statement [Interactive SQL] [page 1473]


Leaves Interactive SQL.

FETCH Statement [ESQL] [SP] [page 1475]


Retrieves one row from the named cursor. The cursor must have been previously opened.

FOR Statement [page 1479]


Repeats the execution of a statement list once for each row in a cursor.

FORWARD TO Statement [page 1481]


Sends native syntax to a remote server, enabling users to specify the server to which a passthrough
connection is required.

FROM Clause [page 1483]


Specifies the database tables or views involved in a SELECT statement.

GET DESCRIPTOR Statement [ESQL] [page 1491]


Retrieves information about variables within a descriptor area, or retrieves actual data from a variable
in a descriptor area.

GOTO Statement [T-SQL] [page 1492]


Branches to a labeled statement.

GRANT CHANGE PASSWORD Privilege Statement [page 1494]


Allows users to manage passwords for other users and administer the CHANGE PASSWORD system
privilege.

GRANT CONNECT Privilege Statement [page 1496]


Create a new user, and can also be used to change a password. However, it is recommended that you
use the CREATE USER statement to create users instead of the GRANT CONNECT statement.

GRANT CREATE Privilege Statement [page 1498]


Grants CREATE privilege on a specified dbspace to the specified users and roles.

GRANT EXECUTE Privilege Statement [page 1499]


Grants EXECUTE privilege on a procedure or user-defined function.

GRANT INTEGRATED LOGIN Statement [page 1500]


Creates an explicit integrated login mapping between one or more Windows user profiles and an
existing database user ID. This allows a user who successfully logged in to their local machine to
connect to a database without having to provide a user ID or password.

GRANT KERBEROS LOGIN Statement [page 1501]


Creates a Kerberos-authenticated login mapping from one or more Kerberos principals to an existing
database user ID. This allows a user who has successfully logged in to Kerberos (user who has a valid
Kerberos ticket-granting ticket) to connect to a database without having to provide a user ID or
password.

GRANT Object-Level Privilege Statement [page 1502]


Grants database object-level privileges on individual tables or views to a user or role.

GRANT ROLE Statement [page 1504]


Grants roles to users or other roles, with or without administrative rights.

GRANT SET USER Privilege Statement [page 1509]

SAP IQ SQL Reference


1126 INTERNAL SQL Statements
Grants the ability for one user to impersonate another user and to administer the SET USER system
privilege.

GRANT System Privilege Statement [page 1511]


Grants specific system privileges to users or roles, with or without administrative rights.

GRANT USAGE ON SEQUENCE Privilege Statement [page 1528]


Grants the USAGE system privilege on a specified sequence to a user or role.

IF Statement [page 1529]


Lets you conditionally execute the first list of SQL statements whose <search-condition> evaluates
to TRUE.

IF Statement [T-SQL] [page 1531]


Provides conditional execution of a Transact-SQL statement, as an alternative to the SAP IQ IF
statement.

INCLUDE Statement [ESQL] [page 1532]


Includes a file into a source program to be scanned by the SQL source language preprocessor.

INSERT Statement [page 1534]


Inserts a single row or a selection of rows, from elsewhere in the current database, into the table. This
command can also insert a selection of rows from another database into the table.

INSTALL JAVA Statement [page 1541]


Makes Java classes available for use within a database.

IQ UTILITIES Statement [page 1544]


Starts a cache monitor that collects buffer cache statistics.

LEAVE Statement [page 1547]


Continues execution by leaving a compound statement or LOOP.

LOAD TABLE Statement [page 1549]


Imports data into a database table from an external file.

LOCK MUTEX statement [page 1570]


Locks a resource such as a file or system procedure using a predefined mutex.

LOCK TABLE Statement [page 1572]


Prevents other concurrent transactions from accessing or modifying a table within the specified time
or lock released by earlier transaction.

LOOP Statement [page 1576]


Repeats the execution of a statement list.

MESSAGE Statement [page 1577]


Displays a message, which can be any expression. Clauses can specify where the message is displayed.

NOTIFY SEMAPHORE statement [page 1580]


Increments the counter associated with a semaphore.

OPEN Statement [ESQL] [SP] [page 1582]


Opens a previously declared cursor to access information from the database.

OUTPUT Statement [Interactive SQL] [page 1585]


Writes the information retrieved by the current query to a file.

PARAMETERS Statement [Interactive SQL] [page 1589]


Specifies parameters to an Interactive SQL (dbisql) command file.

SAP IQ SQL Reference


SQL Statements INTERNAL 1127
PREPARE Statement [ESQL] [page 1590]
Prepares a statement to be executed later or used for a cursor.

PRINT Statement [T-SQL] [page 1593]


Displays a message on the message window of the database server.

PUT Statement [ESQL] [page 1595]


Inserts a row into the specified cursor.

RAISERROR Statement [T-SQL] [page 1597]


Allows user-defined errors to be signaled, and sends a message on the client.

READ Statement [Interactive SQL] [page 1598]


Reads Interactive SQL (dbisql) statements from a file.

REFRESH TEXT INDEX Statement [page 1601]


Refreshes a text index.

RELEASE MUTEX statement [page 1603]


Releases the specified connection-scope mutex, if it is locked by the current connection.

RELEASE SAVEPOINT Statement [page 1604]


Releases a savepoint within the current transaction.

REMOVE Statement [page 1605]


Removes a class, a package, or a JAR file from a database. Removed classes are no longer available for
use as a variable type. Any class, package, or JAR to be removed must already be installed.

RESIGNAL Statement [page 1607]


Resignals an exception condition.

RESTORE DATABASE Statement [page 1608]


Restores an SAP IQ database backup from one or more archive devices.

RESUME Statement [page 1618]


Resumes execution of a procedure that returns result sets.

RETURN Statement [page 1620]


Exits a function or procedure unconditionally, optionally providing a return value. Statements following
RETURN are not executed.

REVOKE CHANGE PASSWORD Privilege Statement [page 1621]


Removes the ability of a user to manage passwords and administer the system privilege.

REVOKE CONNECT Privilege Statement [page 1623]


Removes a user from the database.

REVOKE CREATE Privilege Statement [page 1624]


Removes CREATE privileges on the specified dbspace from the specified user IDs.

REVOKE EXECUTE Privilege Statement [page 1625]


Removes EXECUTE permissions that were given using the GRANT statement.

REVOKE INTEGRATED LOGIN Statement [page 1626]


Removes the INTEGRATED LOGIN permissions that were given using the GRANT statement.

REVOKE KERBEROS LOGIN Statement [page 1627]


Removes KERBEROS LOGIN permissions that were given using the GRANT statement.

REVOKE Object-Level Privilege Statement [page 1628]


Removes object-level privileges that were given using the GRANT statement.

SAP IQ SQL Reference


1128 INTERNAL SQL Statements
REVOKE ROLE Statement [page 1630]
Removes a users membership in a role or his or her ability to administer the role.

REVOKE SET USER Privilege Statement [page 1633]


Removes the ability for one user to impersonate another user and to administer the SET USER system
privilege.

REVOKE System Privilege Statement [page 1635]


Removes specific system privileges from specific users and the right to administer the privilege.

REVOKE USAGE ON SEQUENCE Privilege Statement [page 1653]


Removes USAGE privilege on a specified sequence.

ROLLBACK Statement [page 1654]


Undoes any changes made since the last COMMIT or ROLLBACK.

ROLLBACK TO SAVEPOINT Statement [page 1655]


Cancels any changes made since a savepoint was established. Changes made prior to the savepoint
are not undone; they are still pending.

ROLLBACK TRANSACTION Statement [T-SQL] [page 1656]


Cancels any changes made since a savepoint was established using SAVE TRANSACTION. Changes
made prior to the SAVE TRANSACTION are not undone; they are still pending.

SAVE TRANSACTION Statement [T-SQL] [page 1657]


Establishes a savepoint within the current transaction.

SAVEPOINT Statement [page 1658]


Establishes a savepoint within the current transaction.

SELECT Statement [page 1659]


Retrieves information from the database.

SET Statement [ESQL] [page 1670]


Assigns a value to a SQL variable.

SET Statement [T-SQL] [page 1673]


Sets database options in an SAP Adaptive Server Enterprise-compatible manner.

SET CONNECTION Statement [ESQL] [Interactive SQL] [page 1675]


Changes the active database connection.

SET DESCRIPTOR Statement [ESQL] [page 1676]


Describes the variables in a SQL descriptor area, and places data into the descriptor area.

SET OPTION Statement [page 1677]


Changes options that affect the behavior of the database and its compatibility with Transact-SQL.
Setting the value of an option can change the behavior for all users or an individual user, in either a
temporary or permanent scope.

SET OPTION Statement [Interactive SQL] [page 1680]


Changes Interactive SQL (dbisql) options.

SET SQLCA Statement [ESQL] [page 1681]


Tells the SQL preprocessor to use a SQLCA other than the default global <sqlca>.

SETUSER Statement [page 1682]


Allows a user to temporarily assume the roles and system privileges of another user (also known as
impersonation) to perform operations, provided they already have the minimum required privileges to
perform the task to begin with.

SAP IQ SQL Reference


SQL Statements INTERNAL 1129
SIGNAL Statement [page 1684]
Lets you raise an exception condition.

START DATABASE Statement [Interactive SQL] [page 1685]


Starts a database on the specified database server.

START ENGINE Statement [Interactive SQL] [page 1687]


Starts a database server.

START EXTERNAL ENVIRONMENT statement [page 1688]


Starts an external environment.

START JAVA Statement [page 1689]


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

STOP DATABASE Statement [Interactive SQL] [page 1690]


Stops a database on the specified database server.

STOP ENGINE Statement [Interactive SQL] [page 1691]


Stops a database server.

STOP EXTERNAL ENVIRONMENT statement [page 1692]


Stops an external environment.

STOP JAVA Statement [page 1694]


Releases resources associated with the Java VM to economize on the use of system resources.

TRIGGER EVENT Statement [page 1694]


Triggers a named event. The event may be defined for event triggers or be a scheduled event.

TRUNCATE Statement [page 1695]


Deletes all rows from a table or materialized view without deleting the table definition.

TRUNCATE TEXT INDEX Statement [page 1697]


Deletes the data in a MANUAL or an AUTO REFRESH text index.

UNION Statement [page 1699]


Combines the results of two or more select statements.

UPDATE Statement [page 1700]


Modifies existing rows of a single table, or a view that contains only one table.

UPDATE (Positioned) Statement [ESQL] [SP] [page 1705]


Modifies the data at the current location of a cursor.

VALIDATE Statement [page 1707]


Validates the current database, or a single table, materialized view, or index in the IQ catalog (system)
store.

VALIDATE LDAP SERVER Statement [page 1709]


Validates changes to the settings of existing LDAP server configuration objects before applying them.

WAITFOR Statement [page 1713]


Delays processing for the current connection for a specified amount of time or until a given time.

WAITFOR SEMAPHORE statement [page 1715]


Decrements the counter associated with a semaphore.

WHENEVER Statement [ESQL] [page 1717]


Specifies error handling in an Embedded SQL program.

SAP IQ SQL Reference


1130 INTERNAL SQL Statements
WHILE Statement [T-SQL] [page 1718]
Provides repeated execution of a statement or compound statement.

9.4.1 ALLOCATE DESCRIPTOR Statement [ESQL]

Allocates space for a SQL descriptor area (SQLDA).

 Syntax

ALLOCATE DESCRIPTOR <descriptor-name>


… [ WITH MAX { <integer> | <host-variable> } ]

Parameters

descriptor-name Specifies the name of the descriptor.


WITH MAX { integer | host-variable }

Lets you specify the number of variables within the descriptor area. The default size is 1.

Remarks

You must declare the following in your C code prior to using this statement:

struct sqlda * descriptor_name

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.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

SAP IQ SQL Reference


SQL Statements INTERNAL 1131
Examples

This 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=<password>;DBF=d:\\IQ-16_1\
\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;
}
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;
}

Related Information

DEALLOCATE DESCRIPTOR Statement [ESQL] [page 1411]

SAP IQ SQL Reference


1132 INTERNAL SQL Statements
9.4.2 ALTER AGENT Statement

Modifies connection information for the SAP IQ agent.

 Syntax

ALTER AGENT FOR MULTIPLEX SERVER <server-name> <alter-options>

<alter-options> ::=
{PORT <portnum>
| USER <username> IDENTIFIED BY PASSWORD <agentpwd>, ... }

Parameters

alter-options

Specifies the port, user, and password for an SAP IQ Cockpit SAP IQ agent.

Remarks

Applies to multiplex only.

The SYS.ISYSIQMPXSERVERAGENT system table stores the agent connection definitions for the server.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

The following example alters the agent for server mpxdemo_svr2 by changing the password and port number
for user smit:

ALTER AGENT FOR MULTIPLEX SERVER mpxdemo_svr2 USER smith IDENTIFIED BY smith_pwd
PORT 1112

SAP IQ SQL Reference


SQL Statements INTERNAL 1133
Related Information

REVOKE System Privilege Statement [page 1635]

9.4.3 ALTER DATABASE Statement

Upgrades a database created with a previous version of the software, adds or removes jConnect for JDBC
support, or defines management of system procedure execution. Run this statement with DBISQL Interactive
SQL.

 Syntax

ALTER DATABASE UPGRADE


[ PROCEDURE ON ]
[ JCONNECT { ON | OFF } ]
[ RESTART { ON | OFF } ]
[ SYSTEM PROCEDURE AS DEFINER { ON | OFF} ]

Parameters

PROCEDURE ON

Drops and re-creates all dbo- and sys-owned procedures in the database. When executed via SQL and
passed to the connection as a batch command, the existing connection terminates and the next statement
in the batch is not executed. You must re-establish the connection after the command is executed and
execute any further SQL in the batch.
JCONNECT { ON | OFF }

Specify ON to allow the SAP IQ jConnect JDBC driver to access system catalog information. This installs
jConnect system tables and procedures. To exclude the jConnect system objects, specify OFF. You can still
use JDBC, as long as you do not access system catalog information. The default is to include jConnect
support (JCONNECT ON).
RESTART { ON | OFF }

When you specify ON (default) and the AutoStop connection parameter is set to NO, the database restarts
after it is upgraded. Otherwise, the database is stopped after an upgrade.
SYSTEM PROCEDURE AS DEFINER { ON | OFF }

Defines whether a privileged system procedure runs with the privileges of the invoker (the person
executing the procedure) or the definer (the owner of the procedure):

● OFF – all privileged system procedures execute with the privileges of the invoker. Use
sp_proc_priv() to identify the system privileges required to run a system procedure.
● ON (default), or not specified:
○ When upgrading a pre-16.0 database – pre-16.0 privileged system procedures execute with the
privileges of the definer and 16.0 or later privileged system procedures execute with the privileges
of the invoker.

SAP IQ SQL Reference


1134 INTERNAL SQL Statements
○ When upgrading a database that is version 16.0 or later – the default is the behavior of the
database being upgraded.

 Note

Changing the execution model after upgrade may result in loss of functionality on custom stored
procedures and applications that explicitly grant EXECUTE privilege on system procedures. It may also
impact the ability to run system procedures. See System Procedures [page 572].

Remarks

The ALTER DATABASE statement upgrades databases created with earlier versions of the software. This
applies to maintenance releases as well as major releases.

When you upgrade a database, SAP IQ makes these changes:

● Upgrades the system tables to the current version.


● Adds any new database options.
● Enables new features in the current version.

You can also use ALTER DATABASE UPGRADE simply to add jConnect features, if the database was created
with the current version of the software.

 Note

● See the SAP IQ Installation and Update Guide for backup recommendations before you upgrade.
● Be sure to start the server in a way that restricts user connections before you run ALTER DATABASE
UPGRADE. For instructions and other upgrade caveats, see the SAP IQ Installation and Update Guide for
your platform.
● Use the iqunload utility to upgrade databases created in versions earlier than 15.0. See the SAP IQ
Installation and Update Guide for your platform.

After using ALTER DATABASE UPGRADE, shut down the database.

 Note

For parameters that accept variable names, an error is returned if one of the following conditions is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

Requires the ALTER DATABASE system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

SAP IQ SQL Reference


SQL Statements INTERNAL 1135
Side Effects

Automatic commit

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example disables jConnect support:

ALTER DATABASE UPGRADE JCONNECT OFF

Related Information

CREATE DATABASE Statement [page 1245]


REVOKE System Privilege Statement [page 1635]

9.4.4 ALTER DBSPACE Statement

Changes the read/write mode, changes the size, or extends an existing dbspace.

 Syntax

ALTER DBSPACE <dbspace-name>


{ [ADD {<new-file-spec> [, <new-file-spec> ... ]
| DROP FILE <logical-file-name> [, FILE <logical-file-name> ... ]
| RENAME TO <newname> | RENAME '<new-file-pathname>'
| READONLY | READWRITE
| ONLINE | OFFLINE
| STRIPING { ON | OFF }
| STRIPESIZEKB <size-in-KB>
ALTER FILE <file-name>
{ READONLY | [ FORCE ] READWRITE }
| SIZE <file-size> [ KB | MB | GB | TB ]
| ADD <file-size> [ KB | MB | GB | TB | PAGES ] }
RENAME PATH '<new-file-pathname>'
RENAME TO <newname>

SAP IQ SQL Reference


1136 INTERNAL SQL Statements
<new-file-spec> ::=
FILE <logical-file-name> [ PATH ] '<file-path>' <iq-file-opts>

<iq-file-opts> ::=
[ [ SIZE ] <file-size> KB | MB | GB | TB ] ]
[ RESERVE <reserve-size> [ KB | MB | GB | TB ] ]

Parameters

ADD new-file-spec

Adds one or more files to the specified dbspace. The dbfile name and the physical file path are required for
each file and must be unique. You can add files to IQ main, IQ shared temporary, IQ temporary, or cache
dbspaces. You may add a file to a read-only dbspace, but the dbspace remains read-only. You can add files
to multiplex shared temporary dbspaces only in read-only mode (the default for ADD FILE).

A catalog dbspace may contain only one file, so ADD FILE may not be used on catalog dbspaces.

Use of ADD FILE differs based on dbspace type:

● An RLV dbspace – use ADD FILE on SAP IQ servers only. You cannot add a file to a multiplex RLV
dbspace.
● A cache dbspace – use ADD FILE on multiplex or SAP IQ servers.

When used in the ALTER FILE clause, extends the size of the file in units of pages, kilobytes (KB),
megabytes (MB), gigabytes (GB), or terabytes (TB). The default is MB. You can ADD only if the free list (an
allocation map) has sufficient room and if the dbspace has sufficient reserved space.
DROP FILE logical-file-name

Removes the specified file from a dbspace. The file must be empty. You cannot drop the last file from the
specified dbspace. Instead use DROP DBSPACE if the dbspace contains only one file.
RENAME TO newname

When used with the DROP FILE clause, renames the pathname of the dbspace that contains a single file. It
is semantically equivalent to the RENAME PATH clause. An error is returned if the dbspace contains more
than one file. You cannot rename IQ_SYSTEM_MAIN, IQ_SYSTEM_MSG, IQ_SYSTEM_TEMP,
IQ_SHARED_TEMP, or SYSTEM.

When used with the ALTER FILE clause, renames the specified file's logical name to a new name. The new
name must be unique in the database.
READONLY

When used with the DROP clause, changes any dbspace except IQ_SYSTEM_MAIN, IQ_SYSTEM_TEMP,
When used with the ALTER FILE clause, changes the specified file to read-only. The file must be associated
with an IQ main dbspace. You cannot change files in IQ_SYSTEM_MSG, IQ_SHARED_TEMP, and SYSTEM to
read-only. Disallows DML modifications to any object currently assigned to the dbspace. Can only be used
for the cache dbspace, and dbspaces in the IQ main store.

When used with the ALTER FILE clause, changes the specified file to READONLY status.
READWRITE

SAP IQ SQL Reference


SQL Statements INTERNAL 1137
When used with the DROP FILE clause, changes the dbspace to read-write. The dbspace must be online.
Can only be used for the cache dbspace, and dbspaces in the IQ main store.

When used with the ALTER FILE clause, changes the specified cache dbspace, IQ main, or temporary store
dbfile to read-write. The file must be associated with a cache dbspace, IQ main, or temporary dbspace.
ONLINE

Puts an offline dbspace and all associated files online if both the online value of the file's associated
dbspace and the online value of the file in SYS.ISYSIQDBFILE are true. Can only be used for dbspaces in
the cache dbspace and IQ main store.
OFFLINE

Puts an online read-only dbspace and all associated files offline. (Returns an error if the dbspace is read-
write, offline already, or not of the cache dbspace or IQ main store.) Can only be used for dbspaces in the
cache dbspace or IQ main store.
STRIPING

Changes the disk striping on the dbspace as specified. When disk striping is set ON, data is allocated from
each file within the dbspace in a round-robin fashion. For example, the first database page written goes to
the first file, the second page written goes to the next file within given dbspace, and so on. Read-only
dbspaces are skipped.
STRIPESIZEKB size-in-KB

Specifies the number of kilobytes (KB) to write to each file before the disk striping algorithm moves to the
next stripe for the specified dbspace.
FORCE READWRITE

When used with the ALTER FILE clause, changes the status of the specified shared temporary store dbfile
to read-write, although there may be known file status problems on secondary nodes. The file may be
associated with an IQ main, shared temporary, or temporary dbspace, but because new dbfiles in
IQ_SYSTEM_MAIN and user main are created read-write, this clause only affects shared temporary
dbspaces.
SIZE

Specifies the new size of the file in units of kilobytes (KB), megabytes (MB), gigabytes (GB), or terabytes
(TB). The default is megabytes. You can increase the size of the dbspace only if the free list (an allocation
map) has sufficient room and if the dbspace has sufficient reserved space. You can decrease the size of the
dbspace only if the portion to be truncated is not in use.
RENAME PATH

When used with the ALTER FILE clause, renames the file pathname associated with the specified file. This
clause merely associates the file with the new file path instead of the old path. The clause does not actually
change the operating system file name. You must change the file name through your operating system.

The dbspace must be OFFLINE to rename the file path. The new path is used when the dbspace is altered
ONLINE or when the database is restarted.

 Note

The renamed file path must be on the same server. If you rename the file path to a location on another
server, you will not be able to alter the dbspace ONLINE.

Enclose the physical file path to the dbfile in single quotation marks.

SAP IQ SQL Reference


1138 INTERNAL SQL Statements
You cannot rename the path of a file in IQ_SYSTEM_MAIN. If you need to rename the path of a file in
IQ_SYSTEM_MAIN, make the file read-only, empty the file, drop the file, and add the file again with the new
file path name.

Remarks

ALTER DBSPACE changes the read-write mode, changes the online/offline state, alters the file size, renames
the dbspace name, file logical name or file path, or sets the dbspace striping parameters. For details about
existing dbspaces, run sp_iqdbspace procedure, sp_iqdbspaceinfo procedure, sp_iqfile procedure,
sp_iqdbspaceobjectinfo, and sp_iqobjectinfo. Dbspace and dbfile names are always case-insensitive.
The physical file paths are case-sensitive, if the database is CASE RESPECT and the operating system supports
case-sensitive files. Otherwise, the file paths are case-insensitive.

You may optionally delimit dbspace and dbfile names with double quotation marks.

In Windows, if you specify a path, any backslash characters (\) must be doubled if they are followed by an n or
an x. This prevents them being interpreted as a newline character (\n) or as a hexadecimal number (\x),
according to the rules for strings in SQL. It is safer to always double the backslash.

Privileges

Requires the MANAGE ANY DBSPACE system privilege. See GRANT System Privilege Statement [page 1511]
for assistance with granting privileges.

Side Effects

● Automatic commit
● Automatic checkpoint
● A mode change to READONLY causes immediate relocation of the internal database structures on the
dbspace to one of the read-write dbspaces.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Statements INTERNAL 1139
Examples

● The following example changes the mode of a dbspace called DspHist:

ALTER DBSPACE DspHist READONLY

● The following example adds 500 MB to the dbspace DspHist by adding the file FileHist3 of size 500
MB:

ALTER DBSPACE DspHist


ALTER FILE FileHist3 ADD 500 MB

● On a UNIX system, the following example adds two 500 MB files to the dbspace DspHist:

ALTER DBSPACE DspHist ADD


FILE FileHist3 '/History1/data/file3' SIZE 500 MB,
FILE FileHist4 '/History1/data/file4' SIZE 500

● The following example increases the size of the dbspace IQ_SYSTEM_TEMP by 2 GB:

ALTER DBSPACE IQ_SYSTEM_TEMP ADD 2 GB

● The following example removes two files from dbspace DspHist (both files must be empty):

ALTER DBSPACE DspHist


DROP FILE FileHist2, FILE FileHist4

● The following example increases the size of the dbspace IQ_SYSTEM_MAIN by 1000 pages. (ADD clause
defaults to pages):

ALTER DBSPACE IQ_SYSTEM_MAIN ADD 1000

● The following example adds a file to the cache dbspace myDAS:

ALTER DBSPACE myDAS ADD FILE iqdas2 'sampledb.iqcache' size 1024

● The following example removes dbfile iqdas2 from the cache dbspace myDAS:

ALTER DBSPACE myDAS DROP FILE iqdas2

● The following example disables the cache dbspace myDAS:

ALTER DBSPACE myDAS OFFLINE

● The following example makes the myDAS cache dbspace dbfile iqdas2 read-only:

ALTER DBSPACE myDAS ALTER FILE iqdas2 READONLY

Related Information

CREATE DATABASE Statement [page 1245]


CREATE DBSPACE Statement [page 1254]
DROP Statement [page 1433]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1140 INTERNAL SQL Statements
9.4.5 ALTER DOMAIN Statement

Renames a user-defined domain or data type.

 Syntax

ALTER { DOMAIN | DATATYPE } <user-type>


RENAME <new-name>

Parameters

user-type

Specifies the user-defined data type of the domain being renamed.


RENAME new-name

Specifies an identifier representing the new domain name.

Remarks

The ALTER DOMAIN statement updates the name of the user-defined domain or data type in the
SYSUSERTYPE system table.

Re-create any procedures, views or events that reference the user-defined domain or data type, so they do not
continue to reference the former name.

Privileges

If you are the database user who created the domain no further privileges are required. If you are not the
creator, you require one of the following privileges:

● ALTER DATATYPE system privilege


● ALTER ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

Automatic commit

SAP IQ SQL Reference


SQL Statements INTERNAL 1141
Examples

The following example renames the Address domain to MailingAddress:

ALTER DOMAIN Address RENAME MailingAddress

Related Information

%TYPE and %ROWTYPE attributes [page 93]


CREATE DOMAIN Statement [page 1259]
REVOKE System Privilege Statement [page 1635]

9.4.6 ALTER EVENT Statement

Changes the definition of an event or its associated handler for automating predefined actions. Also alters the
definition of scheduled actions.

 Syntax

ALTER EVENT <event-name>


[ DELETE TYPE | TYPE <event-type> ]
{ WHERE { <trigger-condition> | NULL }
| { ADD | [ MODIFY ] | DELETE } SCHEDULE <schedule-spec>}
[ ENABLE | DISABLE ]
[ [ MODIFY ] HANDLER <compound-statement> | DELETE HANDLER}

<event-type> ::=
BackupEnd
| "Connect"
| ConnectFailed
| DatabaseStart
| DBDiskSpace
| "Disconnect"
| GlobalAutoincrement
| GrowDB
| GrowLog
| GrowTemp
| IQMainDBSpaceFree
| IQTempDBSpaceFree
| LogDiskSpace
| "RAISERROR"
| ServerIdle
| TempDiskSpace

<trigger-condition> ::=
event_condition( <condition-name> )
{ =
| <
| >
| !=
| <=
| >= } <value>

SAP IQ SQL Reference


1142 INTERNAL SQL Statements
<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> ]

Parameters

DELETE TYPE

Removes an association of the event with an event type.


ADD | MODIFY | DELETE SCHEDULE

Changes the definition of a schedule. Only one schedule can be altered in any one ALTER EVENT
statement.
WHERE

Determines the condition under which an event is fired. The WHERE NULL option deletes a condition. You
can specify a variable name for the event_condition value.

 Note

For other parameter descriptions, see the CREATE EVENT Statement.

Remarks

ALTER EVENT lets you alter an event definition created with CREATE EVENT. Possible uses include:

● Change an event handler during development.


● Define and test an event handler without a trigger condition or schedule during a development phase, and
then add the conditions for execution using ALTER EVENT once the event handler is completed.
● Disable an event handler temporarily by disabling the event.

When you alter an event using ALTER EVENT, specify the event name and, optionally, the schedule name.

Each event has a unique event ID. Use the event_id columns of SYSEVENT and SYSSCHEDULE to match the
event to the associated schedule.

 Note

For required parameters that accept variable names, an error is returned if one of the following conditions
is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

SAP IQ SQL Reference


SQL Statements INTERNAL 1143
Privileges

Requires one of:

● MANAGE ANY EVENT system privilege


● ALTER ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

Automatic commit

Examples

● The following example lists event names by querying the system table SYSEVENT:

SELECT event_id, event_name FROM SYS.SYSEVENT

● The following example lists schedule names by querying the system table SYSSCHEDULE:

SELECT event_id, sched_name FROM SYS.SYSSCHEDULE

Related Information

BEGIN … END Statement [page 1218]


CREATE EVENT Statement [page 1262]
REVOKE System Privilege Statement [page 1635]

9.4.7 ALTER FUNCTION Statement

Modifies an existing function. Include the entire modified function in the ALTER FUNCTION statement.

 Syntax

Syntax 1

ALTER FUNCTION [ <owner>.]<function-name> <function-definition>

<function-definition> ::= CREATE FUNCTION <syntax>

SAP IQ SQL Reference


1144 INTERNAL SQL Statements
Syntax 2

ALTER FUNCTION [ <owner>.]<function-name>


| SET HIDDEN
| RECOMPILE

Parameters

SET HIDDEN

Scrambles the definition of the associated function and causes it to become unreadable. The function can
be unloaded and reloaded into other databases.

 Caution

The SET HIDDEN clause setting is irreversible. If you need the original source again, you must maintain
it outside the database.

RECOMPILE

Recompiles a user-defined 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 scrambled by the SET HIDDEN clause remain scrambled
and unreadable.

Remarks

Syntax 1

Syntax 1 is identical in syntax to the CREATE FUNCTION statement except for the first word. Either version of
the CREATE FUNCTION statement can be altered. Existing permissions on the function are maintained and do
not have to be reassigned. If a DROP FUNCTION and CREATE FUNCTION were carried out, execute permissions
must be reassigned.

 Note

For required parameters that accept variable names, an error is returned if one of the following conditions
is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

SAP IQ SQL Reference


SQL Statements INTERNAL 1145
Privileges

The privilege required varies by function type. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Function Privilege Name

Alter a Watcom SQL or Transact-SQL func­ Require one of:


tion
● You own the Watcom SQL or Transact-SQL function
● ALTER ANY PROCEDURE system privilege
● ALTER ANY OBJECT system privilege

Alter an external C/C++ Scalar or Aggre­ Requires CREATE EXTERNAL REFERENCE system privilege.
gate, or external Java function
For external C/C++ Scalar or Aggregate, or external Java functions owned by
others, you also require one of:

● ALTER ANY PROCEDURE system privilege


● ALTER ANY OBJECT system privilege

Side Effects

Automatic commit

Standards

SQL – vendor extension to ISO/ANSI SQL grammar

Examples

The following example creates and then alters a function using a variable in the NAMESPACE clause

1. The following statements create a variable for a NAMESPACE clause:

CREATE VARIABLE @ns LONG VARCHAR ;


SET @ns = 'http://wsdl.domain.com/' ;

2. The following statement creates a function named FtoC that uses a variable in the NAMESPACE clause:

CREATE FUNCTION FtoC ( IN temperature LONG VARCHAR )


RETURNS LONG VARCHAR
URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'
NAMESPACE @ns;

SAP IQ SQL Reference


1146 INTERNAL SQL Statements
3. The following statement alters the function FtoC so that it accepts and returns a FLOAT data type:

ALTER FUNCTION FtoC ( IN temperature FLOAT )


RETURNS FLOAT
URL 'http://localhost:8082/FtoCService'
NAMESPACE @ns;

Related Information

%TYPE and %ROWTYPE attributes [page 93]


ALTER PROCEDURE Statement [page 1163]
CREATE FUNCTION Statement [page 1273]
DROP Statement [page 1433]
REVOKE System Privilege Statement [page 1635]

9.4.8 ALTER INDEX Statement

Renames indexes in base or global temporary tables, foreign key role names of indexes and foreign keys
explicitly created by a user, or changes the clustered nature of an index on a catalog store table. You cannot
rename indexes created to enforce key constraints.

 Syntax

ALTER { INDEX <index-name>


| [ INDEX ] FOREIGN KEY <role-name>
| [ INDEX ] PRIMARY KEY
| ON [<owner>.]<table-name> { <rename-clause> | <move-clause> | <cluster-
clause> }

<rename-clause> ::= RENAME TO | AS <new-name>

<move-clause> ::= MOVE TO <dbspace-name>

<cluster-clause> ::= CLUSTERED | NONCLUSTERED

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

SAP IQ SQL Reference


SQL Statements INTERNAL 1147
Parameters

(back to top)

ON [owner.]table-name

Specifies the name of the table that contains the index or foreign key to rename.
RENAME TO | AS new-name

Specifies the new name of the index or foreign key role.


MOVE TO dbspace-name

Moves the specified index, unique constraint, foreign key, or primary key to the specified dbspace. For
unique constraint or foreign key, you must specify its unique index name.
cluster-clause

Specifies whether the index should be changed to CLUSTERED or NONCLUSTERED. Applies to catalog
store tables only and only one index on a table can be clustered.

Remarks

(back to top)

You must have CREATE privilege on the new dbspace and be the table owner or have the MANAGE ANY
DBSPACE system privilege.

 Note

Attempts to alter an index in a local temporary table return the error index not found. Attempts to alter
a nonuser-created index, such as a default index (FP), return the error Cannot alter index. Only
indexes in base tables or global temporary tables with an owner type of USER can
be altered.

Privileges

(back to top)

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

SAP IQ SQL Reference


1148 INTERNAL SQL Statements
Clause Privilege Required

move-clause for materialized view Require one of:

● MANAGE ANY DBSPACE system privilege


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● You own the materialized view and also have one of:
○ CREATE ANY OBJECT system privilege
○ CREATE object-level privilege on the target dbspace.

move-clause for all other indexes Requires one of:

● MANAGE ANY DBSPACE system privilege


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● You own the underlying table or have REFERENCES object-level privilege
on the table, and you also have one of:
○ CREATE ANY OBJECT system privilege
○ CREATE object-privilege on the target dbspace.

cluster-clause for materialized view If , no additional privilege is required.

Requires one of:

● You own the materialized view


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege

cluster-clause for all other indexes Requires one of:

● You own the underlying table


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● REFERENCES object-level privilege on the table.

All other clauses Requires one of:

● You own the underlying table


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● REFERENCES object-level privilege on the table.

Side Effects

(back to top)

Automatic commit. Clears the Results tab in the Results pane in Interactive SQL. Closes all cursors for the
current connection.

SAP IQ SQL Reference


SQL Statements INTERNAL 1149
Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example moves the primary key, HG for c5, from dbspace Dsp4 to Dsp8:

CREATE TABLE foo (


c1 INT IN Dsp1,
c2 VARCHAR(20),
c3 CLOB IN Dsp2,
c4 DATE,
c5 BIGINT,
PRIMARY KEY (c5) IN Dsp4) IN Dsp3);
CREATE DATE INDEX c4_date ON foo(c4) IN Dsp5;
ALTER INDEX PRIMARY KEY ON foo MOVE TO Dsp8;

● The following example moves DATE index from Dsp5 to Dsp9:

ALTER INDEX c4_date ON foo MOVE TO Dsp9

● The following example rename an index COL1_HG_OLD in the table jal.mytable to COL1_HG_NEW:

ALTER INDEX COL1_HG_OLD ON jal.mytable


RENAME AS COL1_HG_NEW

● The following example rename a foreign key role name ky_dept_id in table dba.Employees to
emp_dept_id:

ALTER INDEX FOREIGN KEY ky_dept_id


ON dba.Employees
RENAME TO emp_dept_id

Related Information

sp_iqrename Procedure [page 744]


ALTER TABLE Statement [page 1181]
CREATE INDEX Statement [page 1294]
CREATE TABLE Statement [page 1377]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1150 INTERNAL SQL Statements
9.4.9 ALTER LDAP SERVER Statement

Any changes to an LDAP server configuration object are applied on subsequent connections. Any connection
already started when the change is applied does not immediately reflect the change.

 Syntax

ALTER LDAP SERVER <ldapua-server-name>


{ [ WITH ( SUSPEND | ACTIVATE | REFRESH ) ] }

<ldapua-server-attribs> ::=
SEARCH DN
URL { '<URL_string>' | NULL }
| ACCESS ACCOUNT { '<DN_string>' | NULL }
| IDENTIFIED BY { '<password>' | NULL }
| IDENTIFIED BY ENCRYPTED { <encrypted-password> | NULL }
| AUTHENTICATION URL { '<URL_string>' | NULL }
| CONNECTION TIMEOUT <timeout_value>
| CONNECTION RETRIES <retry_value>
| TLS { ON | OFF }

Parameters

URL { 'URL_string' | NULL }

Identifies the host (by name or by IP address), port number, and the search to be performed for the DN
lookup for a given user ID. This value is validated for correct LDAP URL syntax before it is stored in the
ISYSLDAPSERVER system table. The maximum size for this string is 1024 bytes.
ACCESS ACCOUNT { 'DN_string' | NULL }

User created in the LDAP server for use by SAP IQ, not a user within SAP IQ. The distinguished name (DN)
for this user is used to connect to the LDAP server. This user has permissions within the LDAP server to
search for DNs by user ID in the locations specified by the SEARCH DN URL. The maximum size for this
string is 1024 bytes.

IDENTIFIED BY { 'password' | NULL }

Provides the password associated with the ACCESS ACCOUNT user. The password is stored using
symmetric encryption on disk. Use the value NULL to clear the password and set it to none. The maximum
size of a clear text password is 255 bytes.

IDENTIFIED BY ENCRYPTED { encrypted-password | NULL }

Configures the password associated with the ACCESS ACCOUNT distinguished name in an encrypted
format. The binary value is the encrypted password and is stored on disk as is. Use the value NULL to clear
the password and set it to none. The maximum size of the binary is 289 bytes. The encrypted key should
be a valid varbinary value. Do not enclose the encrypted key in quotation marks.

AUTHENTICATION URL { 'URL_string' | NULL }

Identifies the host (by name or IP address) and the port number of the LDAP server to use for
authentication of the user. This is the value defined for URL_string and is validated for correct LDAP URL
syntax before it is stored in ISYSLDAPSERVER system table. The DN of the user obtained from a prior DN

SAP IQ SQL Reference


SQL Statements INTERNAL 1151
search and the user password bind a new connection to the authentication URL. A successful connection
to the LDAP server is considered proof of the identity of the connecting user. The maximum size for this
string is 1024 bytes.
CONNECTION TIMEOUT timeout_value

Specifies the connection timeout from SAP IQ to the LDAP server for both DN searches and
authentication. This value is in milliseconds, with a default value of 10 seconds.
CONNECTION RETRIES retry_value

Specifies the number of retries on connections from SAP IQ to the LDAP server for both DN searches and
authentication. The valid range of values is 1– 60, with a default value of 3.
TLS { ON | OFF }

Defines whether the TLS or Secure LDAP protocol is used for connections to the LDAP server for both DN
searches and authentication. When set to ON, the TLS protocol is used and the URL would begin with
"ldap://" When set to OFF (or not specified), Secure LDAP protocol is used and the URL begins with
“ldaps://”. When using the TLS protocol, specify the database security option
TRUSTED_CERTIFICATES_FILE with a file name containing the certificate of the Certificate Authority (CA)
that signed the certificate used by the LDAP server.
WITH ACTIVATE

Activates the LDAP server configuration object for immediate use upon creation. This permits the
definition and activation of LDAP User Authentication in one statement. The LDAP server configuration
object state changes to READY when WITH ACTIVATE is used.

Remarks

In addition to resetting LDAP server configuration object values for attributes, the ALTER LDAP SERVER
statement allows an administrator to make manual adjustments to a server's state and behavior by putting the
LDAP server configuration object in maintenance mode and returning it to service from maintenance mode.

Privileges

Requires the MANAGE ANY LDAP SERVER system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

SAP IQ SQL Reference


1152 INTERNAL SQL Statements
Examples

● The following example suspends the LDAP server configuration object named apps_primary:

ALTER LDAP SERVER apps_primary SUSPEND

● The following example changes the LDAP server configuration object named apps_primary to use a
different URL for authentication on host fairfax, sets the port number to 1066, sets the number of
connection retries to 10, and finally activates the LDAP server configuration object:

ALTER LDAP SERVER apps_primary


AUTHENTICATION URL 'ldap://my_LDAPserver:1066/'
CONNECTION RETRIES 10
WITH ACTIVATE

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.10 ALTER LOGICAL SERVER Statement

Modifies configuration for the existing user-defined logical server in the database. This statement enforces
consistent shared system temporary store settings across physical nodes shared by logical servers.

 Syntax

ALTER LOGICAL SERVER <logical-server-name>


{ <alter-ls-clause> } [ WITH STOP SERVER ]

<alter-ls-clause> ::=
{ ADD MEMBERSHIP '(' { <ls-member>, ... } ')'
| DROP MEMBERSHIP '(' { <ls-member>, ... } ')'
| POLICY <policy-name> }

<ls-member> ::= FOR LOGICAL COORDINATOR | <mpx-server-name>

Parameters

logical-server-name

Refers to an existing user-defined logical server name.


WITH STOP SERVER

Automatically shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP
database option is changed directly or indirectly.

SAP IQ SQL Reference


SQL Statements INTERNAL 1153
Remarks

Applies to multiplex only.

The SYS.ISYSIQLSMEMBER system table stores definitions for the logical server memberships.

A member node that is added to or dropped from a logical server starts or stops accepting logical server
connections only after the TLV log corresponding to ALTER LOGICAL SERVER is played on that node. Existing
connections of a logical server continue to run on a node when that node is dropped from the logical server,
however, distributed processing is stopped for these connections.

ALTER LOGICAL SERVER returns an error under the following conditions:

● Any ls-member specified with the ADD MEMBERSHIP clause is already a member of the logical server.
● Any ls-member specified with the DROP MEMBERSHIP clause is not an existing member of the logical
server.
● A logical server membership change causes a node to belong to multiple logical servers assigned to a
single login policy. Logical server membership in a login policy cannot overlap.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

● The following example alters a user-defined logical server by adding multiplex nodes n1 and n2 to logical
server ls1:

ALTER LOGICAL SERVER ls1 ADD MEMBERSHIP (n1, n2)

● The following example adds logical membership of COORDINATOR and drop a named membership of the
current coordinator node n1 from logical server ls1:

ALTER LOGICAL SERVER ls1 ADD MEMBERSHIP (FOR LOGICAL COORDINATOR)


ALTER LOGICAL SERVER ls1 DROP MEMBERSHIP (n1)

● The following example changes the logical server policy for logical server ls2 to policy lsp1:

ALTER LOGICAL SERVER ls2 POLICY lsp1

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1154 INTERNAL SQL Statements
9.4.11 ALTER LOGIN POLICY Statement

Changes existing login policies or configures logical server access.

 Syntax

Syntax 1

ALTER LOGIN POLICY <policy-name>


{ { ADD | DROP | SET } LOGICAL SERVER <ls-assignment-list>
[ LOGICAL SERVER <ls-override-list> ] )

<ls-assignment-list> ::=
{ { <ls-name>, ...}
| ALL
| COORDINATOR
| SERVER
| NONE
| DEFAULT }

<ls-override-list> ::=
{ <ls-name>, … }

<ls-name> ::=
{ OPEN | <user-defined-ls-name> }

Syntax 2

ALTER LOGIN POLICY <policy-name> <policy-option>

<policy-option> ::=
<policy-option-name> = <policy-option-value>

<policy-option-name> ::=
AUTO_UNLOCK_TIME
| CHANGE_PASSWORD_DUAL_CONTROL
| DEFAULT_LOGICAL_SERVER
| LOCKED
| MAX_CONNECTIONS
| MAX_DAYS_SINCE_LOGIN
| MAX_FAILED_LOGIN_ATTEMPTS
| MAX_NON_DBA_CONNECTIONS
| PAM_FAILOVER_TO_STD
| PAM_SERVICENAME
| PASSWORD_EXPIRY_ON_NEXT_LOGIN
| PASSWORD_GRACE_TIME
| PASSWORD_LIFE_TIME
| ROOT_AUTO_UNLOCK_TIME
| LDAP_PRIMARY_SERVER
| LDAP_SECONDARY_SERVER
| LDAP_AUTO_FAILBACK_PERIOD
| LDAP_FAILOVER_TO_STD
| LDAP_REFRESH_DN

<policy-option-value> ::=
{ UNLIMITED | DEFAULT | <value> }

SAP IQ SQL Reference


SQL Statements INTERNAL 1155
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. See Login Policy Options and LDAP Login Policy Options for supported
values for each option.

policy-option-name

The name of the policy option. See Login Policy Options and LDAP Login Policy Options for details about
each option.

Remarks

If you do not specify a policy option, values for this login policy come from the root login policy. New policies do
not inherit the MAX_NON_DBA_CONNECTIONS and ROOT_AUTO_UNLOCK_TIME policy options.

All new databases include a root login policy. You can modify the root login policy values, but you cannot delete
the policy.

For details on available login policy options for root and user-defined logins, LDAP user authentication, and
multiplex servers, see CREATE LOGIN POLICY Statement.

Privileges

Requires the MANAGE ANY LOGIN POLICY system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Examples

The following example sets the password_life_time value to UNLIMITED and the max_failed_login_attempts
value to 5 in the Test1 login policy:

ALTER LOGIN POLICY Test1


password_life_time=UNLIMITED
max_failed_login_attempts=5;

In this section:

Logical Server Access Configuration [page 1157]


Configure logical server access.

SAP IQ SQL Reference


1156 INTERNAL SQL Statements
Related Information

Login Policy Options


LDAP Login Policy Options
Multiplex Login Policy Configuration
CREATE LOGIN POLICY Statement [page 1307]
DROP LOGIN POLICY Statement [page 1445]
CREATE LOGIN POLICY Statement [page 1307]
REVOKE System Privilege Statement [page 1635]

9.4.11.1 Logical Server Access Configuration

Configure logical server access.

Assume that the root login policy allows access to logical servers ls4 and ls5 and login policy lp1 exists with
no logical server assignment. The statement effectively assigns login policy lp1 to logical servers ls4 and ls5.

Assign logical server ls1 to login policy lp1:

ALTER LOGIN POLICY lp1 ADD LOGICAL SERVER ls1

This statement allows access of logical servers ls2 and ls3 from login policy lp1:

ALTER LOGIN POLICY lp1 ADD LOGICAL SERVER ls2, ls3

Modify login policy lp1 to allow access to ls3 and ls4 only:

ALTER LOGIN POLICY lp1 ADD LOGICAL SERVER ls4

ALTER LOGIN POLICY lp1 DROP LOGICAL SERVER ls1, ls2

Alternatively:

ALTER LOGIN POLICY lp1 SET LOGICAL SERVER ls3, ls4

Modify login policylp1 to deny access to any logical servers:

ALTER LOGIN POLICY lp1 SET LOGICAL SERVER NONE

Drop current logical server assignments of login policylp1 and allow it to inherit the logical server
assignments of the root login policy:

ALTER LOGIN POLICY lp1 SET LOGICAL SERVER DEFAULT

ADD, DROP, or SET clauses let you configure the logical server assignments of a login policy:

● ADD – adds new logical server assignments to a login policy.


● DROP – deletes existing logical server assignments from a login policy.
● SET – replaces all logical server assignments for a login policy with a new set of logical server.

Use only one ADD, DROP, or SET clause. Use SERVER, NONE, and DEFAULT clauses only with the SET clause.
Specify a particular logical server name only once per ls-assignment list or ls-override list.

SAP IQ SQL Reference


SQL Statements INTERNAL 1157
An error is returned if:

● Any logical server specified with the ADD clause is already assigned to the login policy.
● Any logical server specified with the DROP clause is currently not assigned to the login policy.
● Logical server assignment change may cause a membership overlap among assigned logical servers.

SYS.ISYSIQLOGINPOLICYLSINFO stores logical server assignment information. For each logical-server


override of a login policy option, a corresponding row exists in ISYSIQLOGINPOLICYLSINFO.

9.4.12 ALTER LS POLICY Statement

Modifies some or all option values for the root logical server policy or a user-created logical server policy. This
statement enforces consistent shared system temporary store settings across physical nodes shared by logical
servers.

 Syntax

ALTER LS POLICY <ls-policy-name> <ls-option-value-list>


[ WITH STOP SERVER ]

<ls-option-value-list> ::=
{ <ls-option-name> = <ls-policy-option-value> } ...

<ls-option-name> ::=
ALLOW_COORDINATOR_AS_MEMBER
| DQP_ENABLED
| ENABLE_AUTOMATIC_FAILOVER
| LOGIN_REDIRECTION
| REDIRECTION_WAITERS_THRESHOLD
| TEMP_DATA_IN_SHARED_TEMP

Parameters

ls-policy-name

The name of the logical server policy. Specify root to modify the root logical server policy.
ls-option-value-list

The name of the logical server policy option. See Remarks for list of options.
ls-policy-option-value

Any unspecified option inherits its value from the root logical server policy. See Remarks.
WITH STOP SERVER

Automatically shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP option
is changed directly or indirectly.

SAP IQ SQL Reference


1158 INTERNAL SQL Statements
Remarks

Applies to multiplex only.

If you want a smaller IQ_SYSTEM_TEMP dbspace, set TEMP_DATA_IN_SHARED_TEMP to ON, which writes
temporary data to IQ_SHARED_TEMP instead of IQ_SYSTEM_TEMP. In a distributed query processing
environment, however, setting both DQP_ENABLED and TEMP_DATA_IN_SHARED_TEMP to ON may saturate
your SAN with additional data in IQ_SHARED_TEMP, where additional I/O operations against IQ_SHARED_TEMP
may adversely affect DQP performance.

Option Description Properties

ALLOW_COORDI­ Can only be set for the ROOT logical server policy. When ON ● Values – ON, OFF
NATOR_AS_MEM­ (the default), the coordinator can be a member of any user- ● Default – ON
BER defined logical server. OFF prevents the coordinator from be­
ing used as a member of any user-defined logical servers.

DQP_ENABLED When set to 0, query processing is not distributed. When set ● Values – 0, 1, 2
to 1 (the default), query processing is distributed as long as a ● Default – 1
writable shared temporary file exists. When set to 2, query
processing is distributed over the network, and the shared
temporary store is not used.

ENABLE_AUTO­ Can only be set for the ROOT logical server policy. When ON, ● Values – ON, OFF, DEFAULT
MATIC_FAILOVER enables automatic failover for logical servers governed by ● Default – OFF
specified login policy. When OFF (the default), disables auto­
matic failover at the logical server level, allowing manual fail­
over. Specify DEFAULT to set back to the default value.

LOGIN_REDIREC­ When ON, enables login redirection for logical servers gov­ ● Values – ON, OFF
TION erned by specified login policy. When OFF (the default), disa­ ● Default – OFF
bles login redirection at the logical server level, allowing ex­
ternal connection management.

REDIREC­ Specifies how many connections can queue before SAP IQ ● Values – Integer
TION_WAIT­ redirects a connection to this logical server to another ● Default – 5
ERS_THRESHOLD server. Can be any integer value; default is 5.

TEMP_DATA_IN_S When ON, all temporary table data and eligible scratch data ● Values – ON, OFF
HARED_TEMP writes to the shared temporary store, provided that the ● Default – OFF
shared temporary store has at least one read-write file
added. You must restart all multiplex nodes after setting this
option or after adding a read-write file to the shared tempo­
rary store. (If the shared temporary store contains no read-
write file, or if you do not restart nodes, data is written to
IQ_SYSTEM_TEMP instead.)

When OFF (the default), all temporary table data and


scratch data writes to the local temporary store.

SAP IQ SQL Reference


SQL Statements INTERNAL 1159
Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

● The following example alters the logical server policy:

ALTER LS POLICY root


ALLOW_COORDINATOR_AS_MEMBER=ON

● The following example alters the logical server policy and causes servers to shut down automatically when
the option value changes:

ALTER LS POLICY root


TEMP_DATA_IN_SHARED_TEMP=ON WITH STOP SERVER

Related Information

DQP_OPTIONS13 Option [page 1830]


REVOKE System Privilege Statement [page 1635]

9.4.13 ALTER MULTIPLEX RENAME Statement

Renames the multiplex and stores the multiplex name in SYS.ISYSIQINFO system table.

 Syntax

ALTER MULTIPLEX RENAME <multiplex-name>

Remarks

When a multiplex is created, it is named after the coordinator. This statement is automatically committed.

SAP IQ SQL Reference


1160 INTERNAL SQL Statements
Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.14 ALTER MULTIPLEX SERVER Statement

Changes the name, catalog file path, role, or status of the given server.

 Syntax

Syntax 1

ALTER MULTIPLEX SERVER <server-name> <server-option>


<server-option> ::=
{ RENAME <new-server-name>
| DATABASE '<dbfile>'
| ROLE { WRITER | READER | COORDINATOR }
| STATUS { INCLUDED | EXCLUDED }
| ASSIGN AS FAILOVER SERVER
| { ENABLE | DISABLE } RLV STORE
| <host-port-list> }

<host-port-list> ::=
{ HOST '<hostname>' PORT <port number> ...}
{ PRIVATE HOST '<hostname>' PORT <port number> ...}

Syntax 2

ALTER MULTIPLEX SERVER <server-name> PRIVATE NULL

Parameters

RENAME new-server-name

Changes the name of the given server. The server automatically shuts down and the next restart requires
the new name.
DATABASE 'dbfile'

Changes the catalog file path for the given server. The server automatically shuts down and the next restart
requires the new catalog path. The user must relocate the catalog file.
ROLE { WRITER | READER | COORDINATOR }

SAP IQ SQL Reference


SQL Statements INTERNAL 1161
Changes the role of the given server. Users cannot change the role of coordinator or role to coordinator. If
the role of the writer node changes to reader, the server shuts down.
STATUS { INCLUDED | EXCLUDED }

Changes the status of the given server. A failover node cannot be excluded unless it is the last node to be
excluded. The server automatically shuts down after exclusion. After including a node, you synchronize and
restart it.
ASSIGN AS FAILOVER

Designates the given server as the new failover server. The node should not be in the excluded state. The
ASSIGN AS FAILOVER clause is a standalone clause; do not use it with any other ALTER MULTIPLEX
SERVER clause.

The coordinator must be running, but you can run the ALTER MULTIPLEX SERVER statement from any
server in the multiplex. (Run all DDL statements on the coordinator.) In all cases except when altering role
from reader to writer, the named server is automatically shut down.
{ ENABLE | DISABLE } RLV STORE

Allows the coordinator to use an in-memory store for high-performance row-level updates.
host-port-list

Shuts down the target server before you exclude it. If you do not, an excluded server automatically shuts
down and requires ALTER MULTIPLEX SERVER <server-name> STATUS INCLUDED and a synchronize
to rejoin the multiplex.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

The following example excludes secondary server mpx_writer1:

ALTER MULTIPLEX SERVER mpx_writer1 STATUS EXCLUDED

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1162 INTERNAL SQL Statements
9.4.15 ALTER PROCEDURE Statement

Replaces an existing procedure with a modified version. Include the entire modified procedure in the ALTER
PROCEDURE statement, and reassign user permissions on the procedure.

 Syntax

Syntax 1

ALTER PROCEDURE [ <owner>.]<procedure-name>


| <procedure-definition>
| REPLICATE { ON | OFF }
| SET HIDDEN
| RECOMPILE

Syntax 2

ALTER PROCEDURE [ <owner>.]<procedure-name> ( [ <parameter>, …] )


[ RESULT (<result-type>, ...)]
EXTERNAL NAME '<external-call>' [ LANGUAGE JAVA [ <environment-name> ] }

<result-type> ::=
<table-name> TABLE | <result-col-type> [, ...]

<result-col-type> ::= <column-name> <data type>

<external-call> ::=
[<column-name>:]<function-name@library>; ...

<environment-name> ::=
DISALLOW | ALLOW SERVER SIDE REQUESTS

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

[owner.]procedure-name

Specifies the name of the procedure you are replacing. The <owner> clause is optional.
REPLICATE { ON | OFF }

If a procedure needs to be relocated to other sites using SAP Replication Server, use the REPLICATE ON
clause.
SET HIDDEN

SAP IQ SQL Reference


SQL Statements INTERNAL 1163
To obfuscate the definition of the associated procedure and cause it to become unreadable. The procedure
can be unloaded and reloaded into other databases.

 Caution

This setting is irreversible. You should retain the original procedure definition outside of the database.

RECOMPILE

Recompiles a stored procedure. When you recompile a procedure, the definition stored in the catalog is re-
parsed and the syntax is verified. 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.
RESULT

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.
environment-name

DISALLOW is the default. ALLOW indicates that server-side connections are allowed.

 Note

● Do not specify ALLOW unless necessary. Use of the ALLOW clause slows down certain types of
SAP IQ table joins.
● Do not use UDFs with both ALLOW SERVER SIDE REQUESTS and DISALLOW SERVER SIDE
REQUESTS clauses in the same query.

Remarks

(back to top)

The ALTER PROCEDURE statement must include the entire new procedure. You can use PROC as a synonym
for PROCEDURE. Both Watcom and Transact-SQL dialect procedures can be altered through the use of ALTER
PROCEDURE. Existing permissions on the procedure are not changed. If you execute DROP PROCEDURE followed
by CREATE PROCEDURE, execute permissions are reassigned.

You cannot combine Syntax 2 with Syntax 1.

When using the ALTER PROCEDURE statement for table UDFs, the same set of restrictions apply as for the
CREATE PROCEDURE Statement (External Procedures).

 Note

For required parameters that accept variable names, an error is returned if one of the following conditions
is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter

SAP IQ SQL Reference


1164 INTERNAL SQL Statements
● The data type of the variable does not match that required by the parameter

Privileges

(back to top)

The privilege required varies by procedure type. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Procedure Privilege Name

Alter a Watcom SQL or Transact-SQL pro­ Requires one of:


cedure ● You own the Watcom SQL or Transact-SQL procedure
● ALTER ANY PROCEDURE system privilege
● ALTER ANY OBJECT system privilege

Alter an external C/C++ Scalar or Aggre­ Requires CREATE EXTERNAL REFERENCE system privilege
gate, or external Java procedure
For external C/C++ Scalar or Aggregate, or external Java procedures owned
by others, you also require one of:

● ALTER ANY PROCEDURE system privilege


● ALTER ANY OBJECT system privilege

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP SQL Anywhere

Examples

(back to top)

This example creates and then alters a procedure using a variable in the NAMESPACE clause:

1. The following statements create a variable for a NAMESPACE clause:

CREATE VARIABLE @ns LONG VARCHAR


SET @ns = 'http://wsdl.domain.com/';

2. The following statement creates a procedure named FtoC that uses a variable in the NAMESPACE clause:

CREATE PROCEDURE FtoC ( IN temperature LONG VARCHAR )


URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'

SAP IQ SQL Reference


SQL Statements INTERNAL 1165
NAMESPACE @ns;

3. The following statement alters the procedure FtoC so that the temperature parameter accepts a FLOAT
data type:

ALTER PROCEDURE FtoC ( IN temperature FLOAT )


URL 'http://localhost:8082/FtoCService'
NAMESPACE @ns;

Related Information

%TYPE and %ROWTYPE attributes [page 93]


CREATE PROCEDURE Statement [page 1321]
REVOKE System Privilege Statement [page 1635]

9.4.16 ALTER ROLE Statement

Migrates a compatibility role to a user-defined system role, then automatically drops the compatibility role.

 Note

You cannot use the ALTER ROLE statement to migrate SYS_AUTH_SA_ROLE or SYS_AUTH_SSO_ROLE.
These roles are automatically migrated when SYS_AUTH_DBA_ROLE is migrated.

 Syntax

Syntax 1 – Migrates SYS_AUTH_DBA_ROLE

ALTER ROLE <predefined_sys_role_name>


MIGRATE TO <new_role_name> [, <new_sa_role_name>, <new_sso_role_name>]

Syntax 2 – Migrates all Other Compatibility Roles

ALTER ROLE <predefined_sys_role_name>


MIGRATE TO <new_role_name>

Parameters

predefined_sys_role_name

The name of a compatibility role that still exists (has not already been dropped) in the database.
new_role_name

The name of the new role cannot begin with the prefix SYS_ or end with the suffix _ROLE.
new_sa_role_name

SAP IQ SQL Reference


1166 INTERNAL SQL Statements
Required only when migrating SYS_AUTH_DBA_ROLE. The new role to which the underlying system
privileges of SYS_AUTH_SA_ROLE are to be migrated to cannot already exist in the database, and the new
role name cannot begin with the prefix SYS_ or end with the suffix _ROLE.
new_sso_role_name

Required only when migrating SYS_AUTH_DBA_ROLE. The new role to which the underlying system
privileges of SYS_AUTH_SSO_ROLE are to be migrated to cannot already exist in the database, and the
new role name cannot begin with the prefix SYS_ or end with the suffix _ROLE.

Remarks

During the migration process:

● A new user-defined role is created.


● All of the system privileges currently granted to the migrating predefined role are automatically granted to
the new user-defined role.
● All users and roles currently granted to the migrating predefined role are automatically granted to the new
user-defined role.
● The compatibility role is dropped.

Since no role administrator was specified during the migration process, only global role administrators can
manage the new role. Use the CREATE ROLE statement to add role administrators with appropriate
administrative rights to the role.

Privileges

Requires the MANAGE ROLES system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example migrates SYS_AUTH_DBA_ROLE to the new roles Custom_DBA, Custom_SA, and
Custom_SSO respectively. It then automatically migrates all users, underlying system privileges, and roles
granted to SYS_AUTH_DBA_ROLE to the applicable new roles. Finally, it drops SYS_AUTH_DBA_ROLE,
SYS_AUTH_SA_ROLE, and SYS_AUTH_SSO_ROLE:

ALTER ROLE SYS_AUTH_DBA_ROLE


MIGRATE TO Custom_DBA, Custom_SA, Custom_SSO

SAP IQ SQL Reference


SQL Statements INTERNAL 1167
● The following example migrates SYS_AUTH_OPERATOR_ROLE role to the new role Operator_role. It
then automatically migrates all users, underlying system privileges, and roles granted to
SYS_AUTH_OPERATOR_ROLE to the new role and drops SYS_AUTH_OPERATOR_ROLE:

ALTER ROLE SYS_AUTH_OPERATOR_ROLE


MIGRATE TO Operator_role

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.17 ALTER SEQUENCE statement

Alters a sequence. This statement applies to SAP IQ catalog store tables only.

 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

SAP IQ SQL Reference


1168 INTERNAL SQL Statements
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.

Privileges

If you own the sequence, no additional privilege is required. For sequences owned by others, your require one of
the following:

● ALTER ANY SEQUENCE system privilege


● ALTER ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None

Standards

ANSI/ISO SQL Standard

The ALTER SEQUENCE statement is part of optional ANSI/ISO SQL Language Feature T176. The CACHE
clause is not in the standard.

 Example

The following example sets a new maximum value for a sequence named Test:

ALTER SEQUENCE Test


MAXVALUE 1500;

SAP IQ SQL Reference


SQL Statements INTERNAL 1169
Related Information

CREATE SEQUENCE statement [page 1361]


DROP SEQUENCE statement [page 1454]
CREATE SEQUENCE statement [page 1361]
DROP SEQUENCE statement [page 1454]
REVOKE System Privilege Statement [page 1635]

9.4.18 ALTER SERVER Statement

Modifies the attributes of a remote server. Changes made by ALTER SERVER do not take effect until the next
connection to the remote server.

 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
| MSSODBC
| ORAODBC
| ODBC }

<connection-info> ::=
{ <machine-name>:<port-number> [ /<dbname> ] | <data-source-name> }

Go to:

● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

CLASS 'server-class'

Changes the server class.


USING 'connection-info'

SAP IQ SQL Reference


1170 INTERNAL SQL Statements
If a JDBC-based server class is used, the USING clause is <machine-name>:<port-number> [ /
<dbname> ], where:

● <hostname> – is the machine on which the remote server runs.


● <portnumber> – is the TCP/IP port number on which the remote server listens. The default port
number for SAP IQ and SAP SQL Anywhere is 2638.
● <dbname> – for SAP SQL Anywhere remote servers, if you do not specify a <dbname>, the default
database is used. For SAP ASE, the default is the master database, and an alternative to using
<dbname> is to another database by some other means (for example, in the FORWARD TO statement).

If an ODBC-based server class is used, the USING clause is the <data-source-name>, which is the ODBC
Data Source Name.
CAPABILITY 'cap-name' { ON | OFF }

Turns a server capability ON or OFF. Server capabilities are stored in the system table SYSCAPABILITY.
The names of these capabilities are stored in the system table SYSCAPABILITYNAME. The
SYSCAPABILITY table contains no entries for a remote server until the first connection is made to that
server. At the first connection, SAP IQ interrogates the server about its capabilities and then populates
SYSCAPABILITY. For subsequent connections, the server’s capabilities are obtained from this table.

In general, you need not alter a server’s capabilities. It might be necessary to alter capabilities of a generic
server of class ODBC.

<cap-name> is the name of a server capability


CONNECTION CLOSE [ CURRENT | ALL | connection-id ]

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.

These 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 the
SERVER OPERATOR system privilege 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 the SERVER OPERATOR
system privilege to be able to close the connection.

Privileges

(back to top)

Requires the SERVER OPERATOR system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

SAP IQ SQL Reference


SQL Statements INTERNAL 1171
Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

Examples

(back to top)

● The following example changes the server class of the SAP ASE server named ase_prod so its connection
to SAP IQ is ODBC-based. The Data Source Name is ase_prod:

ALTER SERVER ase_prod


CLASS 'ASEODBC'
USING 'ase_prod'

● The following example changes a capability of server infodc:

ALTER SERVER infodc


CAPABILITY 'insert select' OFF

● The following example closes all connections to the remote server named rem_test:

ALTER SERVER rem_test


CONNECTION CLOSE ALL

● The following example closes the connection to the remote server named rem_test that has the
connection ID 142536:

ALTER SERVER rem_test


CONNECTION CLOSE 142536

Related Information

CREATE SERVER Statement [page 1363]


DROP SERVER Statement [page 1455]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1172 INTERNAL SQL Statements
9.4.19 ALTER SERVICE Statement

Causes the database server to act as a Web server

 Syntax

ALTER SERVICE <service-name>


[ TYPE <service-type-string> ]
[ <attributes> ]
[ AS '<statement>' ]

<service-type-string> ::=
{ 'RAW'
| 'HTML'
| 'XML'
| 'SOAP'
| 'DISH' }

<attributes> ::=
[ AUTHORIZATION { ON | OFF } ]
[ SECURE { ON | OFF } ]
[ USER { <user-name> | NULL } ]
[ URL [ PATH/ ] { ON | OFF | ELEMENTS } ]
[ USING { <SOAP-prefix> | NULL } ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

TYPE service-type-string

Identifies the type of the service. The type must be one of the listed service types. There is no default value.

● RAW – Sends the result set to the client without any further formatting. You can produce formatted
documents by generating the required tags explicitly within your procedure.
● HTML – Formats the result set of a statement or procedure into an HTML document that contains a
table.
● XML – Assumes the result set is an XML format. If it is not already so, it is automatically converted to
XML RAW format.
● SOAP – Formats the result set as a Simple Object Access Protocol (SOAP) response. The request must
be a valid SOAP request. For more information about the SOAP standards, see www.w3.org/TR/SOAP
.
● DISH – Determine SOAP Handler, or DISH, service acts as a proxy for one or more SOAP services. In
use, it acts as a container that holds and provides access to a number of SOAP services. A Web
Services Description Language (WSDL) file is automatically generated for each of the included SOAP

SAP IQ SQL Reference


SQL Statements INTERNAL 1173
services. The included SOAP services are identified by a common prefix, which must be specified in
the USING clause.

Web service names may be any sequence of alphanumeric characters or “/”, “-”, “_”, “.”, “!”, “~”, “*”, “'”, “(“,
or “”)”, except that the first character cannot begin with a slash (/) and the name cannot contain two or
more consecutive slash characters.
attributes

The valid values are as follows:

AUTHORIZATION { ON | OFF }

Determines whether users must specify a user name and password when connecting to the service.
The default value is ON.

● If authorization is OFF, the AS clause is required and a single user must be identified by 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 role name using the USER
clause. If the user name is NULL, all known users can access the service.

Run production systems with authorization turned on. Grant permission to use the service by adding
users to a role.
SECURE { ON | OFF }

Indicates whether unsecure connections are accepted. ON indicates that only HTTPS connections are
to be accepted. Service requests received on the HTTP port are automatically redirected to the HTTPS
port. If set to OFF, both HTTP and HTTPS connections are accepted. The default value is OFF.
USER { user-name | NULL }

If authorization is disabled, this parameter becomes mandatory and specifies the user ID used to
execute all service requests. If authorization is enabled (the default), this optional clause identifies the
user or role permitted access to the service. The default value is NULL, which grants access to all
users.
URL [ PATH/ ] { ON | OFF | ELEMENTS }

Determines whether URI paths are accepted and, if so, how they are processed. OFF indicates that
nothing must follow the service name in a URI request. ON indicates that the remainder of the URI is
interpreted as the value of a variable named <url>. ELEMENTS indicates that the remainder of the
URI path is to be split at the slash characters into a list of up to 10 elements. The values are assigned to
variables named url plus a numeric suffix of between 1 and 10; for example, the first three variable
names are url1, url2, and url3. If fewer than 10 values are supplied, the remaining variables are set to
NULL. If the service name ends with the character /, then URL must be set to OFF. The default value
is OFF.
USING { SOAP-prefix | NULL }

Applies only to DISH services. The parameter specifies a name prefix. Only SOAP services whose
names begin with this prefix are handled.
AS 'statement'

If the statement is NULL, the URI must specify the statement to be executed. Otherwise, the specified
SQL statement is the only one that can be executed through the service. The statement is mandatory for
SOAP services, and ignored for DISH services. The default value is NULL.

SAP IQ SQL Reference


1174 INTERNAL SQL Statements
All services that are run in production systems must define a statement. The statement can be NULL only
if authorization is enabled.

Remarks

(back to top)
You cannot rename Web services.

Privileges

(back to top)

Requires MANAGE ANY WEB SERVICE system privilege. See GRANT System Privilege Statement [page 1511]
for assistance with granting privileges.

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

The following example set sup a Web server quickly, starts a database server with the -xs switch, then execute
these statements:

CREATE SERVICE tables TYPE 'HTML'


ALTER SERVICE tables
AUTHORIZATION OFF
USER DBA
AS SELECT * FROM SYS.ISYSTABAfter executing these statements, use any Web
browser to open the URL http://localhost/tables.

Related Information

CREATE SERVICE Statement [page 1365]


DROP SERVICE Statement [page 1456]

SAP IQ SQL Reference


SQL Statements INTERNAL 1175
REVOKE System Privilege Statement [page 1635]

9.4.20 ALTER SPATIAL REFERENCE SYSTEM Statement

Changes the settings of an existing spatial reference system.

 Syntax

ALTER SPATIAL REFERENCE SYSTEM


<srs-name>
[ <srs-attribute> [ <srs-atribute> ... ] ]

<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> }
| TOLERANCE { <tolerance-distance> | DEFAULT }
| SNAP TO GRID { <grid-size> | DEFAULT }
| AXIS ORDER <axis-order>
| POLYGON FORMAT <polygon-format>
| STORAGE FORMAT <storage-format>

<grid-size> ::=
DOUBLE : usually between 0 and 1

<axis-order> ::=
{ 'x/y/z/m' | 'long/lat/z/m' | 'lat/long/z/m' }

<polygon-format> ::=
{ 'CounterClockWise' | 'Clockwise' | 'EvenOdd' }

<storage-format> ::=
{ 'Internal' | 'Original' | 'Mixed' }

Parameters

DEFINITION { definition-string | NULL }

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.

SAP IQ SQL Reference


1176 INTERNAL SQL Statements
<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 organization-name

Information about the organization that created the spatial reference system that the spatial reference
system is based on.
IDENTIFIED BY organization-srs-id

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.
TRANSFORM DEFINITION { transform-definition-string | NULL }

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.
LINEAR UNIT OF MEASURE linear-unit-name

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.

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 { angular-unit-name | NULL }

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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1177
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 { ROUND EARTH | PLANAR }

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 coordinate-name { UNBOUNDED | BETWEEN low-number AND high-number }

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

SAP IQ SQL Reference


1178 INTERNAL SQL Statements
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 SEMI MAJOR AXIS semi-major-axis-length { SEMI MINOR AXIS semi-minor-axis-length |
INVERSE FLATTENING inverse-flattening-ratio }

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)

SAP IQ uses the ellipsoid definition when computing distance in geographic spatial reference systems.
TOLERANCE { tolerance-distance | DEFAULT }

Flat-Earth (planar) spatial reference systems, use the TOLERANCE clause to specify the precision to use
when comparing points. If the distance between two points is less than tolerance-distance, the two points
are considered equal. Setting tolerance-distance allows you to control the tolerance for imprecision in the
input data or limited internal precision. By default, tolerance-distance is set to be equal to grid-size.

When set to 0, two points must be exactly equal to be considered equal.

For round-Earth spatial reference systems, TOLERANCE must be set to 0.


SNAP TO GRID { grid-size | DEFAULT }

Flat-Earth (planar) spatial reference systems, use the SNAP TO GRID clause to define the size of the grid
SAP IQ uses when performing calculations. By default, SAP IQ 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.
POLYGON FORMAT polygon-format

Internally, SAP IQ 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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1179
The interpretation used by SAP IQ 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 – input follows SAP IQ's internal interpretation: the inside of the polygon is on the
left side while following ring orientation.
● Clockwise – input follows the opposite of SAP IQ's approach: the inside of the polygon is on the right
side while following ring orientation.
● EvenOdd – (default) 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 storage-format

Control what is stored when spatial data is loaded into the database. Possible values are:

● Internal – SAP IQ 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).
● Original – SAP IQ 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 – SAP IQ stores the internal version and, if it is different from the original version, SAP 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.

Privileges

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Requires one of:

● You own the spatial reference system

SAP IQ SQL Reference


1180 INTERNAL SQL Statements
● MANAGE ANY SPATIAL OBJECT system privilege
● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the spatial reference system.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

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

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.21 ALTER TABLE Statement

Modifies a table definition.

 Syntax

Syntax 1 – Alter Owner

ALTER TABLE <table_name> ALTER OWNER TO <new_owner>


[ { PRESERVE | DROP } PERMISSIONS ]
[ { PRESERVE | DROP } FOREIGN KEYS ]

Syntax 2

ALTER TABLE [ <owner>. ]<table-name>


|{ ENABLE | DISABLE } RLV STORE
{ <alter-clause>, ... }

<alter-clause> ::=
ADD <create-clause>
| ALTER <column-name> <column-alteration>
| ALTER [ CONSTRAINT <constraint-name> ] CHECK ( <condition> )
| DROP <drop-object>

SAP IQ SQL Reference


SQL Statements INTERNAL 1181
| RENAME <rename-object>
| <move-clause>
| SPLIT PARTITION <range-partition-name>
INTO ( <range-partition-decl>, <range-partition-decl> )
| MERGE PARTITION <partition-name-1> INTO <partition-name-2>
| UNPARTITION
| PARTITION BY <range-partitioning-scheme>
| <hash-partitioning-scheme>
| <composite-partitioning-scheme>

<create-clause> ::=
<column-name> <column-definition> [ <column-constraint> ]
| <table-constraint>
| [ PARTITION BY ] <range-partitioning-scheme>

<column definition> ::=


<column-name> <data-type> [ NOT NULL | NULL ]
[ IN <dbspace-name> ]
[ DEFAULT <default-value> | IDENTITY ]

<column-constraint> ::=
[ CONSTRAINT <constraint-name> ]
{ UNIQUE
| PRIMARY KEY
| REFERENCES <table-name> [ (<column-name> ) ] [ <actions> ]
| CHECK ( <condition> )
| IQ UNIQUE ( <integer> ) }

<table-constraint> ::=
[ CONSTRAINT <constraint-name> ]
{ UNIQUE ( <column-name> [ , … ] )
| PRIMARY KEY ( <column-name> [ , … ] )
| <foreign-key-constraint>
| CHECK ( <condition> ) }

<foreign-key-constraint> ::=
FOREIGN KEY [ <role-name> ] [ ( <column-name> [ , … ] ) ]
... REFERENCES <table-name> [ ( <column-name> [ , … ] ) ]
... [ <actions> ]

<actions> ::= (Back to <column-definition> or <foreign-key-constraint>)


[ ON { UPDATE | DELETE } { RESTRICT } ]

<column-alteration> ::= (Back to <alter-clause>)


{ <column-data-type> | <alterable-column-attribute> } [ <alterable-column-
attribute> … ]
| ADD [ CONSTRAINT[ <constraint-name> ] CHECK ( <condition> )
| DROP { DEFAULT | CHECK | CONSTRAINT <constraint-name> }

<alterable-column-attribute> ::=
[ NOT ] NULL
| DEFAULT <default-value>
| [ CONSTRAINT <constraint-name> ] CHECK { NULL | ( <condition> )
}

<default-value> ::= (Back to <column-definition> or <alterable-column-


attribute>)
CURRENT { DATABASE | DATE | REMOTE USER | TIME | TIMESTAMP | USER |
PUBLISHER )
| <string>
| <global variable>

SAP IQ SQL Reference


1182 INTERNAL SQL Statements
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function> ( <constant-expression> )
| AUTOINCREMENT
| NULL
| TIMESTAMP
| LAST USER
| USER

<drop-object> ::= (Back to <alter-clause>)


{ <column-name>
| CHECK <constraint-name>
| CONSTRAINT
| UNIQUE ( <index-columns-list> )
| PRIMARY KEY
| FOREIGN KEY <fkey-name>
| [ PARTITION ] <range-partition-name> }

<rename-object> ::= (Back to <alter-clause>)


<new-table-name>
| <column-name> TO <new-column-name>
| CONSTRAINT <constraint-name> TO <new-constraint-name>
| [ PARTITION ] <range-partition-name> TO <new-range-partition-name>

<move-clause> ::= (Back to <alter-clause>)


{ ALTER <column-name>
MOVE
{ PARTITION ( <range-partition-name> TO <new-dbspace-name>)
| TO <new-dbspace-name> } }
| MOVE PARTITION <range-partition-name> TO <new-dbspace-name>
| MOVE TO <new-dbspace-name>
| MOVE TABLE METADATA TO <new-dbspace-name> )

<range-partitioning-scheme> ::= (Back to <alter-clause>)


RANGE ( <partition-key> )
( <range-partition-decl> [, <range-partition-decl> ...] )

<partition-key> ::=
<column-name>

<range-partition-decl> ::= (Back to <alter-clause>)


<range-partition-name> VALUES <= ( { <constant> | MAX } ) [ IN <dbspace-
name> ]

<hash-partitioning-scheme> ::= (Back to <alter-clause>)


HASH ( <partition-key>, … ] )

<composite-partitioning-scheme> ::= (Back to <alter-clause>)


<hash-partitioning-scheme> SUBPARTITION <range-partitioning-scheme>

Parameters

ALTER OWNER

Changes the owner of a table.

SAP IQ SQL Reference


SQL Statements INTERNAL 1183
● You cannot use the ALTER OWNER clause in conjunction with any other <alter-clause> clauses of
the ALTER TABLE statement:
○ [ PRESERVE | DROP ] PERMISSIONS – if you do not want the new owner to have the same
privileges as the old owner, use the DROP privileges clause (default) to drop all explicitly-granted
privileges that allow a user access to the table. Implicitly-granted privileges given to the owner of
the table are given to the new owner and dropped from the old owner.
○ [ PRESERVE | DROP ] FOREIGN KEYS – if you want to prevent the new owner from accessing
data in referenced tables, use the DROP FOREIGN KEYS clause (default) to drop all foreign keys
within the table, as well as all foreign keys referring to the table. Use of the PRESERVE FOREIGN
KEYS clause with the DROP PERMISSIONS clause fails unless all referencing tables are owned by
the new owner.
● The ALTER TABLE ALTER OWNER statement fails if:
○ Another table with the same name as the original table exists and is owned by the new user.
○ The PRESERVE FOREIGN KEYS and PRESERVE PERMISSIONS clauses are both specified and
there is a foreign key owned by a user other than the new table owner referencing the table that
relies on implicitly-granted privileges (such as those given to the owner of a table). To avoid this
failure, explicitly grant SELECT privileges to the referring table's original owner, or drop the foreign
keys.
○ The PRESERVE FOREIGN KEYS clause is specified, but the PRESERVE PERMISSIONS clause is
NOT, and there is a foreign key owned by a user other than the new table owner referencing the
table. To avoid this failure, drop the foreign keys.
○ The PRESERVE FOREIGN KEYS clause is specified and the table contains a foreign key that relies
on implicitly granted privileges (such as those given to the owner of a table). To avoid this failure,
explicitly GRANT SELECT privileges to the new owner on the referenced table, or drop the foreign
keys.
○ The table contains a column with a default value that refers to a sequence, and the USAGE
privilege of the sequence generator relies on implicitly-granted privileges (such as those given to
the owner of a sequence). To avoid this failure, explicitly grant USAGE privilege on the sequence
generator to the new owner of the table.
○ Enabled materialized views that depend on the original table exist.
{ ENABLE | DISABLE } RLV STORE

Registers this table with the RLV store for real-time in-memory updates. Not supported for IQ temporary
tables. This value overrides the value of the database option BASE_TABLES_IN_RLV. In a multiplex, the
RLV store can only be enabled on the coordinator
ADD create-clause Adds a new column or column constraint to the table object.

● ADD <column-definition> – Adds a new column to the table. The table must be empty to specify
NOT NULL. The table might contain data when you add an IDENTITY or DEFAULT AUTOINCREMENT
column. If the column has a default IDENTITY value, all rows of the new column are populated with
sequential values. You can also add FOREIGN constraint as a column constraint for a single column
key. The value of the IDENTITY/DEFAULT AUTOINCREMENT column uniquely identifies every row in a
table.
The IDENTITY/DEFAULT AUTOINCREMENT column stores sequential numbers that are automatically
generated during inserts and updates. DEFAULT AUTOINCREMENT columns are also known as
IDENTITY columns. When using IDENTITY/DEFAULT AUTOINCREMENT, the column must be one of
the integer data types, or an exact numeric type, with scale 0. See CREATE TABLE Statement for more
about column constraints and IDENTITY/DEFAULT AUTOINCREMENT columns.

SAP IQ SQL Reference


1184 INTERNAL SQL Statements
 Note

The database option IDENTITY_INSERT must be set to the table name to perform an explicit insert
or update into an IDENTITY or AUTOINCREMENT column. For information on identity columns, see
The IDENTITY or AUTOINCREMENT Default in SAP IQ Administration: Database. For information on
IDENTITY_INSERT, see SAP IQ SQL Reference.

● ADD <column-constraint> – Adds a constraint to a column on a table.


○ <IQ UNIQUE> constraint – Defines the expected cardinality of a column and determines whether
the column loads as Flat FP or NBit FP. An IQ UNIQUE(<n>) value explicitly set to 0 loads the
column as Flat FP. Columns without an IQ UNIQUE constraint implicitly load as NBit up to the
limits defined by the FP_NBIT_AUTOSIZE_LIMIT, FP_NBIT_LOOKUP_MB, and
FP_NBIT_ROLLOVER_MAX_MB options.
○ Using IQ UNIQUE with an <n> value less than the FP_NBIT_AUTOSIZE_LIMIT is not necessary.
Auto-size functionality automatically sizes all low or medium cardinality columns as NBit. Use IQ
UNIQUE in cases where you want to load the column as Flat FP or when you want to load a column
as NBit when the number of distinct values exceeds the FP_NBIT_AUTOSIZE_LIMIT.

 Note

○ Consider memory usage when specifying high IQ UNIQUE values. If machine resources are
limited, avoid loads with FP_NBIT_ENFORCE_LIMITS='OFF' (default).
Prior to SAP IQ 16.1, an IQ UNIQUE <n> value > 16777216 would rollover to Flat FP. In 16.1,
larger IQ UNIQUE values are supported for tokenization, but may require significant
memory resource requirements depending on cardinality and column width.
○ BIT, BLOB, and CLOB data types do not support NBit dictionary compression. If
FP_NBIT_IQ15_COMPATIBILITY='OFF', a non-zero IQ UNIQUE column specification in
a CREATE TABLE or ALTER TABLE statement that includes these data types returns an
error.

● ADD <table-constraint> – Adds a constraint to the table.


○ You can also add a foreign key constraint as a table constraint for a single-column or multicolumn
key. If PRIMARY KEY is specified, the table must not already have a primary key created by the
CREATE TABLE statement or another ALTER TABLE statement. See CREATE TABLE Statement
for a full explanation of table constraints.

 Note

You cannot MODIFY a table or column constraint. To change a constraint, DELETE the old
constraint and ADD the new constraint.

ALTER column-name column-alteration

Changes the column definition:

● SET DEFAULT <default-value> – changes the default value of an existing column in a table. You
can also use the MODIFY clause for this task, but ALTER is ISO/ANSI SQL compliant, and MODIFY is
not. Modifying a default value does not change any existing values in the table.
● DROP DEFAULT – removes the default value of an existing column in a table. You can also use the
MODIFY clause for this task, but ALTER is ISO/ANSI SQL compliant, and MODIFY is not. Dropping a
default does not change any existing values in the table.

SAP IQ SQL Reference


SQL Statements INTERNAL 1185
● ADD – adds a named constraint or a CHECK condition to the column. The new constraint or condition
applies only to operations on the table after its definition. The existing values in the table are not
validated to confirm that they satisfy the new constraint or condition.
● CONSTRAINT <column-constraint-name> – the optional column constraint name lets you modify
or drop individual constraints at a later time, rather than having to modify the entire column constraint.
● [CONSTRAINT <constraint-name>] CHECK (<condition>) – adds a CHECK constraint on the
column.
DROP drop-object

Drops a table object:

● DROP <column-name> – drops the column from the table. If the column is contained in any
multicolumn index, uniqueness constraint, foreign key, or primary key, then the index, constraint, or
key must be deleted before the column can be deleted. This does not delete CHECK constraints that
refer to the column. An IDENTITY/DEFAULT AUTOINCREMENT column can only be deleted if
IDENTITY_INSERT is turned off and the table is not a local temporary table.
● DROP CHECK – drops all check constraints for the table. This includes both table check constraints and
column check constraints.
● DROP CONSTRAINT <constraint-name> – drops the named constraint for the table or specified
column.
● DROP UNIQUE ( <column-name, ...> ) – drops the unique constraints on the specified
column(s). Any foreign keys referencing the unique constraint (rather than the primary key) are also
deleted. Reports an error if there are associated foreign-key constraints. Use ALTER TABLE to delete
all foreign keys that reference the primary key before you delete the primary key constraint.
● DROP PRIMARY KEY – drops the primary key. All foreign keys referencing the primary key for this
table are also deleted. Reports an error if there are associated foreign key constraints. If the primary
key is unenforced, DELETE returns an error if associated unenforced foreign key constraints exist.
● DROP FOREIGN KEY <role-name> – drops the foreign key constraint for this table with the given
role name. Retains the implicitly created non-unique HG index for the foreign key constraint. Users can
explicitly remove the HG index with the DROP INDEX statement.
● DROP [ PARTITION ] – drops the specified partition. The rows in partition P1 are deleted and the
partition definition is dropped. You cannot drop the last partition because dropping the last partition
would transform a partitioned table to a non-partitioned table. (To merge a partitioned table, use an
UNPARTITION clause instead.) For example:

CREATE TABLE foo (c1 INT, c2 INT)


PARTITION BY RANGE (c1)
(P1 VALUES <= (100) IN dbsp1,
P2 VALUES <= (200) IN dbsp2,
P3 VALUES <= (MAX) IN dbsp3
) IN dbsp4);
LOAD TABLE ….
ALTER TABLE DROP PARTITION P1;

RENAME rename-object

Renames an object in the table:

● RENAME <new-table-name> – changes the name of the table to the <new-table-name>. Any
applications using the old table name must be modified. Also, any foreign keys that were automatically
assigned the same name as the old table name do not change names.
● RENAME <column-name> TO <new-column-name> – changes the name of the column to <new-
column-name>. Any applications using the old column name must be modified.

SAP IQ SQL Reference


1186 INTERNAL SQL Statements
● RENAME [ PARTITION ] – renames an existing partition.
● RENAME <constraint-name> TO <new-constraint-name> – changes the name of the constraint
to <new-constraint-name>. Any applications using the old constraint name must be modified.
MOVE

Moves a table object.

● A table object can only reside in one dbspace. Any type of ALTER MOVE blocks any modification to the
table for the entire duration of the move.

 Note

You cannot move objects to a cache dbspace.

● MOVE TO – moves all table objects including columns, indexes, unique constraints, primary key, foreign
keys, and metadata resided in the same dbspace as the table is mapped to the new dbspace. The
ALTER Column MOVE TO clause cannot be requested on a partitioned table.
A BIT data type column cannot be explicitly placed in a dbspace. The following is not supported for BIT
data types:

ALTER TABLE t2 alter c1_bit MOVE TO iq_main;

● MOVE TABLE METADATA – moves the metadata of the table to a new dbspace. For a partitioned table,
MOVE TABLE METADATA also moves metadata that is shared among partitions.
● MOVE PARTITION – moves the specified partition to the new dbspace.

 Note

You cannot use the MOVE PARTITION clause on a DAS dbfile.

PARTITION BY

Divides large tables into smaller, more manageable storage objects.

● Partitions share the same logical attributes of the parent table, but can be placed in separate dbspaces
and managed individually. SAP IQ supports several table partitioning schemes:
○ Hash-partitions
○ Range-partitions
○ Composite-partitions
● A partition-key is the column or columns that contain the table partitioning keys. Partition keys can
contain NULL and DEFAULT values, but cannot contain:
○ LOB (BLOB or CLOB) columns
○ BINARY, or VARBINARY columns
○ CHAR or VARCHAR columns that are 255 bytes long
○ BIT columns
○ FLOAT/DOUBLE/REAL columns
PARTITION BY RANGE

Partitions rows by a range of values in the partitioning column.

● Range partitioning is restricted to a single partition key column and a maximum of 1024 partitions. In a
range-partitioning-scheme, the partition-key is the column that contains the table partitioning keys:

range-partition-decl:

SAP IQ SQL Reference


SQL Statements INTERNAL 1187
<partition-name> VALUES <= ( {<constant-expr> | MAX } [ , { <constant-
expr> | MAX }]... )
[ IN <dbspace-name> ]

<partition-name> is required, and is the name of a new partition on which table rows are stored.
Partition names must be unique within the set of partitions on a table.
● <VALUE> – specifies the inclusive upper bound for each partition (in ascending order). The user must
specify the partitioning criteria for each range partition to guarantee that each row is distributed to
only one partition. NULLs are allowed for the partition column and rows with NULL as partition key
value belong to the first table partition. However, NULL cannot be the bound value.
There is no lower bound (MIN value) for the first partition. Rows of NULL cells in the first column of the
partition key will go to the first partition. For the last partition, you can either specify an inclusive upper
bound or MAX. If the upper bound value for the last partition is not MAX, loading or inserting any row
with partition key value larger than the upper bound value of the last partition generates an error.
● Max – denotes the infinite upper bound and can only be specified for the last partition.
● IN – specifies the dbspace in the <partition-decl> on which rows of the partition should reside.
● These restrictions affect partitions keys and bound values for range partitioned tables:
○ You can only range partition a non-partitioned table if all existing rows belong to the first partition.
○ Partition bounds must be constants, not constant expressions.
○ Partition bounds must be in ascending order according to the order in which the partitions were
created. That is, the upper bound for the second partition must be higher than for the first
partition, and so on.
In addition, partition bound values must be compatible with the corresponding partition-key
column data type. For example, VARCHAR is compatible with CHAR.
○ If a bound value has a different data type than that of its corresponding partition key column, SAP
IQ converts the bound value to the data type of the partition key column, with these exceptions:
○ Explicit conversions are not allowed. This example attempts an explicit conversion from INT to
VARCHAR and generates an error:

CREATE TABLE Employees(emp_name VARCHAR(20))


PARTITION BY RANGE(emp_name)
(p1 VALUES <=(CAST (1 AS VARCHAR(20))),
p2 VALUES <= (CAST (10 AS VARCHAR(20)))

○ Implicit conversions that result in data loss are not allowed. In this example, the partition bounds
are not compatible with the partition key type. Rounding assumptions may lead to data loss and an
error is generated:

CREATE TABLE emp_id (id INT) PARTITION BY RANGE(id) (p1 VALUES <=
(10.5), p2 VALUES <= (100.5))

○ In this example, the partition bounds and the partition key data type are compatible. The bound
values are directly converted to float values. No rounding is required, and conversion is supported:

CREATE TABLE id_emp (id FLOAT)


PARTITION BY RANGE(id) (p1 VALUES <= (10),
p2 VALUES <= (100))

○ Conversions from non-binary data types to binary data types are not allowed. For example, this
conversion is not allowed and returns an error:

CREATE TABLE newemp (name BINARY)


PARTITION BY RANGE(name)
(p1 VALUES <= ("Maarten"),

SAP IQ SQL Reference


1188 INTERNAL SQL Statements
p2 VALUES <= ("Zymmerman")

○ NULL cannot be used as a boundary in a range-partitioned table.


○ The row will be in the first partition if the cell value of the 1st column of the partition key evaluated
to be NULL. SAP IQ supports only single column partition keys, so any NULL in the partition key
distributes the row to the first partition.
PARTITION BY HASH

Maps data to partitions based on partition-key values processed by an internal hashing function.

● Hash partition keys are restricted to a maximum of eight columns with a combined declared column
width of 5300 bytes or less. For hash partitions, the table creator determines only the partition key
columns; the number and location of the partitions are determined internally.
In a hash-partitioning declaration, the partition-key is a column or group of columns, whose composite
value determines the partition where each row of data is stored:

hash-partitioning-scheme:
HASH ( <partition-key> [ , <partition-key>, … ] )

● Restrictions:
○ You can only hash partition a base table. Attempting to partitioning a global temporary table or a
local temporary table raises an error.
○ You can only hash partition a non-partitioned table that is empty.
○ You cannot add, drop, merge, or split a hash partition.
○ You cannot add or drop a column from a hash partition key.
PARTITION BY HASH RANGE

Subpartitions a hash-partitioned table by range.

● In a hash-range-partitioning-scheme declaration, a SUBPARTITION BY RANGE clause adds a new


range subpartition to an existing hash-range partitioned table:

hash-range-partitioning-scheme:
PARTITION BY HASH ( partition-key [ , partition-key, … ] )
[ SUBPARTITION BY RANGE ( range-partition-decl [ , range-partition-
decl ... ] ) ]

The hash partition specifies how the data is logically distributed and colocated; the range subpartition
specifies how the data is physically placed. The new range subpartition is logically partitioned by hash
with the same hash partition keys as the existing hash-range partitioned table. The range subpartition
key is restricted to one column.
● Restrictions:
○ You can only hash partition a base table. Attempting to partitioning a global temporary table or a
local temporary table raises an error.
○ You can only subpartition a hash-partitioned table by range if the table is empty.
○ You cannot add, drop, merge, or split a hash partition.
○ You cannot add or drop a column from a hash partition key.

 Note

Range-partitions and composite partitioning schemes, like hash-range partitions, require the
separately licensed VLDB Management option.

MERGE PARTITION

SAP IQ SQL Reference


SQL Statements INTERNAL 1189
Merges <partition-name-1> into <partition-name-2>. Two partitions can be merged if they are
adjacent partitions and the data resides on the same dbspace. You can only merge a partition with a lower
partition value into the adjacent partition with a higher partition value. Note that the server does not check
CREATE privilege on the dbspace into which the partition is merged. For an example of how to create
adjacent partitions, see CREATE TABLE Statement examples.
RENAME PARTITION

Renames an existing PARTITION.


UNPARTITION

Removes partitions from a partitioned table. Each column is placed in a single dbspace. Note that the
server does not check CREATE privilege on the dbspace to which data of all partitions is moved. ALTER
TABLE UNPARTITION blocks all database activities.

Remarks

The ALTER TABLE statement changes table attributes (column definitions and constraints) in a table that was
previously created. The syntax allows a list of alter clauses; however, only one table constraint or column
constraint can be added, modified, or deleted in each ALTER TABLE 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 server does not process requests referencing the same table while the statement
is being processed.

 Note

You cannot alter local temporary tables, but you can alter global temporary tables when they are in use by
only one connection.

If the table is in a SAN dbspace, altering the table to add these components in a DAS dbspace results in an
error:

● Column
● Primary key
● Foreign key
● Range partition (adding and splitting)

Table subcomponents cannot be created on DAS Dbspaces if the parent table is not a DAS dbspace table.

SAP IQ enforces REFERENCES and CHECK constraints. Table and/or column check constraints added in an
ALTER TABLE statement are evaluated, only if they are defined on one of the new columns added, as part of
that alter table operation. For details about CHECK constraints, see CREATE TABLE Statement [page 1377].

If SELECT <*> is used in a view definition and you alter a table referenced by the SELECT <*> , then you must
run ALTER VIEW <viewname> RECOMPILE to ensure that the view definition is correct and to prevent
unexpected results when querying the view.

SAP IQ SQL Reference


1190 INTERNAL SQL Statements
Privileges

Syntax 1
See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Requires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege

Syntax 2
The system privileges required for syntax 2 vary depending on the clause. See GRANT System Privilege
Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502] for assistance with granting
privileges.

Clause Privilege Name

ADD Requires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the underlying table

UNIQUE, PRIMARY KEY, or IQ UNIQUE column constraint requires above


along with REFERENCES object-level privilege on the underlying table.

FOREIGN KEY column constraint requires above along with one of:

● CREATE ANY INDEX system privilege


● CREATE ANY OBJECT system privilege
● REFERENCES object-level privilege on the base table

PARTITION BY RANGE requires above along with one of:

● CREATE ANY OBJECT system privilege


● CREATE object-level privilege on the dbspaces where the partition is be­
ing created.

ALTER column Requires one of:

● You own the table


● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

To alter a PRIMARY KEY or UNIQUE CONTRAINT also requires REFERENCES


object-level privilege on the table.

SAP IQ SQL Reference


SQL Statements INTERNAL 1191
Clause Privilege Name

DROP Column with no constraints requires one of:

● You own the underlying table


● ALTER ANY OBJECT system privilege
● ALTER ANY TABLE system privilege
● ALTER object-level privilege on the underlying table

Column or table with constraints requires one of:

● You own the underlying table


● ALTER ANY OBJECT system privilege
● ALTER ANY TABLE system privilege
● ALTER and REFERENCES object-level privilege on the underlying table

Partition on a table requires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

RENAME Requires one of:

● You own the table


● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

MOVE Requires one of:

● You own the table


● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the underlying table

Also requires one of:

● CREATE ANY OBJECT system privilege


● CREATE object-level privilege on the dbspace to which the partition is be­
ing moved

SPLIT PARTITION Requires one of:

● SELECT ANY TABLE system privilege


● SELECT object-level privilege on table

Also requires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

SAP IQ SQL Reference


1192 INTERNAL SQL Statements
Clause Privilege Name

MERGE PARTITION, UNPARTITION Table owned by self requires no additional privilege. Table owned by others re­
quires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

PARTITION BY Requires one of:

● You own the table


● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege
● ALTER object-level privilege on the table

Also requires one of:

● CREATE ANY OBJECT system privilege


● CREATE object-level privilege on the dbspaces where the partitions are
being created

DISABLE RLV store Requires one of:

● ALTER ANY TABLE system privilege


● ALTER ANY OBJECT system privilege

Side Effects

● Automatic commit. The ALTER and DROP options close all cursors for the current connection. The
Interactive SQL data window is also cleared.
● A checkpoint is carried out at the beginning of the ALTER TABLE operation.
● Once you alter a column or table, any stored procedures, views or other items that refer to the altered
column no longer work.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – some clauses are supported by SAP Adaptive Server Enterprise.

SAP IQ SQL Reference


SQL Statements INTERNAL 1193
Examples

● The following example adds a new column to the Employees table showing which office they work in:

ALTER TABLE Employees


ADD office CHAR(20)

● The following example drops the office column from the Employees table:

ALTER TABLE Employees


DROP office

● 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)

● The following example adds a new column CustomerNum to the Customers table and assigns a default
value of 88:

ALTER TABLE Customers


ADD CustomerNum INTEGER DEFAULT 88

● The following example moves FP indexes for c2, c4, and c5, from dbspace Dsp3 to Dsp6. FP index for c1
remains in Dsp1. FP index for c3 remains in Dsp2. The primary key for c5 remains in Dsp4. DATE index
c4_date remains in Dsp5:

CREATE TABLE foo (


c1 INT IN Dsp1,
c2 VARCHAR(20),
c3 CLOB IN Dsp2,
c4 DATE,
c5 BIGINT,
PRIMARY KEY (c5) IN Dsp4) IN Dsp3);
CREATE DATE INDEX c4_date ON foo(c4) IN Dsp5;
ALTER TABLE foo
MOVE TO Dsp6;

● The following example moves only FP index c1 from dbspace Dsp1 to Dsp7:

ALTER TABLE foo ALTER c1 MOVE TO Dsp7

● The following example uses many ALTER TABLE clauses to move, split, rename, and merge partitions.
Create a partitioned table:

CREATE TABLE bar (


c1 INT,
c2 DATE,
c3 VARCHAR(10))
PARTITION BY RANGE(c2)
(p1 VALUES <= ('2005-12-31') IN dbsp1,
p2 VALUES <= ('2006-12-31') IN dbsp2,
P3 VALUES <= ('2007-12-31') IN dbsp3,
P4 VALUES <= ('2008-12-31') IN dbsp4);
INSERT INTO bar VALUES(3, '2007-01-01', 'banana nut');
INSERT INTO BAR VALUES(4, '2007-09-09', 'grape jam');
INSERT INTO BAR VALUES(5, '2008-05-05', 'apple cake');

SAP IQ SQL Reference


1194 INTERNAL SQL Statements
○ This example moves partition p2 to dbsp5:

ALTER TABLE bar MOVE PARTITION p2 TO DBSP5;

○ This example splits partition p4 into 2 partitions:

ALTER TABLE bar SPLIT PARTITION p4 INTO


(P41 VALUES <= ('2008-06-30') IN dbsp4,
P42 VALUES <= ('2008-12-31') IN dbsp4);

○ This example reports an error, as it requires data movement. Not all existing rows are in the same
partition after split.

ALTER TABLE bar SPLIT PARTITION p3 INTO


(P31 VALUES <= ('2007-06-30') IN dbsp3,
P32 VALUES <= ('2007-12-31') IN dbsp3);

This error is reported:


No data move is allowed, cannot split partition p3.
○ This example reports an error, because it changes the partition boundary value:

ALTER TABLE bar SPLIT PARTITION p2 INTO


(p21 VALUES <= ('2006-06-30') IN dbsp2,
P22 VALUES <= ('2006-12-01') IN dbsp2);

This error is reported:


Boundary value for the partition p2 cannot be changed.
○ This example merges partition p3 into p2:

ALTER TABLE bar MERGE PARTITION p3 into p2;

This error is reported, as a merge from a higher boundary value partition into a lower boundary value
partition is not allowed:
Partition 'p2' is not adjacent to or before partition 'p3'.
○ This example merges partition p2 into p3:

ALTER TABLE bar MERGE PARTITION p2 INTO P3;

○ This example renames partition p1 to p1_new:

ALTER TABLE bar RENAME PARTITION p1 TO p1_new;

○ This example partitions table bar. This command reports an error, because all rows must be in the first
partition:

ALTER TABLE bar PARTITION BY RANGE(c2)


(p1 VALUES <= ('2005-12-31') IN dbsp1,
P2 VALUES <= ('2006-12-31') IN DBSP2,
P3 VALUES <= ('2007-12-31') IN dbsp3,
P4 VALUES <= ('2008-12-31') IN dbsp4);

This error is reported:


All rows must be in the first partition.
○ This example partitions table bar:

ALTER TABLE bar PARTITION BY RANGE(c2)


(p1 VALUES <= ('2008-12-31') IN dbsp1,

SAP IQ SQL Reference


SQL Statements INTERNAL 1195
P2 VALUES <= ('2009-12-31') IN dbsp2,
P3 VALUES <= ('2010-12-31') IN dbsp3,
P4 VALUES <= ('2011-12-31') IN dbsp4);

○ This example unpartitions table bar:

ALTER TABLE bar UNPARTITION;

● The following example changes a table tab1 so that it is no longer registered for in-memory real-time
updates in the RLV store.

ALTER TABLE tab1 DISABLE RLV STORE

Related Information

%TYPE and %ROWTYPE attributes [page 93]


sp_iqrename Procedure [page 744]
CREATE TABLE Statement [page 1377]
DROP Statement [page 1433]
IDENTITY_INSERT Option [page 1867]
FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]
FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
REVOKE System Privilege Statement [page 1635]

9.4.22 ALTER TEXT CONFIGURATION Statement

Alters a text configuration object.

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

 Syntax

ALTER TEXT CONFIGURATION [ <owner>.]<config-name>


STOPLIST <stoplist>
| DROP STOPLIST
| { MINIMUM | MAXIMUM } TERM LENGTH <integer>
| TERM BREAKER
{ GENERIC [ EXTERNAL NAME <external-call> ] | NGRAM }
| PREFILTER EXTERNAL NAME <external-call>
| DROP PREFILTER

<external-call> ::=
[ <system-configuration>:]<function-name>@<library-file-prefix>
[ .{ so | dll} ]

SAP IQ SQL Reference


1196 INTERNAL SQL Statements
<system-configuration> ::=
{ <generic-operating-system>
| <specific-operating-system> }
[ (<processor-architecture>) ]

<generic-operating-system> ::=
{ UNIX | Windows }

<specific-operating-system> ::=
{ AIX | HPUX | Linux | OSX | Solaris | WindowsNT }

<processor-architecture> ::=
{ 32 | 64 | ARM | IA64 | PPC | SPARC | X86 | X86_64 }

Go to:

● Remarks
● Privileges
● Side Effects
● Examples

Parameters

(back to top)

DROP stoplist

A string expression used to create or replace the list of terms to ignore when building a TEXT index. Terms
specified in this list are also ignored in a query. Separate stoplist terms with spaces.

Stoplist terms cannot contain whitespace and should not contain non-alphanumeric characters. Non-
alphanumeric characters are interpreted as spaces and break the term into multiple terms. For example,
“and/or” is interpreted as the two terms “and” and “or”. The maximum number of stoplist terms is 7999.
DROP STOPLIST

Use to drop the stoplist for a text configuration object.


MINIMUM TERM LENGTH

Specifies the minimum length, in characters, of a term to include in the TEXT index. The value specified in
the MINIMUM TERM LENGTH clause is ignored when using NGRAM TEXT indexes. 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

With GENERIC TEXT indexes, specifies 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

SAP IQ SQL Reference


SQL Statements INTERNAL 1197
Specifies the name of the algorithm to use for separating column values into terms. The choices for IN
SYSTEM tables are GENERIC (the default) or NGRAM. The GENERIC algorithm treats any string of one or
more alphanumerics, separated by non-alphanumerics, as a term. The 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. NGRAM is supported for IN SYSTEM tables. NGRAM term
breaker is built on TEXT indexes, so use text configuration object settings to define whether to use an
NGRAM or GENERIC TEXT index. TERM BREAKER can include the specification for the external term
breaker library using EXTERNAL NAME and the library entry point.
PREFILTER EXTERNAL NAME

Specifies the entry_point and the library name of the external pre-filter library provided by external
vendors.
DROP PREFILTER

Drops the external prefilter and sets NULL to the prefilter columns in ISYSTEXTCONFIG table.

Remarks

(back to top)

TEXT indexes are dependent on a text configuration object. SAP IQ TEXT indexes use immediate refresh, and
cannot be truncated; you must drop the indexes before you can alter the text configuration object. To view the
settings for text configuration objects, query the SYSTEXTCONFIG system view.

Privileges

(back to top)

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

Clause Privilege Name

TERM BREAKER or PRE­ Requires:


FILTER EXTERNAL
● CREATE ANY EXTERNAL REFERENCE system privilege
NAME
Also requires one of:

● You own the text configuration object


● ALTER ANY TEXT CONFIGURATION system privilege
● ALTER ANY OBJECT system privilege

All other clauses regard­ ALTER ANY TEXT CONFIGURATION system privilege
less of object ownership

SAP IQ SQL Reference


1198 INTERNAL SQL Statements
Side Effects

(back to top)

Automatic commit

Examples

(back to top)

● The following example creates a text configuration object, maxTerm16, and then change the maximum
term length to 16:

CREATE TEXT CONFIGURATION maxTerm16 FROM default_char;


ALTER TEXT CONFIGURATION maxTerm16 MAXIMUM TERM LENGTH 16;

● The following example adds stoplist terms to the maxTerm16 configuration object:

ALTER TEXT CONFIGURATION maxTerm16


STOPLIST 'because about therefore only';

● The following example updates the text configuration object, my_text_config, to use the entry point
my_term_breaker in the external library mytermbreaker.dll for breaking the text:

CREATE TEXT CONFIGURATION my_text_config FROM default_char;


ALTER TEXT CONFIGURATION my_text_config
TERM BREAKER GENERIC EXTERNAL NAME 'platform:my_term_breaker@mytermbreaker';

● The following example updates the text configuration object, my_text_config, to use the entry point
my_prefilter in the external library myprefilter.dll for prefiltering the documents:

ALTER TEXT CONFIGURATION my_text_config


PREFILTER EXTERNAL NAME 'platform:my_prefilter@myprefilter';

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.23 ALTER TEXT INDEX Statement

Renames, moves or alters the definition of a TEXT index.

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

SAP IQ SQL Reference


SQL Statements INTERNAL 1199
 Syntax

ALTER TEXT INDEX [ <owner>.]<text-index-name>


ON [<owner>.]<table-name>
<alter-clause>

<alter-clause> ::=
<rename-object> | <move-object>

<rename-object> ::=
RENAME { AS | TO } <new-name>

<move-object> ::=
MOVE TO <dbspace-name>

Parameters

RENAME

Renames the TEXT index.


MOVE

Moves the TEXT index to the specified dbspace.

Privileges

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

Clause Privilege Name

<move-object> Requires one of:

● You own the object


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● REFERENCES object-level privilege the underlying table

SAP IQ SQL Reference


1200 INTERNAL SQL Statements
Clause Privilege Name

<rename-object> Requires one of:

● ALTER ANY INDEX system privilege


● ALTER ANY OBJECT system privilege
● MANAGE ANY DBSPACE system privilege

Also requires one of:

● You own the object


● REFERENCES object-level privilege on the table, along with one of:
○ CREATE ANY OBJECT system privilege
○ CREATE object-level privilege on the target dbspace.

Side Effects

Automatic commit

Examples

The following example creates a TEXT index, MyTextIndex, defining it as IMMEDIATE REFRESH, rename the
TEXT index to Text_index_daily, and move the TEXT index to a dbspace named tispace:

CREATE TEXT INDEX MyTextIndex ON Customers ( CompanyName ) IMMEDIATE REFRESH;


ALTER TEXT INDEX MyTextIndex ON Customers RENAME AS Text_index_daily;
ALTER TEXT INDEX Text_Index_Daily ON Customers MOVE TO tispace;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.24 ALTER TRIGGER statement

Replaces a trigger definition with a modified version. You must include the entire new trigger definition in the
ALTER TRIGGER statement. This statement applies to SAP IQ catalog store tables only.

 Syntax

Change the definition of a trigger

ALTER TRIGGER <trigger-name> <trigger-definition>

SAP IQ SQL Reference


SQL Statements INTERNAL 1201
<trigger-definition> : CREATE TRIGGER syntax

Obfuscate a trigger definition

ALTER TRIGGER <trigger-name> ON [<owner.>] <table-name> SET HIDDEN

Remarks

Change the definition of a trigger

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.
Obfuscate a trigger definition

 Note

The SET HIDDEN operation is irreversible.

Privileges

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

Clause Privilege Name

Alter a trigger on a view Requires one of:

● You own the underlying table referenced by the trigger


● ALTER ANY TRIGGER system privilege
● ALTER ANY OBJECT system privilege
● CREATE ANY OBJECT system privilege and ALTER object-level privilege
on the underlying table

Alter a trigger on a materialized view Requires one of:

● You own the materialized view


● ALTER ANY TRIGGER system privilege and ALTER ANY VIEW system
privilege
● ALTER ANY OBJECT system privilege

SAP IQ SQL Reference


1202 INTERNAL SQL Statements
Side effects

Automatic commit.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

CREATE TRIGGER statement [page 1395]


DROP TRIGGER statement [page 1463]
CREATE TRIGGER statement [page 1395]
DROP TRIGGER statement [page 1463]
REVOKE System Privilege Statement [page 1635]

9.4.25 ALTER USER Statement

Changes user settings.

 Syntax

Syntax 1 – Changes the Definition of a Database User

ALTER USER <user-name>


| [ IDENTIFIED BY <password> ]
| [ LOGIN POLICY <policy-name> ]
| [ FORCE PASSWORD CHANGE { ON | OFF } ]

Syntax 2 – Refreshes the Distinguished Name (DN) for an LDAP User

ALTER USER <user-name>


REFRESH DN

Syntax 3 – Reverts a User's Login Policy to the Original Values

ALTER USER <user-name>


RESET LOGIN POLICY

SAP IQ SQL Reference


SQL Statements INTERNAL 1203
Syntax 4 – Changes a User's Password When CHANGE_PASSWORD_DUAL_CONTROL is
Enabled in a User's Login Policy

ALTER USER <user-name>


IDENTIFIED [ FIRST | LAST ]
BY <password_part>

Parameters

user-name

Name of the user.


IDENTIFIED BY password

The password for the user. Clause is not supported (ERROR) when
CHANGE_PASSWORD_DUAL_CONTROL option is enabled in a user's login policy.
LOGIN POLICY policy-name

Name of the login policy to assign the user. No change is made if you do not specify a login policy. No
change is made if the LOGIN POLICY clause is not specified.
FORCE PASSWORD CHANGE { ON | OFF }

Controls whether the user must specify a new password upon logging in. This setting overrides the
PASSWORD_EXPIRY_ON_NEXT_LOGIN option setting in the user's login policy.

 Note

This functionality is not currently implemented when logging in to SAP IQ Cockpit. However, when
logging in to SAP IQ outside of SAP IQ Cockpit (for example, using Interactive SQL), users are then
prompted to enter a new password.

REFRESH DN

Clears the saved DN and timestamp for a user, which is used during LDAP authentication.
RESET LOGIN POLICY

Reverts the settings of the user's login to the original values in the login policy. This usually clears all locks
that are implicitly set due to the user exceeding the failed logins or exceeding the maximum number of
days since the last login. 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.
IDENTIFIED [ FIRST | LAST ] BY

Required when CHANGE_PASSWORD_DUAL_CONTROL option is enabled in a target user's login policy.


The FIRST and LAST keywords specify the part of the dual password part being defined.
password

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 role and do not want anyone to connect to the database using
the role user ID. A user ID must be a valid identifier. User IDs and passwords cannot:

● Begin with white space, single quotes, or double quotes

SAP IQ SQL Reference


1204 INTERNAL SQL Statements
● End with white space
● Contain semicolons

A password can be either a valid identifier, or a string (maximum 255 characters) placed in single quotes.
Passwords are case-sensitive. The password should be composed of 7-bit ASCII characters, as other
characters may not work correctly if the database server cannot convert them from the client's character
set to UTF-8.

You can use the VERIFY_PASSWORD_FUNCTION option to specify a function to implement password rules
(for example, passwords must include at least one digit). If you do use a password verification function, you
cannot specify more than one user ID and password in the GRANT CONNECT statement.

The encryption algorithm used for hashing the user passwords is FIPS-certified encryption support:

● The DLL is called dbfips10.dll.


● The HASH function accepts the algorithms: SHA1_FIPS SHA256_FIPS.
● If the -fips server option is specified and an algorithm that is not FIPS-certified is given to the HASH
function, the database server uses SHA1_FIPS instead of SHA1, SHA256_FIPS instead of SHA256, and
returns an error if MD5 is used (MD5 is not a FIPS-certified algorithm).
● If the -fips option is specified, the database server uses SHA256_FIPS for password hashing.

Remarks

User IDs and passwords cannot have the following properties:

● Begin with white space, single quotes, or double quotes


● End with white space
● Contain semicolons

Passwords cannot exceed 255 characters.

If you set the PASSWORD_EXPIRY_ON_NEXT_LOGIN value to ON, the passwords of all users assigned to this
login policy expire immediately when he or she next logs in. You can use the ALTER USER and LOGIN POLICY
clauses to force users to change their passwords at the next login.

If the CHANGE_PASSWORD_DUAL CONTROL login policy option is disable (OFF) during the dual password
change process:

● The target user will be unable to log in with the single password part already defined. The ALTER USER
statement must be reissued using single password control syntax.
● If the option is disabled after the dual password change process is complete, but before the target user
logs in, there is no impact on the target user. The target user must log in using both password parts.

If the target user is already logged in when the dual password change process occurs, the user cannot change
their password in the current session until both parts of the new password are set. Once the dual password
change process is complete, the target user can use GRANT CONNECT, ALTER USER, sp_password, or
sp_iqpassword to the password without first logging out. The prompt to enter the current password, use the
new dual control password, not the password originally entered for the current session.

The GRANT CONNECT statement is not supported during for the dual password change process to set either
password part. However, once the dual password change process is complete, the target user can use the
GRANT CONNECT statement, ALTER USER, sp_password, or sp_iqpassword to change their password
without first logging out.

SAP IQ SQL Reference


SQL Statements INTERNAL 1205
As soon as both parts of the password are successfully specified by users with the CHANGE PASSWORD
system privilege, the password for the target user is automatically expired. This forces the target user to
change the password the next time he or she logs in.

The encryption algorithm used for hashing the user passwords is FIPS-certified encryption support the
following:

● The DLL is called dbfips10.dll


● The HASH function accepts the algorithms SHA1_FIPS and SHA256_FIPS
● If the -fips server option is specified and an algorithm that is not FIPS-certified is given to the HASH
function, the database server uses SHA1_FIPS instead of SHA1, SHA256_FIPS instead of SHA256, and
returns an error if MD5 is used (MD5 is not a FIPS-certified algorithm).
● If the -fips option is specified, the database server uses SHA256_FIPS for password hashing.

Privileges

● To change your own password, no additional privilege is required.


● To change the password of another user requires the CHANGE PASSWORD system privilege.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example 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

● The following example clears the distinguished name (DN) and timestamp for a user named Mary used for
LDAP authentication:

ALTER USER Mary REFRESH DN

● The following example sets the password for user3 to PassPart1PassPart2. This assumes that user1
and user2 have the CHANGE PASSWORD system privilege and the change_password_dual_control
option is enabled (ON) in the login policy for user3:

SAP IQ SQL Reference


1206 INTERNAL SQL Statements
1. User1 enters:

ALTER USER user3 IDENTIFIED FIRST BY PassPart1

2. User2 enters:

ALTER USER user3 IDENTIFIED LAST BY PassPart2

3. Once set, user3 logs on by entering the password PassPart1PassPart2.

Related Information

(Deprecated) sp_iqpassword Procedure [page 725]


COMMENT Statement [page 1233]
CREATE LOGIN POLICY Statement [page 1307]
CREATE USER Statement [page 1402]
DROP LOGIN POLICY Statement [page 1445]
DROP USER Statement [page 1464]
ALTER LOGIN POLICY Statement [page 1155]
GRANT ROLE Statement [page 1504]
GRANT System Privilege Statement [page 1511]
REVOKE System Privilege Statement [page 1635]
REVOKE ROLE Statement [page 1630]
REVOKE System Privilege Statement [page 1635]

9.4.26 ALTER VIEW Statement

Replaces a view definition with a modified version.

 Syntax

Syntax 1 – Alters the Structure of the View

ALTER VIEW
… [<owner>.]<view-name> [ ( <column-name> [ , … ] ) ]
… AS <select-statement>
… [ WITH CHECK OPTION ]

Syntax 2 – Changes Attributes for the View

ALTER VIEW
… [<owner>.]<view-name>
… { SET HIDDEN | RECOMPILE | DISABLE | ENABLE }

SAP IQ SQL Reference


SQL Statements INTERNAL 1207
Parameters

AS select-statement

The SELECT statement on which the view is based must not contain an ORDER BY clause, a subquery in
the SELECT list, or a TOP or FIRST qualification. It may have a GROUP BY clause and may be a UNION.
WITH CHECK OPTION

Rejects any updates and inserts to the view that do not meet the criteria of the views as defined by its
SELECT statement. However, SAP IQ currently ignores this option (it supports the syntax for compatibility
reasons).
SET HIDDEN

Obfuscates the definition of the view and cause the view to become hidden from view, for example in SAP
IQ Cockpit. Explicit references to the view still work.

 Caution

The SET HIDDEN operation is irreversible.

When you use SET HIDDEN, you can unload and reload the view into other databases. Debugging using the
debugger does not show the view definition, nor is it 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.
RECOMPILE

Re-creates the column definitions for the view. Identical in functionality to the ENABLE clause, except you
can use it on a view that is not disabled.
DISABLE

Disables the view from use by the database server.

When you use the DISABLE clause, the view is no longer available for use by the database server to answer
queries. Disabling a view is similar to dropping one, 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 to any dependent views, which are also disabled.
ENABLE

Enables a disabled view, which causes the database server to re-create the column definitions for the view.
Before you enable a view, you must enable any views on which it depends.

Remarks

When you alter a view, existing permissions on the view are maintained and do not require reassignment.
Instead of using the ALTER VIEW statement, you could also drop the view and re-create it using DROP VIEW
and CREATE VIEW, respectively. If you do this, view permissions must 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. If you
made changes that impact a dependent view, that view may become invalid, requiring you to alter the definition
for the dependent view.

SAP IQ SQL Reference


1208 INTERNAL SQL Statements
 Caution

If the SELECT statement defining the view contains an asterisk (*), the number of the columns in the view
could change if columns were added or deleted from the underlying tables. The names and data types of
the view columns could also change.

Altering the structure of a view requires that you replace the entire view definition with a new definition, much
as you would when creating the view using the CREATE VIEW statement.

Privileges

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

Clause Privilege Required

RECOMPILE or ENABLE clause for view Requires one of:

● You own the view.


● ALTER ANY VIEW system privilege.
● ALTER ANY OBJECT system privilege.

● Also requires one of:


○ SELECT ANY TABLE system privilege.
○ SELECT object-level privilege on the underlying tables of the view.

RECOMPILE or ENABLE clause for materi­ Requires one of:


alized view
● You own the materialized view.
● ALTER ANY MATERIALNESS VIEW system privilege.
● ALTER ANY OBJECT system privilege.

● Also requires one of:


○ SELECT ANY TABLE system privilege.
○ SELECT object-level privilege on the underlying tables of the materi­
alized view.

DISABLE clause for view Requires one of:

● You own the view.


● ALTER ANY VIEW system privilege.
● ALTER ANY OBJECT system privilege.

DISABLE clause for materialized view Requires one of:

● You own the materialized view.


● ALTER ANY MATERIALIZED VIEW system privilege.
● ALTER ANY OBJECT system privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1209
Clause Privilege Required

All other clauses for view or materialized Require one of:


view
● You own the view.
● ALTER ANY OBJECT system privilege.

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 regularly alter views.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

In this section:

Identifying and Fixing Invalid Dependent Views [page 1211]


Check for, and correct, any dependent views that become invalid due to changes to their underlying
tables.

Related Information

CREATE VIEW Statement [page 1408]


DROP Statement [page 1433]
Identifying and Fixing Invalid Dependent Views [page 1211]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1210 INTERNAL SQL Statements
9.4.26.1 Identifying and Fixing Invalid Dependent Views

Check for, and correct, any dependent views that become invalid due to changes to their underlying tables.

Context

Under most circumstances the database server automatically recompiles views to keep them valid if the
underlying tables change. However, if your table alteration removes or materially changes something
referenced by the view definition, then the dependent view becomes invalid. For example, if you remove a
column referenced in the view definition, then the dependent view is no longer valid. Correct the view definition
and manually recompile the view.

Procedure

1. Run sa_dependent_views to get the list of dependent views.


2. Perform the DDL operation that alters the table. The server automatically disables dependent views, and
attempts to recompile them once the DDL is complete.
3. Check that all the views listed by sa_dependent_views are valid. For example, perform a simple test such
as SELECT * FROM myview.
4. If a view is invalid, it is likely you will need to alter the view definition to resolve the issue. Examine the view
definition against the DDL change that you made and make the necessary changes. Run ALTER VIEW
RECOMPILE to correct the view definition.
5. Test the corrected view to make sure it works. For example, perform a simple test such as SELECT * FROM
myview.

Results

The sa_dependent_views system procedure returns the list of all dependent views for a given table or view.

Related Information

ALTER VIEW Statement [page 1207]

SAP IQ SQL Reference


SQL Statements INTERNAL 1211
9.4.27 BACKUP DATABASE Statement

Backs up an SAP IQ database on one or more archive devices.

 Syntax

BACKUP DATABASE
[ <backup-option> … ]
TO <archive_device> [ <archive-option>... ]
… [ WITH COMMENT <string> ]

<backup-option> ::=
{ READWRITE FILES ONLY |
READONLY <dbspace-or-file> [, … ] }
CRC { ON | OFF }
ATTENDED { ON | OFF }
BLOCK FACTOR <integer>
{ FULL | INCREMENTAL | INCREMENTAL SINCE FULL }
VIRTUAL { DECOUPLED |
ENCAPSULATED '<shell_command>' }
POINT IN TIME RECOVERY LOGS ONLY
WITH COMMENT <comment>

<dbspace-or-file> ::=
{ DBSPACES <identifier-list> | FILES <identifier-list> | <archive-root> }

<identifier-list> ::=
<identifier> [, … ]

<archive-option> ::=
SIZE <integer> STACKER <integer>

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

TO archive_device

Specifies the name of the <archive_device> to be used for backup, delimited with single quotation
marks. The <archive_device> is a file name or tape drive device name for the archive file. If you use
multiple archive devices, specify them using separate TO clauses; a comma-separated list is not allowed.
Archive devices must be distinct. The number of TO clauses determines the amount of parallelism SAP IQ
attempts with regard to output devices.
WITH COMMENT string

SAP IQ SQL Reference


1212 INTERNAL SQL Statements
Specifies an optional comment recorded in the archive file and in the backup history file. Maximum length
is 32 KB. If you do not specify a value, a NULL string is stored.
READWRITE FILES ONLY

Restricts FULL, INCREMENTAL, and INCREMENTAL SINCE FULL backups to only the set of read-write files
in the database. The read-write dbspaces/files must be SAP IQ dbspaces.

If READWRITE FILES ONLY clause is used with an INCREMENTAL or INCREMENTAL SINCE FULL backup,
the backup will not back up data on read-only dbspaces or dbfiles that has changed since the depends-on
backup. If READWRITE FILES ONLY is not specified for an INCREMENTAL or INCREMENTAL SINCE FULL
backup, the backup backs up all database pages that have changed since the depends-on backup, both on
read-write and read-only dbspaces.
CRC { ON | OFF }

Activates 32-bit cyclical redundancy checking on a per block basis (in addition to whatever error detection
is available in the hardware). When you specify this clause, the numbers computed on backup are verified
during any subsequent restore operation, affecting performance of both commands. The default is ON.
ATTENDED { ON | OFF }

Applies only when backing up to a tape device. If ATTENDED ON clause (the default) is used, a message is
sent to the application that issued the BACKUP DATABASE statement if the tape drive requires
intervention. This might happen, for example, when a new tape is required. If you specify OFF, BACKUP
DATABASE does not prompt for new tapes. If additional tapes are needed and OFF has been specified, SAP
IQ gives an error and aborts the BACKUP DATABASE command. However, a short delay is included to
account for the time an automatic stacker drive requires to switch tapes.
BLOCK FACTOR integer

Specifies the number of blocks to write at one time. The value must be greater than 0, or SAP IQ generates
an error message. Its default is 25 for UNIX systems and 15 for Windows systems (to accommodate the
smaller fixed tape block sizes). This clause effectively controls the amount of memory used for buffers. The
actual amount of memory is this value times the block size times the number of threads used to extract
data from the database. Set BLOCK FACTOR to at least 25.
FULL | INCREMENTAL | INCREMENTAL SINCE FULL

● FULL – specifies a full backup; all blocks in use in the database are saved to the archive devices. This is
the default action.
● INCREMENTAL – specifies an incremental backup; all blocks changed since the last backup of any kind
are saved to the archive devices. The keyword INCREMENTAL is not allowed with READONLY FILES.
● INCREMENTAL SINCE FULL – specifies an incremental backup; all blocks changed since the last full
backup are saved to the archive devices.
VIRTUAL DECOUPLED

Specifies a decoupled virtual backup. For the backup to be complete, copy the SAP IQ dbspaces after the
decoupled virtual backup finishes, and then perform a nonvirtual incremental backup.
VIRTUAL ENCAPSULATED 'shell_command'

Specifies an encapsulated virtual backup. The ‘shell-command’ argument can be a string or variable
containing a string that is executed as part of the encapsulated virtual backup. The shell commands
execute a system-level backup of the IQ store as part of the backup operation. For security reasons, it is
recommended that an absolute path be specified in the 'shell-command,' and file protections on that
directory be in place to prevent execution of an unintended program.
POINT IN TIME RECOVERY LOGS ONLY

SAP IQ SQL Reference


SQL Statements INTERNAL 1213
Backs up the point-in-time (PITR) logs to the dbspace set with the ALTER DBSPACE IQ_SYSTEM_LOG
RENAME statement:

BACKUP DATABASE
POINT IN TIME RECOVERY LOGS ONLY TO ' PITR-archive-directory '

The PITR archive directory is set with the ALTER DBSPACE IQ_SYSTEM_LOG RENAME statement.

POINT IN TIME RECOVERY LOGS ONLY supports only one TO clause, which must point to the PITR archive
directory. No other options are allowed.
SIZE integer

Specifies maximum tape or file capacity per output device (some platforms do not reliably detect end-of-
tape markers). No volume used on the corresponding device should be shorter than this value. This value
applies to both tape and disk files but not third-party devices. Units are kilobytes (KB), although in general,
less than 1 GB is inappropriate. For example, for a 3.5 GB tape, specify 3500000. Defaults are by platform
and medium. The final size of the backup file will not be exact, because backup writes in units of large
blocks of data.

If a size less than 1 GB is specified, a SIZE warning message appears. The backup proceeds but uses the
minimum default file size instead of the specified value. For example, if you specify a file size of 1000000
KB, a default file size of 2 GB (UNIX) or 1.5 GB (Windows) is used instead.

Platform Default SIZE for Tape Default SIZE for Disk

UNIX None 2 GB (2097152 KB)

Windows 1.5 GB 1.5 GB (1572864 KB)

SIZE must be a multiple of 64. Other values are


rounded down to a multiple of 64.

The SIZE parameter is per output device. SIZE does not limit the number of bytes per device; SIZE limits
the file size. Each output device can have a different SIZE parameter. During backup, when the amount of
information written to a given device reaches the value specified by the SIZE parameter, BACKUP
DATABASE does one of the following:

● If the device is a file system device, BACKUP DATABASE closes the current file and creates another file
of the same name, with the next ascending number appended to the file name, for example,
bkup1.dat1.1, bkup1.dat1.2, bkup1.dat1.3.
● If the device is a tape unit, BACKUP DATABASE closes the current tape and you need to mount another
tape.

STACKER integer

Specifies that the device is automatically loaded, and specifies the number of tapes with which it is loaded.
This value is not the tape position in the stacker, which could be zero. When ATTENDED is OFF and
STACKER is ON, SAP IQ waits for a predetermined amount of time to allow the next tape to be autoloaded.
The number of tapes supplied along with the SIZE clause are used to determine whether there is enough
space to store the backed-up data. Do not use this clause with third-party media management devices.

SAP IQ SQL Reference


1214 INTERNAL SQL Statements
Remarks

(back to top)

The SAP IQ database might be open for use by many readers and writers when you execute a BACKUP
DATABASE command. It acts as a read-only user and relies on the Table Level Versioning feature of SAP IQ to
achieve a consistent set of data.

BACKUP DATABASE implicitly issues a CHECKPOINT prior to commencing, and then it backs up the catalog
tables that describe the database (and any other tables you have added to the catalog store). During this first
phase, SAP IQ does not allow any metadata changes to the database (such as adding or dropping columns and
tables). Correspondingly, a later RESTORE DATABASE of the backup restores only up to that initial
CHECKPOINT.

The BACKUP DATABASE command lets you specify full or incremental backups. You can choose two types of
incremental backups:

● INCREMENTAL backs up only those blocks that have changed and committed since the last backup of any
type (incremental or full).
● INCREMENTAL SINCE FULL backs up all of the blocks that have changed since the last full backup.

The first type of incremental backup can be smaller and faster to do for BACKUP DATABASE commands, but
slower and more complicated for RESTORE DATABASE commands. The opposite is true for the other type of
incremental backup. The reason is that the first type generally results in N sets of incremental backup archives
for each full backup archive. If a restore is required, a user with the SERVER OPERATOR system privilege must
restore the full backup archive first, and then each incremental archive in the proper order. (SAP IQ keeps track
of which ones are needed.) The second type requires the user with the SERVER OPERATOR system privilege to
restore only the full backup archive and the last incremental archive.

Incremental virtual backup is supported using the VIRTUAL DECOUPLED and VIRTUAL ENCAPSULATED
parameters of the BACKUP DATABASE statement.

Although you can perform an OS-level copy of tablespaces to make a virtual backup of one or more read-only
dbspaces, use the virtual backup statement, because it records the backup in the SAP IQ system tables.

BACKUP DATABASE and RESTORE DATABASE write your SAP IQ data in parallel to or from all of the archive
devices you specify. The catalog store is written serially to the first device. Faster backups and restores result
from greater parallelism.

SAP IQ supports a maximum of 36 hardware devices for backup. For faster backups, specifying one or two
devices per core will help to avoid hardware and IO contention. Set the SIZE parameter on the BACKUP
DATABASE command to avoid creating multiple files per backup device and consider the value used in the
BLOCK FACTOR clause on the BACKUP DATABASE command.

BACKUP DATABASE overwrites existing archive files unless you move the old files or use a different
<archive_device> name or path.

The backup API DLL implementation lets you specify arguments to pass to the DLL when opening an archive
device. For third-party implementations, the archive_device string has this format:

'DLLidentifier::vendor_specific_information'

A specific example:

'spsc::workorder=12;volname=ASD002'

SAP IQ SQL Reference


SQL Statements INTERNAL 1215
The <archive_device> string length can be up to 1023 bytes. The <DLLidentifier> portion must be 1 to
30 bytes in length and can contain only alphanumeric and underscore characters. The
<vendor_specific_information> portion of the string is passed to the third-party implementation without
checking its contents. Do not specify the SIZE or STACKER clauses of the BACKUP DATABASE command when
using third-party implementations, as that information should be encoded in the
<vendor_specific_information> portion of the string.

 Note

Only certain third-party products are certified with SAP IQ using this syntax. Before using any third-party
product to back up your SAP IQ database in this way, make sure it is certified. See the Release Bulletin for
additional usage instructions or restrictions. .

For the SAP IQ implementation of the backup API, you need to specify only the tape device name or file name.
For disk devices, you should also specify the SIZE value, or SAP IQ assumes that each created disk file is no
larger than 2 GB on UNIX, or 1.5 GB on Windows.

An example of an archive device for the SAP API DLL that specifies a tape device for certain UNIX systems is:

'/dev/rmt/0'

It is your responsibility to mount additional tapes if needed, or to ensure that the disk has enough space to
accommodate the backup.

When multiple devices are specified, BACKUP DATABASE distributes the information across all devices. Other
issues for BACKUP DATABASE include:

● BACKUP DATABASE does not support raw devices as archival devices.


● Windows systems support only fixed-length I/O operations to tape devices. Although Windows supports
tape partitioning, SAP IQ does not use it, so do not use another application to format tapes for BACKUP
DATABASE. Windows has a simpler naming strategy for its tape devices, where the first tape device is <\\.
\tape0>, the second is <\\.\tape1>, and so on.

 Caution

For backup (and for most other situations) SAP IQ treats the leading backslash in a string as an escape
character, when the backslash precedes an n, an x, or another backslash. For this reason, when you
specify backup tape devices, you must double each backslash required by the Windows naming
convention. For example, indicate the first Windows tape device you are backing up to as '\\\\.\
\tape0', the second as '\\\\.\\tape1', and so on. If you omit the extra backslashes, or otherwise
misspell a tape device name, and write a name that is not a valid tape device on your system, SAP IQ
interprets this name as a disk file name.

● SAP IQ does not rewind tapes before using them. You must ensure the tapes used for backup and restore
are at the correct starting point before putting them in the tape device. SAP IQ does rewind tapes after
using them on rewinding devices.
● During backup and restore operations, if SAP IQ cannot open the archive device (for example, when it
needs the media loaded) and the ATTENDED clause is ON, it waits for ten seconds and tries again. It
continues these attempts indefinitely until either it is successful or the operation is terminated with a Ctrl
+ C.
● If you enter Ctrl + C , BACKUP DATABASE fails and returns the database to the state it was in before the
backup started.

SAP IQ SQL Reference


1216 INTERNAL SQL Statements
● If disk striping is used, such as on a RAID device, the striped disks are treated as a single device.

Privileges

(back to top)

Requires one of:

● You own the database.


● BACK UP DATABASE system privilege.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● (UNIX) This example backs up the iqdemo database onto tape devices /dev/rmt/0 and /dev/rmt/2 on
an Oracle Solaris platform. On Solaris, the letter n after the device name specifies the “no rewind on close”
feature. Always specify this feature with BACKUP DATABASE, using the naming convention appropriate for
your UNIX platform (Windows does not support this feature). This example backs up all changes to the
database since the last full backup:

BACKUP DATABASE
INCREMENTAL SINCE FULL
TO '/dev/rmt/0n' SIZE 10000000
TO '/dev/rmt/2n' SIZE 15000000

 Note

Size units are kilobytes (KB), although in most cases, size of less than 1 GB are inappropriate. In this
example, the specified sizes are 10 GB and 15 GB.

SAP IQ SQL Reference


SQL Statements INTERNAL 1217
● In these examples, the BACKUP DATABASE statement specifies read-only files and dbspaces:

BACKUP DATABASE READONLY DBSPACES dsp1


TO '/dev/rmt/0'

BACKUP DATABASE READONLY FILES dsp1_f1, dsp1_f2


TO 'bkp.f1f2'

BACKUP DATABASE READONLY DBSPACES dsp2, dsp3


READONLY FILES dsp4_f1, dsp5_f2
TO 'bkp.RO'

Related Information

RESTORE DATABASE Statement [page 1608]


REVOKE System Privilege Statement [page 1635]

9.4.28 BEGIN … END Statement

Groups SQL statements together.

 Syntax

[ <statement-label> : ]
… BEGIN [ [ NOT ] ATOMIC ]
… [ <local-declaration> ; … ]
… <statement-list>
… [ EXCEPTION [ <exception-case> … ] ]
… END [ <statement-label> ]

<local-declaration> ::=
{ <variable-declaration>
| <cursor-declaration>
| <exception-declaration>
| <temporary-table-declaration> }

<variable-declaration> ::=
DECLARE <variable-name> [ , … ] <data-type>
[{ = | DEFAULT} <initial-value>]

<initial-value> ::=
<special-value>
| <string>
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function> ( <constant-expression> )
| NULL

<special-value> ::=
CURRENT {
DATABASE

SAP IQ SQL Reference


1218 INTERNAL SQL Statements
| DATE
| PUBLISHER
| TIME
| TIMESTAMP
| USER
| UTC TIMESTAMP }
| USER

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

statement-label

If specified, it must match the beginning <statement-label>. You can use the LEAVE statement to
resume execution at the first statement after the compound statement. The compound statement that is
the body of a procedure has an implicit label that is the same as the name of the procedure.
initial-value

If specified, the variable is set to that value and the data type must match the type defined by <data-
type>. If you do not specify an initial-value, the variable contains the NULL value until a SET statement
assigns a different value.

Remarks

(back to top)

The body of a procedure is a compound statement. Compound statements can also be used in control
statements within a procedure.

A compound statement allows one or more SQL statements to be grouped together and treated as a unit. A
compound statement starts with BEGIN and ends with END. Immediately after BEGIN, a compound statement
can have local declarations that exist only within the compound statement. A compound statement can have a
local declaration for a variable, a cursor, a temporary table, or an exception. Local declarations can be
referenced by any statement in that compound statement, or in any compound statement nested within it.
Local declarations are invisible to other procedures that are called from within a compound statement.

An atomic statement is a statement 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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1219
Privileges

(back to top)

None

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise. This does not mean that all
statements inside a compound statement are supported.
BEGIN and END keywords are not required in Transact-SQL.
BEGIN and END are used in Transact-SQL to group a set of statements into a single compound statement,
so that control statements such as IF … ELSE, which affect the performance of only a single SQL
statement, can affect the performance of the whole group. The ATOMIC keyword is not supported by SAP
ASE.
In Transact-SQL, DECLARE statements need not immediately follow BEGIN, and the cursor or variable that
is declared exists for the duration of the compound statement. You should declare variables at the
beginning of the compound statement for compatibility.

Examples

(back to top)

In the following example, the body of a procedure 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

SAP IQ SQL Reference


1220 INTERNAL SQL Statements
LEAVE CustomerLoop ;
END IF ;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue ;
SET TopCompany = ThisCompany ;
END IF ;
END LOOP CustomerLoop ;

CLOSE curThisCust ;
END

Related Information

DECLARE LOCAL TEMPORARY TABLE Statement [page 1422]


DECLARE CURSOR Statement [ESQL] [SP] [page 1415]
LEAVE Statement [page 1547]
RESIGNAL Statement [page 1607]
SIGNAL Statement [page 1684]
REVOKE System Privilege Statement [page 1635]

9.4.29 BEGIN PARALLEL IQ … END PARALLEL IQ Statement

Groups CREATE INDEX statements together for execution at the same time.

 Syntax

... BEGIN PARALLEL IQ <statement-list>


... END PARALLEL IQ

Parameters

statement-list

A list of CREATE INDEX statements

Remarks

The BEGIN PARALLEL IQ … END PARALLEL IQ statement lets you execute a group of CREATE INDEX
statements as though they are a single DDL statement, creating indexes on multiple IQ tables at the same time.
While this statement is executing, you and other users cannot issue other DDL statements.

SAP IQ SQL Reference


SQL Statements INTERNAL 1221
 Note

This statement does not support the following:

● RLV-enabled tables
● TEXT indexes

Privileges

None

Side Effects

Automatic commit

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. For support of statements
inside the statement, see CREATE INDEX Statement.

Examples

The following statement executes atomically. If one command fails, the entire statement rolls back:

BEGIN PARALLEL IQ
CREATE HG INDEX c1_HG on table1 (col1);
CREATE HNG INDEX c12_HNG on table1 (col12);
CREATE HNG INDEX c2_HNG on table1 (col2);
END PARALLEL IQ

Related Information

CREATE INDEX Statement [page 1294]


REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1222 INTERNAL SQL Statements
9.4.30 BEGIN TRANSACTION Statement [T-SQL]

Use this statement to begin a user-defined transaction.

 Syntax

BEGIN TRAN[SACTION] [ <transaction-name> ]

Parameters

transaction-name

(Optional) 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.

Remarks

 Note

BEGIN TRANSACTION is a T-SQL construct and must contain only valid T-SQL commands. You cannot mix
T-SQL and non-T-SQL commands.

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 SAP ASE and SAP IQ have two transaction modes.

The default SAP ASE 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/2003
compatible chained mode only commits a transaction when an explicit COMMIT is executed or when a
statement that carries out an autocommit (such as data definition statements) is executed.

You can control the mode by setting the chained database option. The default setting for ODBC and embedded
SQL connections in SAP IQ is On, in which case SAP ASE runs in chained mode. (ODBC users should also
check the AutoCommit ODBC setting). The default for TDS connections is Off.

In unchained mode, a transaction is implicitly started before any data retrieval or modification statement.
These statements include: DELETE, INSERT, OPEN, FETCH, SELECT, and UPDATE. You must still explicitly end
the transaction with a COMMIT or ROLLBACK statement.

You cannot alter the chained option within a transaction.

 Note

When calling a stored procedure, you should ensure that it operates correctly under the required
transaction mode.

SAP IQ SQL Reference


SQL Statements INTERNAL 1223
The current nesting level is held in the global variable @@trancount. The @@trancount variable has a value of
zero before the first BEGIN TRANSACTION statement is executed, and only a COMMIT executed when
@@trancount is equal to one makes changes to the database permanent.

A ROLLBACK statement without a transaction or savepoint name always rolls back statements to the
outermost BEGIN TRANSACTION (explicit or implicit) statement, and cancels the entire transaction.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

The following example reports successive values of @@trancount as 0, 1, 2, 1, 0 and prints the values on the
server window:

PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount

Do not rely on the value of @@trancount for more than keeping track of the number of explicit BEGIN
TRANSACTION statements that have been issued.

When SAP ASE starts a transaction implicitly, the @@trancount variable is set to 1. SAP IQ does not set the
@@trancount value to 1 when a transaction is started implicitly. So, the SAP IQ @@trancount variable has a
value of zero before any BEGIN TRANSACTION statement (even though there is a current transaction), while in
SAP ASE (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 SAP
ASE and SAP ASE 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 SAP IQ, and SAP ASE after the BEGIN TRANSACTION statement.

SAP IQ SQL Reference


1224 INTERNAL SQL Statements
Related Information

COMMIT Statement [page 1238]


ROLLBACK TRANSACTION Statement [T-SQL] [page 1656]
SAVE TRANSACTION Statement [T-SQL] [page 1657]
ISOLATION_LEVEL Option [page 1885]
REVOKE System Privilege Statement [page 1635]

9.4.31 CALL Statement


Invokes a procedure.

 Syntax

Syntax 1

[ <variable> = ] CALL <procedure-name> ( [ <expression> ] [ , … ] )


[ AS USER { <string> | <variable> } IDENTIFIED BY { <string> |
<variable> } ]

Syntax 2

[ <variable> = ] CALL <procedure-name> ( [ <parameter-name> =


<expression> ] [ , … ] )
[ AS USER { <string> | <variable> } IDENTIFIED BY { <string> |
<variable> } ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

AS USER ... IDENTIFIED BY clause

(Optional) Calls a procedure or function as a different user. The database server verifies that the user ID
and password provided are valid, and then executes the procedure or function as the specified user. The
invoker of the procedure is the specified user. Upon exiting the procedure or function, the user context is
restored to its original state.

 Note

All string values must be enclosed in single quotes; otherwise the database server interprets them as
variable names.

SAP IQ SQL Reference


SQL Statements INTERNAL 1225
Remarks

(back to top)

CALL invokes a procedure that has been previously created with a CREATE PROCEDURE statement. When the
procedure completes, any INOUT or OUT parameter values are copied back.

 Note

The AS USER ... IDENTIFIED BY clause only applies to the CALL statement and is not supported for
procedures in the FROM clause or functions in the select list.

You can specify the argument list by position or by using keyword format. By position, arguments match up
with the corresponding parameter in the parameter list for the procedure. By keyword, arguments match the
named parameters.

Procedure arguments can be assigned default values in the CREATE PROCEDURE statement, and missing
parameters are assigned the default value, or, if no default is set, NULL.

Inside a procedure, CALL can be used in a DECLARE statement when the procedure returns result sets.

 Note

You cannot reference a Table UDF in a CALL SQL statement.

Procedures can return an integer value (as a status indicator, say) using the RETURN statement. You can save
this return value in a variable using the equality sign as an assignment operator:

CREATE VARIABLE returnval INT ;


returnval = CALL proc_integer ( arg1 = val1, ... )

 Note

Use of this statement to invoke a function is deprecated. To call functions, use an assignment statement to
invoke the function and assign its result to a variable. For example:

DECLARE varname INT;


SET varname=test( );

Privileges

(back to top)

Requires one of:

● You own the procedure.


● EXECUTE ANY PROCEDURE system privilege.
● EXECUTE object-level permission for the procedure.

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

SAP IQ SQL Reference


1226 INTERNAL SQL Statements
Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. For an alternative that is
supported, see EXECUTE Statement [ESQL].

Examples

(back to top)

● The following example calls the sp_customer_list procedure. This procedure has no parameters, and
returns a result set:

CALL sp_customer_list()

● The following 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 CustomerID INT, OUT Orders INT)


BEGIN
SELECT COUNT("DBA".SalesOrders.ID)
INTO Orders
FROM "DBA".Customers
KEY LEFT OUTER JOIN "DBA".SalesOrders
WHERE "DBA".Customers.ID = CustomerID ;
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

Related Information

CREATE PROCEDURE Statement [page 1321]


EXECUTE Statement [ESQL] [page 1467]
GRANT EXECUTE Privilege Statement [page 1499]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1227
9.4.32 CASE Statement

The CASE statement is a control statement that lets you choose a list of SQL statements to execute based on
the value of an expression.

 Syntax

CASE <value-expression>
… WHEN [ <constant> | NULL ] THEN <statement-list> …
… [ WHEN [ <constant> | NULL ] THEN <statement-list> ] …
… ELSE <statement-list>
… END

Remarks

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.

 Note

The ANSI standard allows two forms of CASE statements. Although SAP IQ allows both forms, when CASE is
in the predicate, for best performance you must use the form shown here.

If you require the other form (also called ANSI syntax) for compatibility with SAP SQL Anywhere, use this
syntax:

CASE
WHEN [ search-condition | NULL] THEN statement-list ...
[ WHEN [ search-condition | NULL] THEN statement-list ] ...
[ ELSE statement-list ]
END [ CASE ]

With this ANSI syntax 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

Do not confuse the syntax of the CASE statement with that of the CASE expression.

Privileges

None

SAP IQ SQL Reference


1228 INTERNAL SQL Statements
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example classifies the products listed in the Products table of the demo 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 "GROUPO"."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

Related Information

BEGIN … END Statement [page 1218]


REVOKE System Privilege Statement [page 1635]

9.4.33 CHECKPOINT Statement

Checkpoints the database.

 Syntax

CHECKPOINT

SAP IQ SQL Reference


SQL Statements INTERNAL 1229
Remarks

CHECKPOINT forces the database server to execute a checkpoint. Checkpoints are also performed
automatically by the database server according to an internal algorithm. Applications do not normally need to
issue CHECKPOINT.

SAP IQ uses checkpoints differently than OLTP databases such as SAP SQL Anywhere. OLTP databases tend
to have short transactions that affect only a small number of rows. Writing entire pages to disk would be very
expensive for them. Instead, OLTP databases generally write to disk at checkpoints, and write only the changed
data rows. SAP IQ is an OLAP database. A single OLAP transaction can change thousands or millions of rows of
data. For this reason, the database server does not wait for a checkpoint to occur to perform physical writes. It
writes updated data pages to disk after each transaction commits. For an OLAP database, writing full pages of
data to disk is much more effective than writing small amounts of data at arbitrary checkpoints.

Adjusting the checkpoint time or issuing explicit checkpoints may be unnecessary. Controlling checkpoints is
less important in SAP IQ than in OLTP database products, because SAP IQ writes the actual data pages after
each transaction commits.

Privileges

Requires the CHECKPOINT system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.34 CLEAR Statement [Interactive SQL]

Closes any open result sets in Interactive SQL (dbisql).

 Syntax

CLEAR

SAP IQ SQL Reference


1230 INTERNAL SQL Statements
Remarks

Closes any open result sets and leaves the contents of the SQL Statements pane unchanged.

Privileges

None

Side Effects

The CLEAR statement closes the cursor that is associated with the data being cleared.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Related Information

EXIT Statement [Interactive SQL] [page 1473]


REVOKE System Privilege Statement [page 1635]

9.4.35 CLOSE Statement [ESQL] [SP]

Closes a named cursor.

 Syntax

CLOSE { <identifier> | <host-variable> }

Remarks

This statement closes the named cursor.

SAP IQ SQL Reference


SQL Statements INTERNAL 1231
The cursor must have been previously opened.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

● The following example closes cursors in Embedded SQL:

EXEC SQL CLOSE employee_cursor;


EXEC SQL CLOSE :cursor_var;

● The following example uses a cursor:

CREATE PROCEDURE TopCustomer (OUT TopCompany CHAR(35), OUT TopValue INT)


BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE '02000' ;
DECLARE curThisCust CURSOR FOR
SELECT CompanyName,
CAST( sum(SalesOrderItems.Quantity *
Products.UnitPrice) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName ;
DECLARE ThisValue INT ;
DECLARE ThisCompany CHAR(35) ;
SET TopValue = 0 ;
OPEN curThisCust ;
CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue ;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop ;
END IF ;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue ;
SET TopCompany = ThisCompany ;
END IF ;
END LOOP CustomerLoop ;
CLOSE curThisCust ;
END

SAP IQ SQL Reference


1232 INTERNAL SQL Statements
Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


OPEN Statement [ESQL] [SP] [page 1582]
PREPARE Statement [ESQL] [page 1590]
REVOKE System Privilege Statement [page 1635]

9.4.36 COMMENT Statement

Stores a comment, in the system tables, about a database object.

 Syntax

COMMENT ON
{ COLUMN [<owner>.]<table-name>.<column-name>
| DBSPACE <dbspace-name>
| EVENT <event-name>
| EXTERNAL [ENVIRONMENT] OBJECT <object-name>
| EXTERNAL ENVIRONMENT <environment-name>
| EXTERNAL 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>"
| LDAP SERVER <ldap-server-name>
| LOGICAL SERVER <logical-server-name>
| LOGIN POLICY <policy-name>
| LS POLICY <ls-policy-name>
| MATERIALIZED VIEW [<owner>.]<materialized-view-name>
| PRIMARY KEY ON [<owner>.]<table-name>
| PROCEDURE [<owner>.]<table-name>
| ROLE <role-name>
| SERVICE <web-service-name>
| SEQUENCE [<owner>.]<sequence-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>
| TRIGGER [[<owner>.]<table-name>.]<trigger-name>
| USER <userid>
| VIEW [ <owner>.]<view-name> }
IS <comment>

<environment-name> ::=
JAVA | PERL | PHP | C_ESQL32 | C_ESQL64 | C_ODBC32 | C_ODBC64

<comment> ::=
{ <string> | NULL }

Go to:

● Privileges

SAP IQ SQL Reference


SQL Statements INTERNAL 1233
● Standards
● Examples

Remarks

(back to top)

The COMMENT statement updates remarks in the ISYSREMARK system table. You can remove a comment by
setting it to NULL. The owner of a comment on an index or trigger is the owner of the table on which the index
or trigger is defined.

The COMMENT ON DBSPACE, COMMENT ON JAVA JAR, and COMMENT ON JAVA CLASS statements allow you
to set the Remarks column in the SYS.ISYSREMARK system table. Remove a comment by setting it to NULL.

You cannot add comments for local temporary tables.

 Note

Materialized views are supported only for SAP SQL Anywhere tables in the IQ catalog store.

Privileges

(back to top)

The privilege required varies by clause. See GRANT System Privilege Statement [page 1511] or GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges.

Clause Privilege Required

COLUMN Requires one of:

● You own the table


● CREATE ANY TABLE system privilege
● ALTER ANY TABLE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

DBSPACE MANAGE ANY DBSPACE system privilege

EVENT Requires one of:

● MANAGE ANY EVENT system privilege


● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

EXTERNAL [ENVIRONMENT] OBJECT MANAGE ANY EXTERNAL OBJECT system privilege

EXTERNAL ENVIRONMENT MANAGE ANY EXTERNAL ENVIRONMENT system privilege

SAP IQ SQL Reference


1234 INTERNAL SQL Statements
Clause Privilege Required

FOREIGN KEY Requires one of:

● You own the table


● CREATE ANY TABLE system privilege
● ALTER ANY TABLE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

INDEX Requires one of:

● You own the index


● CREATE ANY INDEX system privilege
● ALTER ANY INDEX system privilege
● COMMENT ANY OBJECT system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege

INTEGRATED LOGIN MANAGE ANY USER system privilege

JAVA CLASS or JAVA JAR MANAGE ANY EXTERNAL OBJECT system privilege

KERBEROS LOGIN MANAGE ANY USER system privilege

LDAP SERVER MANAGE ANY LDAP SERVER system privilege

LOGICAL SERVER MANAGE MULTIPLEX system privilege

LOGIN POLICY MANAGE ANY LOGIN POLICY system privilege

LS POLICY MANAGE MULTIPLEX system privilege

MATERIALIZE VIEW Requires one of:

● You own the view


● CREATE ANY MATERIALIZED VIEW system privilege
● ALTER ANY MATERIALIZED VIEW system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

PRIMARY KEY ON Requires one of:

● You own the table


● CREATE ANY TABLE system privilege
● ALTER ANY TABLE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

SAP IQ SQL Reference


SQL Statements INTERNAL 1235
Clause Privilege Required

PROCEDURE Requires one of:

● You own the procedure


● CREATE ANY PROCEDURE system privilege
● ALTER ANY PROCEDURE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

SEQUENCE Requires one of:

● You own the sequence


● CREATE ANY SEQUENCE system privilege
● ALTER ANY SEQUENCE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

SERVICE MANAGE ANY WEB SERVICE system privilege

SPATIAL REFERENCE SYSTEM Requires one of:

● COMMENT ANY OBJECT system privilege


● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● MANAGE ANY SPATIAL OBJECT system privilege

SPATIAL UNIT OF MEASURE Requires one of:

● COMMENT ANY OBJECT system privilege


● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● MANAGE ANY SPATIAL OBJECT system privilege

ROLE System role – administrative privilege over the role being commented on.

User-defined role – MANAGE ROLES system privilege or administrative privi­


lege over the role being commented on.

TABLE Requires one of:

● You own the table


● CREATE ANY TABLE system privilege
● ALTER ANY TABLE system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

TEXT CONFIGURATION Requires one of:

● You created the text configuration


● CREATE ANY TEXT CONFIGURATION system privilege
● ALTER ANY TEXT CONFIGURATION system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

SAP IQ SQL Reference


1236 INTERNAL SQL Statements
Clause Privilege Required

TEXT INDEX Requires one of:

● You created the text index


● CREATE ANY INDEX system privilege
● ALTER ANY INDEX system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

TRIGGER Requires one of:

● You created the trigger


● CREATE ANY TRIGGER system privilege
● ALTER ANY TRIGGER system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

USER MANAGE ANY USER system privilege

VIEW Requires one of:

● You own the view


● CREATE ANY VIEW system privilege
● ALTER ANY VIEW system privilege
● CREATE ANY OBJECT system privilege
● ALTER ANY OBJECT system privilege
● COMMENT ANY OBJECT system privilege

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example adds a comment to the Employees table:

COMMENT
ON TABLE Employees
IS "Employee information"

● The following example removes the comment from the Employees table:

COMMENT
ON TABLE Employees

SAP IQ SQL Reference


SQL Statements INTERNAL 1237
IS NULL

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.37 COMMIT Statement

Makes changes to the database permanent, or terminates a user-defined transaction.

 Syntax

Syntax 1 – Ends a Transaction and Makes All Changes Permanent

COMMIT [ WORK ]

Syntax 2 – Constructs Nested Transactions

COMMIT TRAN[SACTION ] [ <transaction-name> ]

Remarks

Syntax 1
Data definition statements carry out commits automatically. For information, see the Side Effects listing for
each SQL statement.

COMMIT fails if the database server detects any invalid foreign keys. This makes it impossible to end a
transaction with any invalid foreign keys. Usually, foreign key integrity is checked on each data manipulation
operation. However, if the database option WAIT_FOR_COMMIT is set ON or a particular foreign key was defined
with a CHECK ON COMMIT clause, the database server delays integrity checking until the COMMIT statement is
executed.

Syntax 2
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, COMMIT
TRANSACTION decreases the nesting level of transactions by one. When transactions are nested, only the
outermost COMMIT makes the changes to the database permanent.

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.

You can use a set of options to control the detailed behavior of the COMMIT statement. See
COOPERATIVE_COMMIT_TIMEOUT Option, COOPERATIVE_COMMITS Option, DELAYED_COMMITS Option,

SAP IQ SQL Reference


1238 INTERNAL SQL Statements
and DELAYED_COMMIT_TIMEOUT Option. You can use the Commit connection property to return the number
of commits on the current connection.

Must be connected to the database.

Privileges

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.

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise. Syntax 2 is a Transact-SQL
extension to ISO/ANSI SQL grammar.

Examples

● The following example commits the current transaction:

COMMIT

● The following example shows how the Transact-SQL batch reports successive values of @@trancount as
0, 1, 2, 1, 0:

PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount
go

SAP IQ SQL Reference


SQL Statements INTERNAL 1239
Related Information

BEGIN TRANSACTION Statement [T-SQL] [page 1223]


CONNECT Statement [ESQL] [Interactive SQL] [page 1241]
DISCONNECT Statement [Interactive SQL] [page 1432]
ROLLBACK Statement [page 1654]
SAVEPOINT Statement [page 1658]
SET CONNECTION Statement [ESQL] [Interactive SQL] [page 1675]
COOPERATIVE_COMMIT_TIMEOUT Option [page 1797]
COOPERATIVE_COMMITS Option [page 1798]
DELAYED_COMMITS Option [page 1823]
DELAYED_COMMIT_TIMEOUT Option [page 1822]
REVOKE System Privilege Statement [page 1635]

9.4.38 CONFIGURE Statement [Interactive SQL]

Activates the Interactive SQL (dbisql) configuration window.

 Syntax

CONFIGURE

Remarks

The dbisql configuration window displays the current settings of all dbisql options. It does not display or let
you modify database options.

If you select Permanent, the options are written to the SYSOPTION table in the database and the database
server performs an automatic COMMIT. If you do not choose Permanent, and instead click OK, options are set
temporarily and remain in effect only for the current database connection.

Privileges

None

SAP IQ SQL Reference


1240 INTERNAL SQL Statements
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Related Information

SET OPTION Statement [page 1677]


REVOKE System Privilege Statement [page 1635]

9.4.39 CONNECT Statement [ESQL] [Interactive SQL]

Establishes a connection to the database identified by <database-name> running on the server identified by
<engine-name>.

 Syntax

Syntax 1

CONNECT
…[ TO <engine-name> ]
…[ DATABASE <database-name> ]
…[ AS <connection-name> ]
…[ USER ] <userid> [ IDENTIFIED BY ]

Syntax 2

CONNECT USING <connect-string>

Go to:

● Remarks
● Standards
● Privileges
● Examples

Parameters

(back to top)

AS connection-name

Connection can optionally be named by specifying the 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 might even get locking conflicts between your

SAP IQ SQL Reference


SQL Statements INTERNAL 1241
transactions if, for example, you try to modify the same record in the same database from two different
connections.
connect-string

A list of parameter settings of the form keyword=<value>, and must be enclosed in single quotes.

Remarks

(back to top)

Embedded SQL behavior

If no <engine-name> is specified, the default local database server is assumed (the first database server
started). If no <database-name> is specified, the first database on the given server is assumed.

The user ID and password are used for permission checks on all dynamic SQL statements. By default, the
password is case-sensitive; the user ID is not. You can connect without a password by using a host variable
for the password and setting the value of the host variable to be the null pointer.
Dbisql behavior

If no database or server is specified in the CONNECT statement, dbisql remains connected to the current
database, rather than to the default server and database. If a database name is specified without a server
name, dbisql attempts to connect to the specified database on the current server. You must specify the
database name defined in the -n database switch, not the database file name. If a server name is specified
without a database name, dbisql connects to the default database on the specified server. For example, if
this batch is executed while connected to a database, the two tables are created in the same database:

CREATE TABLE t1( c1 int );


CONNECT DBA IDENTIFIED BY <password>;
CREATE TABLE t2 ( c1 int );

No other database statements are allowed until a successful CONNECT statement has been executed.

The user ID and password check the permissions on SQL statements. If the password or the user ID and
password are not specified, the user is prompted to type the missing information. By default, the password
is case-sensitive; the user ID is not.

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 SET
CONNECTION. Executing a CONNECT statement does not close the existing connection (if any). Use
DISCONNECT to drop connections.

Static SQL statements use the user ID and password specified with the -l option on the SQLPP statement line.
If no -l option is given, the user ID and password of the CONNECT statement are used for static SQL
statements also.

Privileges

(back to top)

SAP IQ SQL Reference


1242 INTERNAL SQL Statements
None

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – Open Client Embedded SQL supports a different syntax for the CONNECT
statement.

Examples

(back to top)

● The following example connects to the default database using dbisql without specifying credentials. You
are prompted for a user ID and password:

CONNECT

● The following example connects to the default database as user DBA using . You are prompted for a user ID
and password:

CONNECT USER "DBA"

● The following example connects to the demo database as user DBA using dbisql, where
<machine_iqdemo> is the engine name:

CONNECT
TO <machine_iqdemo>
USER "DBA"
IDENTIFIED BY <password>

● The following example connects to the demo database using a connect string using dbisql:

CONNECT USING 'UID=DBA;PWD=<password>;DBN=iqdemo'

Related Information

DISCONNECT Statement [Interactive SQL] [page 1432]


GRANT CONNECT Privilege Statement [page 1496]
SET CONNECTION Statement [ESQL] [Interactive SQL] [page 1675]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1243
9.4.40 CREATE AGENT Statement

Associates an SAP IQ agent for SAP IQ Cockpit with the named server to support high availability.

 Syntax

CREATE AGENT FOR MULTIPLEX SERVER <server-name>


USER <username> IDENTIFIED BY <agentpwd> PORT <portnum>

Remarks

Applies to multiplex only.

The SYS.ISYSIQMPXSERVERAGENT system table stores the agent connection definitions for the server.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Side Effects

Automatic commit

Examples

The following example creates an agent for the SAP IQ server named mpx_writer1. The user login is
"sqltester" and the port number is 1138:

CREATE AGENT FOR MULTIPLEX SERVER mpx_writer1 USER sqltester IDENTIFIED BY


'8U3dkA' PORT 1138

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1244 INTERNAL SQL Statements
9.4.41 CREATE DATABASE Statement

Creates a database consisting of several operating system files.

 Syntax

CREATE DATABASE <db-name>


DBA USER <userid> DBA PASSWORD <password>
[ TRANSACTION ] { LOG ON [ <log-file-name> ]
[ MIRROR <mirror-file-name> ] } ]
[ CASE { RESPECT | IGNORE } ]
[ PAGE SIZE <catalog-page-size> ]
[ COLLATION <collation-label>[( <collation-tailoring-string> ) ] ]
[ ENCRYPTED {<algorithm-key-spec> | OFF } ]
[ BLANK PADDING ON ]
[ JCONNECT { ON | OFF } ]
[ IQ PATH <iq-file-name> ]
[ IQ SIZE <iq-file-size> ]
[ IQ PAGE SIZE <iq-page-size> ]
[ BLOCK SIZE <block-size> ]
[ IQ RESERVE <sizeMB> ]
[ TEMPORARY RESERVE <sizeMB> ]
[ MESSAGE PATH <message-file-name> ]
[ TEMPORARY PATH <temp-file-name> ]
[ TEMPORARY SIZE <temp-db-size> ]
[ SYSTEM PROCEDURE AS DEFINER {ON | OFF} ]

<catalog-page-size> ::= { 4096 | 8192 | 16384 | 32768 } (bytes)

<collation-label> ::= <string>

<collation-tailoring-string> ::= <keyword=value>

<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'

<key> ::= <quoted string>

<iq-page-size> ::= { 65536 | 131072 | 262144 | 524288 } (bytes)

<block-size> ::= { 4096 | 8192 | 16384 | 32768 } (bytes)

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

SAP IQ SQL Reference


SQL Statements INTERNAL 1245
Parameters

(back to top)

DBA USER userid DBA PASSWORD password

A DBA user ID and password for the database.

By default, passwords must be a minimum length of 6 characters unless the MINIMUM PASSWORD
LENGTH clause is specified and set to a different value. Passwords should be composed of 7-bit ASCII
characters. Other characters may not work correctly if the server cannot convert from the client character
set to UTF-8.
TRANSACTION LOG

A file where the database server logs all changes made to the database. The transaction log plays a key role
in system recovery. If you do not specify any TRANSACTION LOG clause, or if you omit a path for the file
name, it is placed in the same directory as the .db file. However, you should place it on a different physical
device from the .db and .iq. It cannot be created on a raw partition.
MIRROR mirror-file-name

An identical copy of a transaction log, usually maintained on a separate device, for greater protection of
your data. By default, SAP IQ does not use a mirrored transaction log. If you do want to use a transaction
log mirror, you must provide a file name. If you use a relative path, the transaction log mirror is created
relative to the directory of the catalog store (db-name.db). Tip: Always create a mirror copy of the
transaction log.
CASE { RESPECT | IGNORE }

For databases created with CASE RESPECT, all affected values are case-sensitive in comparisons and
string operations. Database object names such as columns, procedures, or user IDs, are unaffected.
Dbspace names are always case-insensitive, regardless of the CASE specification. The default (RESPECT)
is that all comparisons are case-sensitive. CASE RESPECT provides better performance than CASE
IGNORE.
PAGE SIZE catalog-page-size

Page size for the SQL Anywhere segment of the database (containing the catalog tables) can be 4096,
8192, 16384, or 32768 bytes. Normally, use the default, 4096 (4 KB). Large databases might need a larger
page size than the default and may see performance benefits as a result. The smaller values might limit the
number of columns your database can support. If you specify a page size smaller than 4096, SAP IQ uses a
page size of 4096.
COLLATION collation-label [ ( collation-tailoring-string ) ]

The collation sequence used for sorting and comparison of character data types in the database. The
collation provides character comparison and ordering information for the encoding (character set) being
used. If the COLLATION clause is not specified, SAP IQ chooses a collation based on the operating system
language and encoding. For most operating systems, the default collation sequence is ISO_BINENG, which
provides the best performance. In ISO_BINENG, the collation order is the same as the order of characters
in the ASCII character set. All uppercase letters precede all lowercase letters (for example, both 'A' and 'B'
precede 'a').

You can choose the collation from a list of supported collations. For SAP SQL Anywhere databases created
on an SAP IQ server, the collation can also be the Unicode Collation Algorithm (UCA). If UCA is specified,
also specify the ENCODING clause. SAP IQ does not support any of the UCA-based collations for SAP IQ
databases. If a UCA-based collation is specified in the CREATE DATABASE statement for a database, the

SAP IQ SQL Reference


1246 INTERNAL SQL Statements
server returns the error UCA collation is not supported and database creation fails. A collation
sequence cannot be changed after the database is 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.

This table contains the supported keyword, allowed alternate forms, and allowed values for the collation
tailoring option (<collation-tailoring-string>) for an SAP IQ database:

Alternate
Keyword Collation Forms Allowed Values

CaseSensitivity All supported CaseSensitive, ● respect – respect case differences between letters. For
collations Case the UCA collation, this is equivalent to UpperFirst. For
other collations, the value of respect depends on the colla­
tion itself.
● ignore – ignore case differences between letters.
● UpperFirst – always sort upper case first (Aa).
● LowerFirst – always sort lowercase first (aA).

 Note

Several collation tailoring options are supported when you specify the UCA collation for an SAP SQL
Anywhere database created on an SAP IQ server. For all other collations and for SAP IQ, only case
sensitivity tailoring is supported. Also, databases created with collation tailoring options cannot be
started using a pre-15.0 database server.

ENCRYPTED { algorithm-key-spec | OFF }

Makes the data stored in your physical database file unreadable. Use the CREATE DATABASE ENCRYPTED
keyword without the TABLE keyword to encrypt the entire database. Use the ENCRYPTED TABLE clause to
enable only table encryption for SQL Anywhere tables. Table-level encryption is not supported for SAP IQ
tables. 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 encryption: simple and strong.

● Simple encryption is equivalent to obfuscation. The data is unreadable, but someone with
cryptographic expertise could decipher the data. For simple encryption, specify the CREATE
DATABASE clause ENCRYPTED ON ALGORITHM 'SIMPLE', ENCRYPTED ALGORITHM 'SIMPLE', or
specify the ENCRYPTED ON clause without specifying an algorithm or key.
● Strong encryption is achieved through the use of a 128-bit algorithm and a security key. The data is
unreadable and virtually undecipherable without the key. For strong encryption, specify the CREATE
DATABASE clause ENCRYPTED ON ALGORITHM with a 128-bit or 256-bit AES algorithm and use the
KEY clause to specify an encryption key. You should 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.
This encryption key is required each time you start the database.

You can specify encryption only during database creation. To introduce encryption to an existing database
requires a complete unload, database re-creation, and reload of all data. If the ENCRYPTED clause is used
but no algorithm is specified, the default is AES. By default, encryption is OFF.

SAP IQ SQL Reference


SQL Statements INTERNAL 1247
 Caution

Protect your encryption key! Store a copy of your key in a safe location. A lost key results in a
completely inaccessible database from which there is no recovery.

BLANK PADDING ON

Trailing blanks are ignored for comparison purposes (BLANK PADDING ON), and Embedded SQL programs
pad strings that are fetched into character arrays. This option is provided for compatibility with the ISO/
ANSI SQL standard. CREATE DATABASE no longer supports BLANK PADDING OFF.
JCONNECT { ON | OFF }

To use the SAP jConnect for JDBC driver to access system catalog information, install jConnect support.
Set JCONNECT to OFF to exclude the jConnect system objects (the default is ON). You can still use JDBC,
as long as you do not access system information.
IQ PATH iq-file-name

The path name of the main segment file containing the SAP IQ data. You can specify an operating system
file or a raw partition of an I/O device. (IQ PATH Parameter Guidelines in SAP IQ Administration: Database
describes the format for specifying a raw partition.)
SAP IQ automatically detects which type based on the path name you specify. If you use a relative path, the
file is created relative to the directory of the catalog store (the .db file).

If you omit the IQ PATH clause, specifying any of these options generates an error: IQ SIZE, IQ PAGE SIZE,
BLOCK SIZE, MESSAGE PATH, TEMPORARY PATH, and TEMPORARY SIZE.
IQ SIZE iq-file-size

The size in MB of either the raw partition or the operating system file you specify with the IQ PATH clause.
For raw partitions, you should always take the default by not specifying IQ SIZE, which allows SAP IQ to use
the entire raw partition; if you specify a value for IQ SIZE, the value must match the size of the I/O device or
SAP IQ returns an error. For operating system files, you can specify a value from the minimum in the
following table up to a maximum of 100 TB.

The default size for an operating system file depends on IQ PAGE SIZE:

TEMPORARY SIZE De­ Minimum Explicit IQ Minimum Explicit TEM­


IQ PAGE SIZE IQ SIZE Default fault SIZE PORARY SIZE

65536 4096000 2048000 4 MB 2 MB

131072 8192000 4096000 8 MB 4 MB

262144 16384000 8192000 16 MB 8 MB

524288 32768000 16384000 32 MB 16 MB

IQ PAGE SIZE iq-page-size

The page size, in bytes, for the SAP IQ segment of the database (containing the IQ tables and indexes). The
value must be a power of 2, from 65536 to 524288 bytes. The default is 131072 (128 KB). Other values for
the size are changed to the next larger size. The IQ page size determines the default I/O transfer block size
and maximum data compression for your database.

For best performance, use these minimum page sizes:

SAP IQ SQL Reference


1248 INTERNAL SQL Statements
● 64 KB (IQ PAGE SIZE 65536) for databases for which its largest table contains up to 1 billion rows, or a
total size less than 8 TB. This is the absolute minimum for a new database. On 32-bit platforms, a 64
KB IQ page size gives the best performance.
● 128 KB (IQ PAGE SIZE 131072) for databases on a 64-bit platform, for which its largest table contains
more than 1 billion rows and fewer than 4 billion rows, or might grow to a total size of 8 TB or greater.
128 KB is the default IQ page size.
● 256 KB (IQ PAGE SIZE 262144) for databases on a 64-bit platform, for which its largest table contains
more than 4 billion rows, or might grow to a total size of 8 TB or greater.
BLOCK SIZE block-size

The I/O transfer block size, in bytes, for the SAP IQ segment of the database. The value must be less than
IQ PAGE SIZE, and must be a power of two between 4096 and 32768. Other values for the size are changed
to the next larger size. The default value depends on the value of the IQ PAGE SIZE clause. For most
applications, the default value is optimum.
IQ RESERVE sizeMB

Size, in megabytes, of space to reserve for the main IQ store (IQ_SYSTEM_MAIN dbspace), so that the
dbfile can be increased in size in the future. The sizeMB parameter can be any number greater than 0. You
cannot change the reserve after the dbspace is created. When IQ RESERVE is specified, the database uses
more space for internal (free list) structures. If reserve size is too large, the space needed for the internal
structures can be larger than the specified size, which results in an error.
TEMPORARY RESERVE sizeMB

Size, in megabytes, of space to reserve for the temporary IQ store (IQ_SYSTEM_TEMP dbspace), so that
the dbfile can be increased in size in the future. The sizeMB parameter can be any number greater than 0.
You cannot change the reserve after the dbspace is created. When TEMPORARY RESERVE is specified, the
database uses more space for internal (free list) structures. If reserve size is too large, the space needed
for the internal structures can be larger than the specified size, which results in an error.

 Note

Reserve and mode for temporary dbspaces are lost if the database is restored from a backup.

MESSAGE PATH message-file-name

Path name of the segment containing the SAP IQ


TEMPORARY PATH temp-file-name

The name of the temporary raw partition or operating system file.


TEMPORARY SIZE temp-db-size

Size, in megabytes, of either the raw partition or the operating system file you specify with the
TEMPORARY PATH clause. For raw partitions, always use the default by not specifying TEMPORARY SIZE,
which allows messages trace file. You must specify an operating system file; the message file cannot be on
a raw partition. If you use a relative path or omit the path, the message file is created relative to the
directory of the .db file.SAP IQ to use the entire raw partition. The default for operating system files is
always one-half the value of IQ SIZE. If the IQ store is on a raw partition and the temporary store is an
operating system file, the default TEMPORARY SIZE is half the size of the IQ store raw partition.
SYSTEM PROCEDURE AS DEFINER { ON | OFF }

Defines whether a privileged system procedure runs with the privileges of the invoker (the person
executing the procedure) or the definer (the owner of the procedure). OFF (default), or not specified,

SAP IQ SQL Reference


SQL Statements INTERNAL 1249
means all privileged system procedures execute with the privileges of the invoker. Use sp_proc_priv()
to identify the system privileges required to run a system procedure.

ON means that pre-16.0 privileged system procedures execute with the privileges of the definer. 16.0 or
later privileged system procedures execute with the privileges of the invoker.

Remarks

(back to top)

Creates a database with the supplied name and attributes. The IQ PATH clause is required for creating the SAP
IQ database; otherwise, you create a standard SAP SQL Anywhere database.

When SAP IQ creates a database, it automatically generates four database files to store different types of data
that constitute a database. Each file corresponds to a dbspace, the logical name by which SAP IQ identifies
database files:

● <db-name.db> is the file that holds the catalog dbspace, SYSTEM. It contains the system tables and
stored procedures describing the database and any standard SAP SQL Anywhere database objects you
add. If you do not include the .db extension, SAP IQ adds it. This initial dbspace contains the catalog store,
and you can later add dbspaces to increase its size. It cannot be created on a raw partition.
● <db-name.iq> is the default name of the file that holds the main data dbspace, IQ_SYSTEM_MAIN, which
contains the IQ tables and indexes. You can specify a different file name with the IQ PATH clause. This initial
dbspace contains the IQ store.

 Caution

IQ_SYSTEM_MAIN is a special dbspace that contains all structures necessary for the database to open:
the IQ db_identity blocks, the IQ checkpoint log, the IQ rollforward/rollback bitmaps of each committed
transaction and each active checkpointed transaction, the incremental backup bitmaps, and the
freelist root pages. IQ_SYSTEM_MAIN is always online when the database is open.

The administrator can allow user tables to be created in IQ_SYSTEM_MAIN, especially if these tables
are small, important tables. However, it is more common that immediately after creating the database,
the administrator creates a second main dbspace, revokes create privilege in dbspace
IQ_SYSTEM_MAIN from all users, grants create privilege on the new main dbspace to selected users,
and sets PUBLIC.default_dbspace to the new main dbspace.

● <db-name.iqtmp> messages trace is the default name of the file that holds the initial temporary dbspace,
IQ_SYSTEM_TEMP. It contains the temporary tables generated by certain queries. The required size of this
file can vary depending on the type of query and amount of data. You can specify a different name using
the TEMPORARY PATH clause. This initial dbspace contains the temporary store.
● <db-name.iqmsg> is the default name of the file that contains the messages trace dbspace,
IQ_SYSTEM_MSG. You can specify a different file name using the MESSAGE PATH clause.

In addition to these files, a database has a transaction log file (db-name.log), and might have a transaction
log mirror file.

The dbbackup utility truncates the database name to 70 characters and creates a target file with a truncated
name. SAP IQ uses dbbackup when synchronizing secondary servers. Due to dbbackup restrictions, database
names must be less than 70 characters long.

SAP IQ SQL Reference


1250 INTERNAL SQL Statements
The file names (<db-name>, <log-file-name>, <mirror-file-name>, <iq-file-name>, <message-
file-name>, <temp-file-name>) are strings containing operating system file names. As literal strings, they
must be enclosed in single quotes.

In Windows, if you specify a path, any backslash characters (\) must be doubled if they are followed by an n or
an x. This prevents them being interpreted as a newline character (\n) or as a hexadecimal number (\x),
according to the rules for strings in SQL. It is safer to always double the backslash. For example:

CREATE DATABASE 'c:\\SAP\\mydb.db'


DBA USER 'DBA' DBA PASSWORD 'passwd'
LOG ON 'e:\\logdrive\\mydb.log'
JCONNECT OFF
IQ PATH 'c:\\SAP\\mydb'
IQ SIZE 40

If you specify no path, or a relative path:

● The catalog store file (<db-name.db>) is created relative to the working directory of the server.
● The IQ store, temporary store, and message log files are created in the same directory as, or relative to, the
catalog store.

You should use relative path names.

 Caution

The database file, temporary dbspace, and transaction log file must be located on the same physical
machine as the database server. Do not place database files and transaction log files on a network drive.
The transaction log should be on a separate device from its mirror, however.

On UNIX-like operating systems, you can create symbolic links, which are indirect pointers that contain the
path name of the file to which they point. You can use symbolic links as relative path names. There are several
advantages to creating a symbolic link for the database file name:

● Symbolic links to raw devices can have meaningful names, while the actual device name syntax can be
obscure.
● A symbolic name might eliminate problems restoring a database file that was moved to a new directory
since it was backed up.

To create a symbolic link, use the ln -s command. For example:

ln -s /disk1/company/iqdata/company.iq company_iq_store

Once you create this link, you can specify the symbolic link in commands like CREATE DATABASE or RESTORE
DATABASE instead of the fully qualified path name.

When you create a database or a dbspace, the path for every dbspace file must be unique. If your CREATE
DATABASE command specifies the identical path and file name for these two stores, you receive an error.

You can create a unique path in any of these ways:

● Specify a different extension for each file (for example, mydb.iq and mydb.iqtmp)
● Specify a different file name (for example, mydb.iq and mytmp.iq)
● Specify a different path name (for example, /iqfiles/main/iq and /iqfiles/temp/iq) or different
raw partitions

SAP IQ SQL Reference


SQL Statements INTERNAL 1251
● Omit TEMPORARY PATH when you create the database. In this case, the temporary store is created in the
same path as the catalog store, with the default name and extension dbname.iqtmp, where <dbname> is
the database name.

 Caution

To maintain database consistency on UNIX-like operating systems, you must specify file names that are
links to different files. SAP IQ cannot detect the target where linked files point. Even if the file names in the
command differ, make sure they do not point to the same operating system file.

Character strings inserted into tables are always stored in the case they are entered, regardless of whether the
database is case-sensitive or not. If the string Value is inserted into a character data type column, the string is
always stored 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. The SAP IQ server may return results in any combination of
lowercase and uppercase, so you cannot expect case-sensitive results in a database that is case-insensitive
(CASE IGNORE).

For example, given this table and data:

CREATE TABLE tb (id int NOT NULL,


string VARCHAR(30) NOT NULL);
INSERT INTO tb VALUES (1, 'ONE');
SELECT * FROM tb WHERE string = 'oNe';

The result of the SELECT can be “oNe” (as specified in the WHERE clause) and not necessarily “ONE” (as
stored in the database).

Similarly, the result of the following can be "One":

SELECT * FROM tb WHERE string = 'One';

The result of the following can be "ONe":

SELECT * FROM tb WHERE string = 'ONe';

All databases are created with at least one user ID (DBA) and password (<password>).

In new databases, all passwords are case-sensitive, regardless of the case-sensitivity of the database. The user
ID is unaffected by the CASE RESPECT setting.

When you start a database, its page size cannot be larger than the page size of the current server. The server
page size is taken from the first set of databases started or is set on the server command line using the -gp
command line option.

Command line length for any statement is limited to the catalog page size. The 4 KB default is large enough in
most cases; however, in a few cases, a larger PAGE SIZE value is needed to accommodate very long
commands, such as RESTORE DATABASE commands that reference numerous dbspaces. A larger page size
might also be needed to execute queries involving large numbers of tables or views.

Because the default catalog page size is 4 KB, this is a problem only when the connection is to a database such
as utility_db, which has a page size of 1024. This restriction may cause RESTORE DATABASE commands
that reference numerous dbspaces to fail. To avoid the problem, make sure the length of SQL command lines is
less than the catalog page size.

Alternatively, start the engine with -gp 32768 to increase catalog page size.

SAP IQ SQL Reference


1252 INTERNAL SQL Statements
Privileges

(back to top)

The permissions required to execute this statement are set using the -gu server command line option, as
follows:

● NONE – No user can issue this statement.


● DBA – Requires the SERVER OPERATOR system privilege.
● UTILITY_DB – Only those users who can connect to the utility_db database can issue this statement.

The account under which the server is running must have write permissions on the directories where files are
created.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise provides a CREATE DATABASE statement, but
with different options.

Examples

(back to top)

● (Windows) This example creates an SAP IQ database named mydb with its corresponding mydb.db,
mydb.iq, mydb.iqtmp, and mydb.iqmsg files in the C:\s1\data directory:

CREATE DATABASE 'C:\\s1\\data\\mydb'


DBA USER 'DBA' DBA PASSWORD 'passwd'
BLANK PADDING ON
IQ PATH 'C:\\s1\\data'
IQ SIZE 2000
IQ PAGE SIZE 131072

● (UNIX) This example creates an SAP IQ database with raw devices for IQ PATH and TEMPORARY PATH.
The default IQ page size of 128 KB applies:

CREATE DATABASE '/s1/data/bigdb'

SAP IQ SQL Reference


SQL Statements INTERNAL 1253
DBA USER 'DBA' DBA PASSWORD 'passwd'
IQ PATH '/dev/md/rdsk/bigdb'
MESSAGE PATH '/s1/data/bigdb.iqmsg'
TEMPORARY PATH '/dev/md/rdsk/bigtmp'

● (Windows) This example creates an SAP IQ database with a raw device for IQ PATH. Note the doubled
backslashes in the raw device name (a Windows requirement):

CREATE DATABASE 'company'


DBA USER 'DBA' DBA PASSWORD 'passwd'
IQ PATH '\\\\.\\E:'
JCONNECT OFF
IQ SIZE 40

● (UNIX) This example creates a strongly encrypted SAP IQ database using the AES encryption algorithm
with the key “is!seCret.”

CREATE DATABASE 'marvin.db'


DBA USER 'DBA' DBA PASSWORD 'passwd'
BLANK PADDING ON
CASE RESPECT
COLLATION 'ISO_BINENG'
IQ PATH '/filesystem/marvin.main1'
IQ SIZE 6400
IQ PAGE SIZE 262144
TEMPORARY PATH '/filesystem/marvin.temp1'
TEMPORARY SIZE 3200
ENCRYPTED ON KEY 'is!seCret' ALGORITHM 'AES'

Related Information

CREATE DBSPACE Statement [page 1254]


DROP DATABASE Statement [page 1439]
REVOKE System Privilege Statement [page 1635]

9.4.42 CREATE DBSPACE Statement

Creates a new dbspace and the associated dbfiles for the IQ main store, cache dbspace, catalog store, or RLV
store.

 Syntax

Syntax 1 – Creates Only IQ Catalog Store dbspaces

CREATE DBSPACE <dbspace-name> AS <file-path> CATALOG STORE

Syntax 2 – Creates Only IQ Main Store dbspaces

CREATE DBSPACE <dbspace-name> USING <file-specification>


[ IQ STORE ] <iq-dbspace-opts>

Syntax 3 – Creates Only RLV dbspaces

CREATE DBSPACE <dbspace-name> USING <file-specification>

SAP IQ SQL Reference


1254 INTERNAL SQL Statements
IQ RLV STORE

Syntax 4 – Creates Only Cache dbspace dbspaces

CREATE DBSPACE <dbspace-name> USING FILE <file-specification>


IQ CACHE STORE

<file-specification> ::= or
{ <single-path-spec> | <new-file-spec> [, ...] }

<single-path-spec> ::=
'<file-path>' | <iq-file-opts>

<new-file-spec> ::=
FILE <logical-file-name > | '<file-path>' <iq-file-opts>

<iq-file-opts> ::=
[ [ SIZE ] <file-size> ]
…[ KB | MB | GB | TB ] ]
[ RESERVE <size>
…[ KB | MB | GB | TB ] ]

<iq-dbspace-opts> ::=
[ NOPREALLOCATE ]
[ STRIPING ] {ON | OFF} ] …[ STRIPESIZEKB <sizeKB> ]

Go to:

● Remarks [page 1256]


● Privileges [page 1257]
● Side Effects [page 1257]
● Standards [page 1257]
● Examples [page 1258]

Parameters

(back to top) [page 1254]

new-file-spec

Creates a dbspace for the IQ main store. You can specify one or more dbfiles for the IQ main store. The
dbfile name and physical file path are required for each file, and must be unique.
RESERVE

Specifies the size in kilobytes (KB), megabytes (MB), gigabytes (GB), or terabytes (TB) of space to reserve,
so that the dbspace can be increased in size in the future. The size parameter can be any number greater
than 0; megabytes is the default. You cannot change the reserve after the dbspace dbfile is created. When
RESERVE is specified, the database uses more space for internal (free list) structures. If reserve size is too
large, the space needed for the internal structures can be larger than the specified size, which results in an
error.
dbspace-name and dbfile-name

SAP IQ SQL Reference


SQL Statements INTERNAL 1255
Internal names for dbspaces and dbfiles. A database can have as many as (32 KB - 1) dbspaces, including
the initial dbspaces created when you create the database. However, your operating system might limit the
number of dbfiles per database.

 Note

SAP IQ supports IQ_SYSTEM_MAIN plus one user dbspace in the base product license. You must be
licensed for the IQ_VLDBMGMT option in order to create additional dbspaces.

file-path

The actual operating system file name of the dbfile, with a preceding path where necessary. <file-path>
without an explicit directory is created in the same directory as the catalog store of the database. Any
relative directory is relative to the catalog store.
SIZE

Specifies the size, from 0 to 4 terabytes, of the operating system file specified in <file-path>. The
default depends on the store type and block size. For the IQ main store, the default number of bytes equals
1000* the block size. You cannot specify the SIZE clause for the catalog store. A SIZE value of 0 creates a
dbspace of minimum size, which is 8 MB for the IQ main store. For raw partitions, do not explicitly specify
SIZE. SAP IQ automatically sets this parameter to the maximum raw partition size, and returns an error if
you attempt to specify another size.
NOPREALLOCATE

Instructs SAP IQ to bypass preallocation of dbspace files on cooked (not raw) file systems. Preallocation
can take an excessive amount of time if allocating large files to the dbspace on a cooked file system. You
cannot change the NOPREALLOCATE value. You must drop the dbspace in order to change the allocation.
NOPREALLOCATE is not available on IQ_SYSTEM_MAIN or IQ_SYSTEM_TEMP dbspaces.
STRIPESIZEKB

Specifies the number of kilobytes (KB) to write to each file before the disk striping algorithm moves to the
next stripe for the specified dbspace. If you do not specify striping or stripe size, the default values of the
options DEFAULT_DISK_STRIPING and DEFAULT_KB_PER_STRIPE apply.
IQ CACHE STORE

(Applies to cache dbspace only) Creates a cache dbspace.

Remarks

(back to top) [page 1254]

CREATE DBSPACE creates a new dbspace for the IQ main store, cache dbspace, catalog store, or RLV store.
The dbspace you add can be on a different disk device than the initial dbspace, allowing you to create stores
that are larger than one physical device.

Syntax 1 creates a dbspace for the catalog store, where both dbspace and dbfile have the same logical name.
Each dbspace in the catalog store has a single file.

The dbspace name and dbfile names are always case-insensitive. The physical file paths have the case
sensitivity of the operating system if the database is CASE RESPECT, and are case-insensitive if the database is
CASE IGNORE.

SAP IQ SQL Reference


1256 INTERNAL SQL Statements
You cannot create a dbspace for an IQ temporary store. A single temporary dbspace, IQ_SYSTEM_TEMP, is
created when you create a new database or upgrade one that was created in a version earlier than SAP IQ 15.3.
You can add additional files to the IQ_SYSTEM_TEMP dbspace using the ALTER DBSPACE ADD FILE
statement.

 Note

Creating a RLV dbspace containing a minimum of one file is a prerequisite for RLV storage. Before enabling
RLV storage on an SAP IQ server, check that the RLV dbspace exists.

You can create only one cache dbspace on an SAP IQ server or multiplex node. Attempting to create a second
cache dbspace results in an error.

You can create a unique path by specifying any of the following:

● A different extension for each file (for example, mydb.iq)


● A different file name (for example, mydb2.iq)
● A different path name (for example, /iqfiles/main/iq) or different raw partitions

 Caution

(UNIX platforms) To maintain database consistency, specify file names that are links to different files. SAP
IQ cannot detect the target where linked files point. Even if the file names in the command differ, make sure
they do not point to the same operating system file.

Privileges

(back to top) [page 1254]

Requires the MANAGE ANY DBSPACE system privilege. See GRANT System Privilege Statement [page 1511]
for assistance with granting privileges.

Side Effects

(back to top) [page 1254]

● Automatic commit
● Automatic checkpoint

Standards

(back to top) [page 1254]

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Statements INTERNAL 1257
Examples

(back to top) [page 1254]

● The following example creates a dbspace called DspHist for the IQ main store with two dbfiles on a UNIX
system. Each dbfile is 1 GB in size and can grow 500 MB:

CREATE DBSPACE DspHist USING FILE


FileHist1 '/History1/data/file1'
SIZE 1000 RESERVE 500,
FILE FileHist2 '/History1/data/file2'
SIZE 1000 RESERVE 500;

● The following example creates a second catalog dbspace called DspCat2:

CREATE DBSPACE DspCat2 AS


'catalog_file2'
CATALOG STORE;

● The following example creates an IQ main dbspace called EmpStore1 for the IQ store (three alternate
syntax examples):

CREATE DBSPACE EmpStore1


USING FILE EmpStore1
'EmpStore1.IQ' SIZE 8 MB IQ STORE;

CREATE DBSPACE EmpStore1


USING FILE EmpStore1
'EmpStore1.IQ' 8 IQ STORE;

CREATE DBSPACE EmpStore1


USING FILE EmpStore1
'EmpStore1.IQ' 8;

● The following example creates a RLV store dbspace called d1:

CREATE DBSPACE d1
USING FILE f1
'f1.iq' SIZE 1000 IQ RLV STORE;

● The following example creates a cache dbspace called myDAS with a 200 GB dbfile:

CREATE DBSPACE myDAS


USING FILE iqdas1
'iqdas1.iq' SIZE 200 GB IQ CACHE STORE

● The following example bypasses preallocation of dbspace files on a cooked file system:

CREATE DBSPACE BigDB USING FILE BigDB 'BigDB.iq' SIZE 500000 IQ STORE
NOPREALLOCATE;

Related Information

CREATE DATABASE Statement [page 1245]


DROP Statement [page 1433]
ALTER DBSPACE Statement [page 1136]

SAP IQ SQL Reference


1258 INTERNAL SQL Statements
REVOKE System Privilege Statement [page 1635]

9.4.43 CREATE DOMAIN Statement

Creates a user-defined data type in the database.

 Syntax

CREATE { DOMAIN | DATATYPE } <domain-name> <data-type>


… [ NOT ] NULL ]
… [ DEFAULT <default-value> ]

<default-value> ::=
<special-value>
| <string>
| <global variable>
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function>( <constant-expression> )
| AUTOINCREMENT
| CURRENT DATABASE
| CURRENT REMOTE USER
| NULL
| TIMESTAMP
| LAST USER

<special-value> ::=
CURRENT
{ DATE
| TIME
| TIMESTAMP
| USER
| PUBLISHER }
| USER

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

data-type

Built-in data type, with precision and scale.

SAP IQ SQL Reference


SQL Statements INTERNAL 1259
You can also specify a %TYPE or %ROWTYPE attribute to set the data type to the data type of a column or
row in a table or view. However, specifying a table reference variable for the %ROWTYPE (TABLE REF
(table-reference-variable) %ROWTYPE) is not allowed.

Remarks

(back to top)

User-defined data types are aliases for built-in data types, including precision and scale values, where
applicable. They improve convenience and encourage consistency in the database.

 Note

Use CREATE DOMAIN, rather than CREATE DATATYPE, as CREATE DOMAIN is the ANSI/ISO SQL3 term.

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 user-defined data type name must be unique, and all users can
access the data type without using the owner as prefix.

User-defined data types are objects within the database. Their names must conform to the rules for identifiers.
User-defined data type names are always case-insensitive, as are built-in data type names.

By default, user-defined data types allow NULLs unless the allow_nulls_by_default database option is set
to OFF. In this case, new user-defined data types by default do not allow NULLs. The nullability of a column
created on a user-defined data type depends on the setting of the definition of the user-defined data type, not
on the setting of the allow_nulls_by_default option when the column is referenced. Any explicit setting of
NULL or NOT NULL in the column definition overrides the user-defined data type setting.

The CREATE DOMAIN statement allows you to specify DEFAULT values on user-defined data types. The
DEFAULT value specification is inherited by any column defined on the data type. Any DEFAULT value explicitly
specified on the column overrides that specified for the data type.

The CREATE DOMAIN statement lets you incorporate a rule, called a CHECK condition, into the definition of a
user-defined data type.

SAP IQ enforces CHECK constraints for base, global temporary. local temporary tables, and user-defined data
types.

To drop the data type from the database, use the DROP statement. You must be either the owner of the data
type or have the CREATE DATATYPE or CREATE ANY OBJECT system privilege in order to drop a user-defined
data type.

Privileges

(back to top)

Requires one of:

● CREATE DATATYPE system privilege

SAP IQ SQL Reference


1260 INTERNAL SQL Statements
● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise. Transact-SQL provides similar
functionality using the sp_addtype system procedure and the CREATE DEFAULT and CREATE RULE
statements.

Examples

(back to top)

The following example creates a data type named address, which holds a 35-character string, and which may
be NULL:

CREATE DOMAIN address CHAR( 35 ) NULL

Related Information

%TYPE and %ROWTYPE attributes [page 93]


DROP Statement [page 1433]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1261
9.4.44 CREATE EVENT Statement

Defines an event and its associated handler for automating predefined actions. Also defines scheduled actions.

 Syntax

CREATE EVENT <event-name>


[ TYPE <event-type>
[ WHERE <trigger-condition> [ AND <trigger-condition> ], ...]
| SCHEDULE <schedule-spec>, … ]
… [ ENABLE | DISABLE ]
… [ AT { CONSOLIDATED | REMOTE | ALL } ]
… [ HANDLER
BEGIN

END ]

<event-type> ::=
BackupEnd
| "Connect"
| ConnectFailed
| DatabaseStart
| DBDiskSpace
| "Disconnect"
| GlobalAutoincrement
| GrowDB
| GrowLog
| GrowTemp
| IQMainDBSpaceFree
| IQTempDBSpaceFree
| 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> ]

Parameters

event-name

SAP IQ SQL Reference


1262 INTERNAL SQL Statements
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. You can list event names by querying the system table SYSEVENT. For example:

SELECT event_id, event_name FROM SYS.SYSEVENT

TYPE event-type

One of a 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 – 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.
● LogDiskSpace – checks the location of the transaction log and any mirrored transaction log, and
reports based on the least available space.
● Globalautoincrement – fires when the GLOBAL AUTOINCREMENT default value for a table is within
one percent of the end of its range. A typical action for the handler could be to request a new value for
the GLOBAL_DATABASE_ID clause.
You can use the EVENT_CONDITION function with RemainingValues as an argument for this event type.
● ServerIdle – if the database contains an event handler for the ServerIdle type, the server checks for
server activity every 30 seconds.
WHERE trigger-condition

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 percent full, use this 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.

You can specify a variable name for the event_condition value.


SCHEDULE schedule-spec

Specifies when scheduled actions are to take place. The sequence of times acts as a set of triggering
conditions for the associated actions defined in the event handler.You can create more than one schedule
for a given event and its associated handler. This permits complex schedules to be implemented. While it is
compulsory to provide a schedule name when there is more than one schedule, it is optional if you provide
only a single schedule.

You can list schedule names by querying the system table SYSSCHEDULE. For example:

SELECT event_id, sched_name FROM SYS.SYSSCHEDULE

Each event has a unique event ID. Use the event_id columns of SYSEVENT and SYSSCHEDULE to match
the event to the associated schedule.

When a nonrecurring scheduled event has passed, its schedule is deleted, but the event handler is not
deleted.

SAP IQ SQL Reference


SQL Statements INTERNAL 1263
Scheduled event times are calculated when the schedules are created, and again when the event handler
completes execution. The next event time is computed by inspecting the schedule or schedules for the
event, and finding the next schedule time that is in the future. If an event handler is instructed to run every
hour between 9:00 and 5:00, and it takes 65 minutes to execute, it runs at 9:00, 11:00, 1:00, 3:00, and
5:00. If you want execution to overlap, you must create more than one event.

The subclauses of a schedule definition are as follows:

● START DATE – the date on which scheduled events are to start occurring. The default is the current
date.
● START TIME – the first scheduled time for each day on which the event is scheduled. If a START DATE
is specified, the START TIME refers to that date. If no START DATE is specified, the START TIME is on
the current day (unless the time has passed) and each subsequent day.
You can specify a variable name for <start-time>.
● BETWEEN … AND – a range of times during the day outside of which no scheduled times occur. If a
START DATE is specified, the scheduled times do not occur until that date.
You can specify a variable name for <start-time> and <end-time>.
● EVERY – an interval between successive scheduled events. Scheduled events occur only after the
START TIME for the day, or in the range specified by BETWEEN …AND.
You can specify a variable name for <period>.
● ON – a list of days on which the scheduled events occur. The default is every day. These can be
specified as days of the week or days of the month.
Days of the week are Monday, Tuesday, and so on. The abbreviated forms of the day, such as Mon, Tue,
and so on, may also be used. The database server recognizes both full-length and abbreviated day
names in any of the languages supported by SAP IQ.
Days of the month are integers from 0 to 31. A value of 0 represents the last day of any month.

Each time a scheduled event handler is completed, the next scheduled time and date is calculated.

● If the EVERY clause is used, find whether the next scheduled time falls on the current day, and is before
the end of the BETWEEN …AND range. If so, that is the next scheduled time.
● If the next scheduled time does not fall on the current day, find the next date on which the event is to
be executed.
● Find the START TIME for that date, or the beginning of the BETWEEN … AND range.
ENABLE | DISABLE

By default, event handlers are enabled. When DISABLE is specified, the event handler does not execute
even when the scheduled time or triggering condition occurs. A TRIGGER EVENT statement does not
cause a disabled event handler to be executed
AT { CONSOLIDATED | REMOTE | ALL }

To execute events at remote or consolidated databases in a SQL Remote setup, use this clause to restrict
the databases at which the event is handled. By default, all databases execute the event.
HANDLER

Each event has one handler. Like the body of a stored procedure, the handler is a compound statement.
There are some differences, though: you can use an EXCEPTION clause within the compound statement to
handle errors, but not the ON EXCEPTION RESUME clause provided within stored procedures.

SAP IQ SQL Reference


1264 INTERNAL SQL Statements
Remarks

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 might want to develop and test event handlers using TRIGGER
EVENT and add the schedule or WHERE clause once testing is complete.

Event errors are logged to the database server console.

When event handlers are triggered, the server makes context information, such as the connection ID that
caused the event to be triggered, available to the event handler using the EVENT_PARAMETER function.

 Note

Although statements that return result sets are disallowed in events, you can allow an event to call a stored
procedure and insert the procedure results into a temporary table.

For parameters that accept variable names, an error is returned if one of the following conditions is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Requires one of:

● MANAGE ANY EVENT system privilege.


● CREATE ANY OBJECT system privilege.

Event handlers execute on a separate connection, with the privileges of the event owner. To execute an event
with privileges other than MANAGE ANY EVENT system privilege, you can call a procedure from within the
event handler. The procedure executes with the permissions of its owner.

Side Effects

● Automatic commit.
● The actions of an event handler are committed if no error is detected during execution, and rolled back if
errors are detected.

SAP IQ SQL Reference


SQL Statements INTERNAL 1265
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example instructs the database server to carry out an automatic incremental backup daily at
1 a.m.:

CREATE EVENT IncrementalBackup


SCHEDULE
START TIME '1:00AM' EVERY 24 HOURS
HANDLER
BEGIN
BACKUP DATABASE INCREMENTAL
TO 'backups/daily.incr'
END

● The following example instructs the database server to call the system stored procedure
sp_iqspaceused every 10 minutes, then store in a table the returned current date and time, the current
number of connections to the database, and current information about the use of main and temporary IQ
store:

CREATE TABLE mysummary(dt DATETIME,


users INT, mainKB UNSIGNED BIGINT,
mainPC UNSIGNED INT,
tempKB UNSIGNED BIGINT,
tempPC UNSIGNED INT) ;

CREATE EVENT mysummary


SCHEDULE sched_mysummary
START TIME '00:01 AM' EVERY 10 MINUTES
HANDLER
BEGIN
DECLARE mt UNSIGNED BIGINT;
DECLARE mu UNSIGNED BIGINT;
DECLARE tt UNSIGNED BIGINT;
DECLARE tu UNSIGNED BIGINT;
DECLARE conncount UNSIGNED INT;

SET conncount = DB_PROPERTY('ConnCount');


CALL SP_IQSPACEUSED(mt,mu,tt,tu);

INSERT INTO mysummary VALUES( NOW(),


conncount, mu, (mu*100)/mt, tu,
(tu*100)/tt );
END;

● The following example posts a message to the server log when free disk space on the device containing the
transaction log file falls below 30 percent, but execute the handler no more than once every 300 seconds:

CREATE EVENT LowTxnLogDiskSpace


TYPE DBDiskSpace
WHERE event_condition( 'DBFreePercent' ) < 30
AND event_condition( 'Interval' ) >= 300
HANDLER

SAP IQ SQL Reference


1266 INTERNAL SQL Statements
BEGIN
message 'Disk space for Transaction Log is low.';
END;

Related Information

EVENT_CONDITION Function [System] [page 354]


EVENT_CONDITION_NAME Function [System] [page 356]
EVENT_PARAMETER Function [System] [page 357]
ALTER EVENT Statement [page 1142]
BEGIN … END Statement [page 1218]
COMMENT Statement [page 1233]
DROP Statement [page 1433]
TRIGGER EVENT Statement [page 1694]
REVOKE System Privilege Statement [page 1635]

9.4.45 CREATE EXISTING TABLE Statement

Creates a new proxy table that represents an existing table on a remote server.

 Syntax

CREATE EXISTING TABLE [<owner>.]<table_name>


[ ( <column-definition>, … ) ]
AT '<location-string>'

<column-definition> ::= <column-name> <data-type> [ NOT NULL ]

<location-string> ::=
<remote-server-name>.[<db-name>].[<owner>].<object-name>
| <remote-server-name>;[<db-name>];[<owner>];<object-name>

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

column-definition

SAP IQ SQL Reference


SQL Statements INTERNAL 1267
If you do not specify column definitions, SAP IQ derives the column list from the metadata it obtains from
the remote table. If you do specify column definitions, SAP IQ verifies them. When SAP IQ checks column
names, data types, lengths, and null properties:

● Column names must match identically (although case is ignored).


● Data types in CREATE EXISTING TABLE 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 NUMERIC, whereas
the remote column data type is MONEY. You may encounter some errors, if you select from a table in
which the data types do not match or other inconsistencies exist.
● 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 lengths of CHAR, VARCHAR, BINARY, DECIMAL, and NUMERIC
columns do not match, a warning message is issued, but the command is not aborted. You might
choose to include only a subset of the actual remote column list in your CREATE EXISTING statement.
AT 'location-string'

Specifies the location of the remote object. The AT clause supports the semicolon (;) as a delimiter. If a
semicolon is present anywhere in the <column-definition>, 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. An ESCAPE CHARACTER clause allows applications to escape these
delimiters within a location string.

When you create a proxy table by using either the CREATE TABLE or the CREATE EXISTING statement, the
AT clause includes a location string that consists of the following parts:

● The name of the remote server


● The remote catalog
● The remote owner or schema
● The remote table name

Use a period or semicolon to delimit the location strings. The location string can also contain variable
names that are expanded when the database server evaluates the location string. Variable names within
the location string are encapsulated within braces. It is very rare to have a period, semicolon, and a brace,
or just a brace, be part of a remote server name, catalog name, owner name, schema name, or table name.
However, there may be some situations where one or all of these delimiter characters must be interpreted
literally within a location string.

 Note

The ESCAPE clause is only necessary if there is a need to escape delimiters within the location clause.
In general, the ESCAPE clause can be omitted when creating proxy tables. The escape character can be
any single byte character.

The string in the AT clause can contain local or global variable names enclosed in braces (for example,
{variable-name}). The SQL variable name must be of type CHAR, VARCHAR, or LONG VARCHAR. For
example, an AT clause that contains 'access;{@myfile};;a1' indicates that @myfile is a SQL variable
and that the current contents of the @myfile variable should be substituted when the proxy table is
created.

SAP IQ SQL Reference


1268 INTERNAL SQL Statements
Remarks

(back to top)

The CREATE EXISTING TABLE statement creates a new, local, proxy table that maps to a table at an external
location. CREATE EXISTING TABLE 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 to import its metadata. This
syntax establishes the remote table as a visible entity to users. The software verifies that the table exists at the
external location before it creates the table.

Tables used as proxy tables cannot have names longer than 30 characters.

If the object does not exist (either as a host data file or remote server object), the statement is rejected with an
error message.

Index information from the host data file or remote server table is extracted and used to create rows for the
ISYSIDX system table. This information defines indexes and keys in server terms and enables the query
optimizer to consider any indexes that may exist on this table.

Referential constraints are passed to the remote location when appropriate.

In a simplex environment, you cannot create a proxy table that refers to a remote table on the same node. In a
multiplex environment, you cannot create a proxy table that refers to the remote table defined within the
multiplex.

For example, in a simplex environment, if you try to create proxy table proxy_e, which refers to base table
Employees defined on the same node, the CREATE EXISTING TABLE statement is rejected with an error
message. In a multiplex environment, the CREATE EXISTING TABLE statement is rejected if you create proxy
table proxy_e from any node (coordinator or secondary) that refers to remote table Employees defined
within a multiplex.

If <column-definitions> are not specified, then the database server derives the column list from the
metadata it obtains from the remote table. If column-definitions are specified, then the database server verifies
the column-definitions. Column names, data types, lengths, the identity property, and null properties are
checked for the following conditions:

● Column names must match identically (although case is ignored).


● Data types in the CREATE EXISTING TABLE statement must match or be convertible to the data types of
the column on the remote location. For example, a local column data type is defined as money, while the
remote column data type is numeric.
● Each column's NULL property is checked. If the local column's NULL property is not identical to the remote
column's NULL property, then 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, then 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. Referential constraints are passed to the remote location when appropriate.

Privileges

(back to top)

To create a table to be owned by self requires one of:

SAP IQ SQL Reference


SQL Statements INTERNAL 1269
● CREATE ANY TABLE system privilege.
● CREATE ANY OBJECT system privilege.

To create a table to be owned by another user requires the CREATE ANY TABLE system privilege.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – not in the ISO/ANSI SQL standard.


● SAP database products – supported by SAP Adaptive Server Enterprise. The format of <location-
string> is implementation-defined.

Examples

(back to top)

● The following example creates a proxy table named nation for the nation table at the remote server
server_a:

CREATE EXISTING TABLE nation


( n_nationkey int,
n_name char(25),
n_regionkey int,
n_comment char(152))
AT 'server_a.db1.joe.nation'

● The following example creates a proxy table named blurbs for the blurbs table at the remote server
server_a. SAP IQ derives the column list from the metadata it obtains from the remote table:

CREATE EXISTING TABLE blurbs


AT 'server_a.db1.joe.blurbs'

● The following example creates a proxy table named rda_employee for the Employees table at the SAP IQ
remote server remote_iqdemo_srv:

CREATE EXISTING TABLE rda_employee


AT 'remote_iqdemo_srv..dba.Employees'

Related Information

CREATE TABLE Statement [page 1377]


REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1270 INTERNAL SQL Statements
9.4.46 CREATE EXTERNLOGIN Statement

Assigns an alternate login name and password to be used when communicating with a remote server.

 Syntax

CREATE EXTERNLOGIN <login-name>


TO <remote-server>
REMOTE LOGIN <remote-user>
[ IDENTIFIED BY <remote-password> ]

Parameters

login-name

Specifies the local user login name. When using integrated logins, the <login-name> is the database user
to which the Windows user ID is mapped.
TO remote-server

Specifies the name of the remote server.


REMOTE LOGIN remote-user

Specifies the user account on <remote-server> for the local user <login-name>.
IDENTIFIED BY remote-password

(Optional) Specifies that <remote-password> is the password for <remote-user>. If you omit the
IDENTIFIED BY clause, the password is sent to the remote server as NULL. If you specify IDENTIFIED BY " "
(an empty string), the password sent is the empty string.

Remarks

Changes made by CREATE EXTERNLOGIN do not take effect until the next connection to the remote server.

By default, SAP IQ 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. It stores the password internally in encrypted form.

The <remote_server> must be known to the local server by an entry in the ISYSSERVER system table. For
more information, see the CREATE SERVER Statement.

Creating a remote login with the CREATE EXTERNLOGIN statement and defining a remote server with a
CREATE SERVER statement sets up an external login and password for the INSERT...LOCATION such that any
user can use the login and password in any context. This avoids possible errors due to inaccessibility of the
login or password, and is the recommended way to connect to a remote server.

SAP IQ SQL Reference


SQL Statements INTERNAL 1271
 Note

If you rely on the user ID and password of the current connection, and a user changes the password, you
must stop and restart the server before the new password takes effect on the remote server. Remote logins
created with CREATE EXTERNLOGIN are unaffected by changes to the password for the default user ID.

Sites with automatic password expiration should plan for periodic updates of passwords for external logins.

CREATE EXTERNLOGIN cannot be used from within a transaction.

The <remote-user> and <remote-password> combination must be valid on <remote-server>.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example maps the local user named DBA to the user sa with password 4TKNOX when connecting
to the server mydb1:

CREATE EXTERNLOGIN dba


TO mydb1
REMOTE LOGIN sa
IDENTIFIED BY 4TKNOX

Related Information

DROP EXTERNLOGIN Statement [page 1441]

SAP IQ SQL Reference


1272 INTERNAL SQL Statements
INSERT Statement [page 1534]
CREATE SERVER Statement [page 1363]
REVOKE System Privilege Statement [page 1635]

9.4.47 CREATE FUNCTION Statement

Creates a user-defined function in the database. A function can be created for another user by specifying an
owner name. Subject to permissions, a user-defined function can be used in exactly the same way as other
non-aggregate functions.

 Syntax

Syntax 1

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>
| EXTERNAL NAME <native-call>
| EXTERNAL NAME <java-call> LANGUAGE JAVA }

<parameter> ::=
IN <parameter-name> <data-type> [ DEFAULT <expression> ]

<tsql-compound-statement> ::=
<sql-statement>
<sql-statement> …

<native-call> ::=
'[ <system-configuration>:]<function-name>@<library-file-prefix>; …'

<system-configuration> ::=
{ <generic-operating-system> | <specific-operating-system> } [ (<processor-
architecture>) ]

<generic-operating-system> ::= { UNIX | Windows }

<specific-operating-system> ::=
{ AIX | HPUX | Linux | OSX | Solaris | WindowsNT }

<processor-architecture> ::=
{ 32 | 64 | ARM | IA64 | PPC | SPARC | X86 | X86_64 }

<java-call> ::=
'[ <package-name>.]<class-name>.<method-name> <method-signature>'

<method-signature> ::=
( [ <field-descriptor>, ….] ) <return-descriptor>

SAP IQ SQL Reference


SQL Statements INTERNAL 1273
<field-descriptor> and <return-descriptor>
Z | B | S | I | J | F | D | C | V | [ <descriptor> | L <class-name>;

Syntax 2

CREATE FUNCTION [ <owner>.]<function-name> ( [ <parameter>, … ] )


RETURNS <data-type>
URL <url-string>
[ HEADER <header-string> ]
[ SOAPHEADER <soap-header-string> ]
[ TYPE { 'HTTP[:{ GET | POST } ] ' | 'SOAP[:{ RPC | DOC } ]' } ]
[ NAMESPACE <namespace-string> ]
[ CERTIFICATE <certificate-string> ]
[ CLIENTPORT <clientport-string> ]
[ PROXY <proxy-string> ]

<parameter> ::=
IN <parameter-name> <data-type> [ DEFAULT <expression> ]

<url-string> ::=
' { HTTP | HTTPS | HTTPS_FIPS }://[<user:password@>]<hostname>[:<port>][/
<path>] '

Parameters

CREATE [ OR REPLACE ]

Parameter names must conform to the rules for database identifiers. They must have a valid SQL data type
and be prefixed by the keyword IN, signifying that the argument is an expression that provides a value to
the function.

The CREATE clause creates a new function, while the OR REPLACE clause replaces an existing function
with the same name. When a function is replaced, the definition of the function is changed but the existing
permissions are preserved. You cannot use the OR REPLACE clause with temporary functions.
TEMPORARY

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 operations 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), and can only be owned
by their creator. Therefore, do not specify owner when creating a temporary function. They can be created
and dropped when connected to a read-only database.
SQL SECURITY

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.

When INVOKER is specified, more memory is used because annotation must be done for each user that
calls the procedure. Also, name resolution is done as the invoker as well. Therefore, take care to qualify all
object names (tables, procedures, and so on) with their appropriate owner.

SAP IQ SQL Reference


1274 INTERNAL SQL Statements
data-type

The data type of the parameter. Set the data type explicitly, or specify the %TYPE or %ROWTYPE attribute
to set the data type to the data type of another object in the database. Use %TYPE to set it to the data type
of a column in a table or view. Use %ROWTYPE to set the data type to a composite data type derived from
a row in a table or view. LONG BINARY and LONG VARCHAR are not permitted as return-value data types.
compound-statement

A set of SQL statements bracketed by BEGIN and END, and separated by semicolons. See BEGIN … END
Statement.
tsql-compound-statement

A batch of Transact-SQL statements.


external-name

A wrapper around a call to a function in an external library and can have no other clauses following the
RETURNS clause. The library name may 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 external-name clause is not supported for temporary functions.
LANGUAGE JAVA

A wrapper around a Java method. For information on calling Java procedures, see CREATE PROCEDURE
Statement.
ON EXCEPTION RESUME

Uses Transact-SQL-like error handling. See CREATE PROCEDURE Statement.


[NOT] DETERMINISTIC

Function is re-evaluated each time it is called in a query. The results of functions not specified in this
manner may be cached for better performance, and re-used each time the function is called with the same
parameters during query evaluation.

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 may be declared as DETERMINISTIC if they always return the same value for given input
parameters. All user-defined 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 will return the same result without unwanted side-effects on the semantics of the
query.
URL

SAP IQ SQL Reference


SQL Statements INTERNAL 1275
For web service client functions, the return type of SOAP and HTTP functions must one of the character
data types, such as VARCHAR. 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.

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

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.
For moFor use only when defining an HTTP or SOAP web services client function. Specifies information
about how to use this the URL 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 clause,
see the HEADER clause of the authentication base-64 encodes the user and password information and
passes it in the “Authentication” header of the HTTP request.
SOAPHEADER

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

Specifies the format used when making the web service request. If SOAP is specified or no type clause is
included, the default type SOAP:RPC is used. HTTP implies HTTP:POST. Since SOAP requests are always
sent as XML documents, HTTP:POST is always used to send SOAP requests.
NAMESPACE

Applies to SOAP client functions only and 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 description 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.
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. The certificate
can be placed in a file and the name of the file provided using the file key, or the whole certificate can be
placed in a string, but not both. These keys are available:

Key Abbreviation Description

file File name of certificate

certificate cert The certificate

company co Company specified in the certificate

unit For use only when defining an HTTP or SOAP web services client
function. SpecifiesCompany unit specified in the certificate

SAP IQ SQL Reference


1276 INTERNAL SQL Statements
Key Abbreviation Description

name Common name specified in the certificate

Certificates are required only for requests that are either directed to an HTTPS server or can be redirected
from an insecure to a secure server.

CLIENTPORT

Identifies the port number on which the HTTP client procedure 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

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.

Remarks

To modify a user-defined function, or to hide the contents of a function by scrambling its definition, use the
ALTER FUNCTION statement.

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.

Required Parameters
For required parameters that accept variable names, an error is returned if one of the following conditions is
true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

To create a function to be owned by self requires the CREATE PROCEDURE system privilege.

To create a function to be owned by another user requires one of:

● CREATE ANY PROCEDURE system privilege.


● CREATE ANY OBJECT system privilege.

To create a function containing an external reference, regardless of ownership of the function also requires the
CREATE EXTERNAL REFERENCE system privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1277
See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example 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

● This example illustrates the use of the fullname function.


○ Return a full name from two supplied strings:

SELECT fullname ('joe','smith')

fullname('joe', 'smith')

joe smith

○ List the names of all employees:

SELECT fullname (givenname, surname)


FROM Employees

fullname (givenname, surname)

Fran Whitney

Matthew Cobb

Philip Chin

SAP IQ SQL Reference


1278 INTERNAL SQL Statements
fullname (givenname, surname)

Julie Jordan

Robert Breault

...

● The following example uses Transact-SQL syntax:

CREATE FUNCTION DoubleIt ( @Input INT )


RETURNS INT
AS
DECLARE @Result INT
SELECT @Result = @Input * 2
RETURN @Result

The statement SELECT DoubleIt( 5 ) returns a value of 10.


● The following example creates an external function written in Java:

CREATE FUNCTION dba.encrypt( IN name char(254) )


RETURNS VARCHAR
EXTERNAL NAME
'Scramble.encrypt (Ljava/lang/String;)Ljava/lang/String;'
LANGUAGE JAVA

In this section:

CREATE FUNCTION Statement [Java UDF] [page 1280]


Creates a new external Java table UDF function in the database.

CREATE FUNCTION statement [Web service] [page 1283]


Creates a web client function that makes an HTTP or SOAP over HTTP request.

Related Information

%TYPE and %ROWTYPE attributes [page 93]


ALTER FUNCTION Statement [page 1144]
BEGIN … END Statement [page 1218]
CREATE PROCEDURE Statement [page 1321]
DROP Statement [page 1433]
RETURN Statement [page 1620]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1279
9.4.47.1 CREATE FUNCTION Statement [Java UDF]

Creates a new external Java table UDF function in the database.

 Syntax

CREATE [ OR REPLACE | TEMPORARY ] FUNCTION [ <owner>.]<function-name>


( [ <parameter>, ...] )
[ SQL SECURITY { INVOKER | DEFINER } ]
RETURNS <data-type>
ON EXCEPTION RESUME
| [ NOT ] DETERMINISTIC
{ <compound-statement> | AS <tsql-compound-statement>
| EXTERNAL NAME '<java-call>' LANGUAGE JAVA [ ALLOW | DISALLOW
SERVER SIDE REQUESTS ] <environment-name>}

<parameter> ::=
IN <parameter-name> <data-type> [ DEFAULT <expression> ]

<tsql-compound-statement> ::=
<sql-statement>
<sql-statement> …

<java-call> ::=
'[ <package-name>.]<class-name>.<method-name> <method-signature>'

<method-signature> ::=
( [ <field-descriptor>, ...] ) <return-descriptor>

<field-descriptor> and <return-descriptor> ::=


Z | B | S | I | J | F | D | C | V | [ <descriptor> | L <class-name>;

Parameters

CREATE [ OR REPLACE ]

Parameter names must conform to the rules for database identifiers. They must have a valid SQL data type
and be prefixed by the keyword IN, signifying that the argument is an expression that provides a value to
the function.

The CREATE clause creates a new function, while the OR REPLACE clause replaces an existing function
with the same name. When a function is replaced, the definition of the function is changed but the existing
permissions are preserved. You cannot use the OR REPLACE clause with temporary functions.
TEMPORARY

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 operations on them, and unlike other functions, temporary functions are not recorded in
the catalog or transaction log.

SAP IQ SQL Reference


1280 INTERNAL SQL Statements
Temporary functions execute with the permissions of their creator (current user), and can only be owned
by their creator. Therefore, do not specify owner when creating a temporary function. They can be created
and dropped when connected to a read-only database.
SQL SECURITY

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.

When INVOKER is specified, more memory is used because annotation must be done for each user that
calls the procedure. Also, name resolution is done as the invoker as well. Therefore, take care to qualify all
object names (tables, procedures, and so on) with their appropriate owner.
data-type

LONG BINARY and LONG VARCHAR are not permitted as return-value data types.
compound-statement

A set of SQL statements bracketed by BEGIN and END, and separated by semicolons. See BEGIN … END
Statement.
tsql-compound-statement

A batch of Transact-SQL statements.


[NOT] DETERMINISTIC

Function is re-evaluated each time it is called in a query. The results of functions not specified in this
manner may be cached for better performance, and re-used each time the function is called with the same
parameters during query evaluation.

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 may be declared as DETERMINISTIC if they always return the same value for given input
parameters. All user-defined 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 will return the same result without unwanted side-effects on the semantics of the
query.
LANGUAGE JAVA

A wrapper around a Java method. For information on calling Java procedures, see CREATE PROCEDURE
Statement.
environment-name

SAP IQ SQL Reference


SQL Statements INTERNAL 1281
A wrapper around a Java method.

The DISALLOW clause is the default. The ALLOW clause indicates that server-side connections are allowed.

 Note

Do not specify the ALLOW clause unless necessary. ALLOW slows down certain types of SAP IQ table
joins. Do not use UDFs with both the ALLOW and DISALLOW SERVER SIDE REQUESTS clauses in the
same query.

Remarks

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.

Privileges

For function to be owned by self – requires the CREATE PROCEDURE system privilege

For function to be owned by any user – requires one of:

● CREATE ANY PROCEDURES system privilege.


● CREATE ANY OBJECT system privilege.

To create a function containing an external reference, regardless of whether or not they are the owner of the
function, also requires the CREATE EXTERNAL REFERENCE system privilege.

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example creates an external function written in Java:

CREATE FUNCTION dba.encrypt( IN name char(254) )


RETURNS VARCHAR
EXTERNAL NAME
'Scramble.encrypt (Ljava/lang/String;)Ljava/lang/String;'
LANGUAGE JAVA

SAP IQ SQL Reference


1282 INTERNAL SQL Statements
9.4.47.2 CREATE FUNCTION statement [Web service]
Creates a web client function that makes an HTTP or SOAP over HTTP request.

 Syntax

CREATE [ OR REPLACE ] FUNCTION [ <owner>.]<function-name>


( [ <parameter>, ... ] )
RETURNS <data-type>
URL <url-string>
[ 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
| OPTIONS } ]

<soap-type-spec-string> :
SOAP[:{ RPC | DOC }

<parameter> :
[ IN ] <parameter-name> <datatype> [ DEFAULT <expression> ]

<url-string> :
{ HTTP | HTTPS | HTTPS_FIPS }://[<user>:<password>@]<hostname>[:<port>][/<path>]

<protocol-option-string> : <option-list> [, <option-list> ...]

<option-list> :
HTTP( <http-option> [ ;<http-option> ...] )
| SOAP( <soap-option> [ ;<soap-option> ...] )
| REDIR( <redir-option> [ ;<redir-option> ...] )

<http-option> :
CHUNK={ ON | OFF | AUTO }
| EXCEPTIONS={ ON | OFF | AUTO }
| VERSION={ 1.0 | 1.1 }
| KTIMEOUT=<number-of-seconds>

<soap-option> :
OPERATION=<soap-operation-name>

<redir-option> :
COUNT=<count>
| STATUS=<status-list>

SAP IQ SQL Reference


SQL Statements INTERNAL 1283
Parameters

OR REPLACE clause

Specifying CREATE OR REPLACE FUNCTION creates a new function, or replaces an existing function with
the same name. This clause changes the definition of the function, but preserves existing privileges. You
cannot use the OR REPLACE clause with temporary functions.
function-name

The name of the function.


parameter-name

Parameter names must conform to the rules for database identifiers. They must have a valid SQL data
type.

If a parameter has a default value, it need not be specified. Parameters with no default value must be
specified.

Parameters can 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.
data-type

The data type of the parameter. Set the data type explicitly, or specify the %TYPE or %ROWTYPE attribute
to set the data type to the data type of another object in the database. Use %TYPE to set it to the data type
of a column in a table or view. Use %ROWTYPE to set the data type to a composite data type derived from
a row in a table or view. However, defining the data type using a %ROWTYPE that is set to a table reference
variable (TABLE REF (<table-reference-variable>) %ROWTYPE) is not allowed.

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

SAP IQ SQL Reference


1284 INTERNAL SQL Statements
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 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 function.

URL 'http://localhost/service?parm=1

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.

To use a certificate from the operating system certificate store, specify a URL beginning with https://.
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:POST and HTTP:PUT types. When
HTTP:PUT is used, then a MIME-type must be specified.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
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. When a MIME-type is specified then the single body parameter is sent in the request as is, so the
application must ensure that the content is formatted to match the MIME-type.

Some typical MIME-types include:

● text/plain
● text/html
● text/xml

When no MIME-type is specified, parameter names and values (multiple parameters are permitted) are
URL encoded within the body of the HTTP request.

The keywords for the TYPE clause have the following meanings:

'HTTP:GET'

By default, this type uses the application/x-www-form-urlencoded MIME-type for encoding


parameters specified in the URL.

For example, the following request is produced when a client submits a request from the URL http://
localhost/WebServiceName?arg1=param1&arg2=param2:

GET /WebServiceName?arg1=param1&arg2=param2 HTTP/1.1


// <End of Request - NO BODY>

'HTTP:POST'

By default, this type uses the application/x-www-form-urlencoded MIME-type for encoding


parameters specified in the body of a POST request. URL parameters are stored in the body of the
request.

SAP IQ SQL Reference


SQL Statements INTERNAL 1285
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 function that uploads
data to a database server running the %IQDIRSAMP%\SQLAnywhere\HTTP\put_data.sql sample:

CREATE OR REPLACE FUNCTION CPUT([data] LONG VARCHAR, resnm LONG VARCHAR,


mediatype LONG VARCHAR)
RETURNS LONG BINARY
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:PUT:!mediatype';
SELECT CPUT('hello world', 'hello', 'text/plain' );

'HTTP:DELETE'

A web service client function 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 function that deletes a
resource from a database server running the put_data.sql sample:

CREATE OR REPLACE FUNCTION CDEL(resnm LONG VARCHAR, mediatype LONG VARCHAR)


RETURNS LONG BINARY
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:DELETE:!mediatype';
SELECT CDEL('hello', 'text/plain' );

'HTTP:HEAD'

The HEAD method is identical to a GET method but the server does not return a body. A media type
can be specified.

CREATE OR REPLACE FUNCTION CHEAD(resnm LONG VARCHAR)


RETURNS LONG BINARY
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:HEAD';
SELECT CHEAD( 'hello' );

'HTTP:OPTIONS'

The OPTIONS method is identical to a GET method but the server does not return a body. A media
type can be specified. This method allows Cross-Origin Resource Sharing (CORS).
'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.

SAP IQ SQL Reference


1286 INTERNAL SQL Statements
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 functions, 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 to sign the HTTP
server's certificate (or any certificate higher in the signing chain). The necessary information is specified in
a string of semicolon-separated keyword=value pairs. The following keywords are available:

Keyword Abbreviation Description

file The file name of the certificate or


specify * to use a certificate from the
operating system certificate store.
Cannot be specified if either the certif­
icate or certificate_name keyword is
specified.

certificate cert The certificate itself. Cannot be speci­


fied if either the file or certifi-
cate_name keyword is specified.

certificate_name cert_name The name of a certificate stored in the


database. Cannot be specified if ei­
ther the file or certificate keyword is
specified.

company co The company specified in the certifi-


cate.

unit The company unit specified in the cer­


tificate.

name The common name specified in the


certificate.

SAP IQ SQL Reference


SQL Statements INTERNAL 1287
Keyword Abbreviation Description

skip_certificate_name_check Specify ON to prevent checking the


database server certificate.

 Note
Setting this option to ON is not
recommended because this set­
ting prevents the database server
from fully authenticating the
HTTP server.

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 function 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. The
<proxy-string> is usually an HTTP or HTTPS url-string. This is site specific information that you usually
need to obtain from your network administrator. This clause indicates that the function is to connect to the
proxy server and send the request to the web service through it. For an example, the following PROXY
clause sets the proxy server to proxy.example.com:

PROXY http://proxy.example.com

SET clause

Specifies protocol-specific behavior options for HTTP, SOAP, and REDIR (redirects). Only one SET clause is
permitted. The following list describes the supported SET options. CHUNK, EXCEPTIONS, VERSION, and
KTIMEOUT apply to the HTTP protocol, OPERATION applies to the SOAP protocol, and COUNT and
STATUS apply to the REDIR option. REDIR options can be included with either HTTP or SOAP protocol
options.

CHUNK={ ON | OFF | AUTO }

(short form CH) This HTTP 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.

SAP IQ SQL Reference


1288 INTERNAL SQL Statements
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.
EXCEPTIONS={ ON | OFF | AUTO }

(short form EX) This HTTP option allows you to control status code handling. The default is ON.

When set to ON or AUTO, HTTP client functions will return a response for HTTP success status codes
(1XX and 2XX) and all codes will raise the exception SQLE_HTTP_REQUEST_FAILED.

SET 'HTTP(EXCEPTIONS=AUTO)'

When set to OFF, HTTP client functions will always return a response, independent of the HTTP status
code. The HTTP status code will not be available.

Exceptions that are not related to the HTTP status code (for example,
SQLE_UNABLE_TO_CONNECT_TO_HOST) will be raised when appropriate regardless of the
EXCEPTIONS setting.
VERSION={ 1.0 | 1.1 }

(short form VER) This HTTP option allows you to specify the version of the HTTP protocol that is used
for the format of the HTTP message. For example, the following SET clause sets the HTTP version to
1.1:

SET 'HTTP(VERSION=1.1)'

Possible values are 1.0 and 1.1. If VERSION is not specified:

● if CHUNK is set to ON, 1.1 is used as the HTTP version


● if CHUNK is set to OFF, 1.0 is used as the HTTP version
● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode
KTIMEOUT=number-of-seconds

(short form KTO) This HTTP option allows you to specify the keep-alive timeout criteria, permitting a
web client function to instantiate and cache a keep-alive HTTP/HTTPS connection for a period of time.
To cache an HTTP keep-alive connection, the HTTP version must be set to 1.1 and KTIMEOUT set to a
non-zero value. KTIMEOUT may be useful for HTTPS connections particularly, if you notice a
significant performance difference between HTTP and HTTPS connections. A database connection
can only cache a single keep-alive HTTP connection. Subsequent calls to a web client function using
the same URI reuse the keep-alive connection. Therefore, the executing web client call must have a URI
whose scheme, destination host and port match that of the cached URI, and the HEADER clause must
not specify Connection: close. When KTIMEOUT is not specified, or is set to zero, HTTP/HTTPS
connections are not cached.
OPERATION=soap-operation-name

(short form OP) This SOAP option allows you to specify the name of the SOAP operation, if it is
different from the name of the function you are creating. The value of OPERATION is analogous to the

SAP IQ SQL Reference


SQL Statements INTERNAL 1289
name of a remote function call. For example, if you wanted to create a function called accounts_login
that calls a SOAP operation called login, you would specify something like the following:

CREATE FUNCTION accounts_login( name LONG VARCHAR, pwd LONG VARCHAR )


RETURNS LONG BINARY
SET 'SOAP(OPERATION=login)'

If the OPERATION option is not specified, the name of the SOAP operation must match the name of
the function you are creating.
COUNT=count

(short form CNT) This REDIR option allows you to control redirects. See STATUS below.
STATUS=status-list

(short form STAT) This REDIR option allows you to control redirects. HTTP response status codes such
as302 Found and 303 See Other are used to redirect web applications to a new URI, particularly after
an HTTP POST has been performed. For example, a client request could be:

GET /people/alice HTTP/1.1


Host: www.example.com
Accept: text/html, application/xhtml+xml
Accept-Language: en, de

The web server response could be:

HTTP/1.1 302 Found


Location: http://www.example.com/people/alice.en.html

In response, the client would send another HTTP request to the new URI. The REDIR options allow you
to control the maximum number of redirections allowed and which HTTP response status codes to
automatically redirect.

For example, SET 'REDIR(COUNT=3; STATUS=301,307)' allows a maximum limit of 3 re-directions


and permits redirection for 301 and 307 statuses. If one of the other redirection status codes such as
302 or 303 is received, an error is issued (SQLE_HTTP_REQUEST_FAILED).

The default redirection limit <count> is 5. By default, an HTTP client function 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 (SQLE_HTTP_REQUEST_FAILED). 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 function 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 function
will handle 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 will include these parameters.

Location: alternate_service?a=1&b=2

In the above example, the query parameters are a=1&b=2.

SAP IQ SQL Reference


1290 INTERNAL SQL Statements
The following example shows how several option settings are combined in the same SET clause:

CREATE FUNCTION accounts_login( name LONG VARCHAR, pwd LONG VARCHAR )


RETURNS LONG BINARY
SET 'HTTP( CHUNK=ON; VERSION=1.1 ), REDIR(COUNT=5;STATUS=302,303)'
...

The following example shows the use of short forms with uppercase and lowercase letters.

CREATE FUNCTION accounts_login( name LONG VARCHAR, pwd LONG VARCHAR )


RETURNS LONG BINARY
SET 'HTTP( CH=ON; Ver=1.1 ), REDIR(CNT=5;Stat=302,303)'
...

SOAPHEADER clause

(SOAP format only) 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.

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 FUNCTION soap_client( IN hd1 LONG VARCHAR, IN hd2 LONG VARCHAR, IN hd3
LONG VARCHAR)
RETURNS LONG BINARY
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 function's URL, up to but not including the optional path component.

You can specify a variable name for <namespace-string>. If the variable is NULL, the namespace
property is ignored.

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.

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.

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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1291
 Note

For required parameters that accept variable names, an error is returned if one of the following conditions is
true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

You must have the CREATE PROCEDURE system privilege to create functions owned by you.

You must have the CREATE ANY PROCEDURE or CREATE ANY OBJECT system privilege to create functions
owned by others.

To replace an existing function, you must own the procedure or have one of the following:

● CREATE ANY PROCEDURE and DROP ANY PROCEDURE system privileges.


● CREATE ANY OBJECT and DROP ANY OBJECT system privileges.
● ALTER ANY OBJECT or ALTER ANY PROCEDURE system privileges.

Side effects

Automatic commit.

Standards

ANSI/ISO SQL Standard

Not in the standard.


Transact-SQL

Not supported by Adaptive Server Enterprise.

 Example

1. The following statement creates a function named cli_test1 that returns images from the get_picture
service running on localhost:

CREATE FUNCTION cli_test1( image LONG VARCHAR )


RETURNS LONG BINARY
URL 'http://localhost/get_picture'
TYPE 'HTTP:GET';

SAP IQ SQL Reference


1292 INTERNAL SQL Statements
2. The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=widget:

SELECT cli_test1( 'widget' );

3. The following statement uses a substitution parameter to allow the request URL to be passed as an
input parameter. The secure HTTPS request uses a certificate stored in the database. The SET clause
is used to turn off CHUNK mode transfer-encoding.

CREATE CERTIFICATE client_cert


FROM FILE 'C:\\Users\\Public\\Documents\\SQL Anywhere
17\\Samples\\Certificates\\rsaroot.crt';
CREATE FUNCTION cli_test2( image LONG VARCHAR, myurl LONG VARCHAR )
RETURNS LONG BINARY
URL '!myurl'
CERTIFICATE 'certificate_name=client_cert'
TYPE 'HTTPS:GET'
SET 'HTTP(CH=OFF)'
HEADER 'ASA-ID';

4. The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=widget:

CREATE VARIABLE a_binary LONG BINARY;


SET a_binary = cli_test2( 'widget', 'https://localhost/get_picture' );
SELECT a_binary;

5. The following example creates a function using a variable in the NAMESPACE clause
1. The following statements create a variable for a NAMESPACE clause:

CREATE VARIABLE @ns LONG VARCHAR


SET @ns = 'http://wsdl.domain.com/';

2. The following statement creates a function named FtoC that uses a variable in the NAMESPACE
clause:

CREATE FUNCTION FtoC ( IN temperature LONG VARCHAR )


RETURNS LONG BINARY
URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'
NAMESPACE @ns;

Related Information

ALTER FUNCTION Statement [page 1144]


BEGIN … END Statement [page 1218]
CREATE PROCEDURE Statement [page 1321]
DROP Statement [page 1433]
RETURN Statement [page 1620]
Referencing Temporary Tables Within Procedures [page 1328]
BEGIN … END Statement [page 1218]
CALL Statement [page 1225]
CREATE PROCEDURE Statement [External Procedures] [page 1331]

SAP IQ SQL Reference


SQL Statements INTERNAL 1293
CREATE PROCEDURE Statement [T-SQL] [page 1329]
CREATE SERVER Statement [page 1363]
DROP Statement [page 1433]
EXECUTE IMMEDIATE Statement [ESQL] [SP] [page 1471]
GRANT EXECUTE Privilege Statement [page 1499]
ON_TSQL_ERROR Option [TSQL] [page 1946]
RAISERROR Statement [T-SQL] [page 1597]

9.4.48 CREATE INDEX Statement

Creates an index on a specified table, or pair of tables. Once an index is created, it is never referenced in a SQL
statement again except to delete it using the DROP INDEX statement.

 Syntax

CREATE [ UNIQUE ] [ <index-type> ] INDEX [ IF NOT EXISTS ] <index-name>


… ON [ <owner>.]<table-name>
… ( <column-name> [ , <column-name> ] … )
… [ { IN | ON } <dbspace-name> ]
… [ NOTIFY <integer> ]
… [ DELIMITED BY '<separators-string>' ]
… [ LIMIT <maxwordsize-integer> ]

<index-type> ::=
{ CMP | HG | HNG | WD | DATE | TIME | DTTM }

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

index-type

For columns in SAP IQ tables, you can specify an <index-type> of the following:

● HG (default) – High_Group
● WD – Word
● DATE
● TIME
● DTTM – Datetime

SAP IQ SQL Reference


1294 INTERNAL SQL Statements
If you do not specify an <index-type>, an HG index is created by default.

To create an index on the relationship between two columns in an IQ main store table, you can specify an
<index-type> of CMP (Compare). Columns must be of identical data type, precision and scale. For a
CHAR, VARCHAR, BINARY or VARBINARY column, precision means that both columns have the same width.

For maximum query speed, the correct type of index for a column depends on:

● The number of unique values in the column


● How the column is going to be used in queries
● The amount of disk space available

You can specify multiple indexes on a column of an IQ main store table, but these must be of different index
types. CREATE INDEX does not let you add a duplicate index type. SAP IQ chooses the fastest index
available for the current query or portion of the query. However, each additional index type might
significantly add to the space requirements of that table.
column-name

Specifies the name of the column to be indexed. A column name is an identifier preceded by an optional
correlation name. (A correlation name is usually a table name. For more information on correlation names,
see FROM Clause.) If a column name has characters other than letters, digits, and underscore, enclose it in
quotation marks (“”).

Only the HG and CMP index types can be specified on a multi-column index.

Foreign keys require nonunique indexes and composite foreign keys require nonunique composite HG
indexes. CHAR, VARCHAR, BINARY, and VARBINARY data cannot be more than 5300 bytes in a single-
column HG index. A multi-column HG index (both unique and non-unique) can contain a single CHAR,
VARCHAR, or BINARY column of up to 5297 bytes.
UNIQUE

Permitted for index type HG only. Ensures that no two rows in the table have identical values in all the
columns in the index. Each index key must be unique or contain a NULL in at least one column.

SAP IQ allows the use of NULL in data values on a user created unique multicolumn HG index, if the column
definition allows for NULL values and a constraint (primary key or unique) is not being enforced.
IF NOT EXISTS

If the named object already exists, no changes are made and an error is not returned.
IN

Specifies index placement. If you omit the IN clause, the index is created in the dbspace where the table is
created. An index is always placed in the same type of dbspace (IQ main store or temporary store) as its
table. When you load the index, the data is spread across any database files of that type with room
available. SAP IQ ensures that any <dbspace-name> you specify is appropriate for the index. If you try to
specify IQ_SYSTEM_MAIN or other main dbspaces for indexes on temporary tables, or vice versa, you
receive an error. Dbspace names are always case-insensitive, regardless of the CREATE DATABASE...CASE
IGNORE or CASE RESPECT specification.
DELIMITED BY

Specifies separators to use in parsing a column string into the words to be stored in the WD index of that
column. If you omit this clause or specify the value as an empty string, SAP IQ uses the default set of
separators. The default set of separators is designed for the default collation order (ISO-BINENG). It
includes all 7-bit ASCII characters that are not 7-bit ASCII alphanumeric characters, except for the hyphen

SAP IQ SQL Reference


SQL Statements INTERNAL 1295
and the single quotation mark. The hyphen and the single quotation mark are part of words by default.
There are 64 separators in the default separator set. For example, if the column value is this string:

The cat is on the mat

and the database was created with the CASE IGNORE setting using default separators, these words are
stored in the WD index from this string:

cat is mat on the

If you specify multiple DELIMITED BY and LIMIT clauses, no error is returned, but only the last clause of
each type is used.
separators-string

Must be a sequence of 0 or more characters in the collation order used when the database was created.
Each character in the separators string is treated as a separator. If there are no characters in the
separators string, the default set of separators is used. (Each separator must be a single character in the
collation sequence being used.) There cannot be more than 256 characters (separators) in the separators
string.

To specify tab as a delimiter, you can either type a TAB character within the separator string, or use the
hexadecimal ASCII code of the tab character, \x09. “\t” specifies two separators, \ and the letter t. To
specify newline as a delimiter, you can type a RETURN character or the hexadecimal ASCII code \x0a.

For example, the clause DELIMITED BY ' :;.\/t' specifies these seven separators:
space : ; . \ / t

Delimiter Separator String for the DELIMITED BY Clause

tab Either of the following:

● ' ' (type TAB )


● '\x09'

newline Either of the following:

● ' ' (type RETURN )


● '\x0a'

LIMIT

Can be used for the creation of the WD index only. Specifies the maximum word length that is permitted in
the WD index. Longer words found during parsing causes an error. The default is 255 bytes. The minimum
permitted value is 1 and the maximum permitted value is 255. If the maximum word length specified in the
CREATE INDEX statement or determined by default exceeds the column width, the used maximum word
length is silently reduced to the column width. Using a lower maximum permitted word length allows
insertions, deletions, and updates to use less space and time. The empty word (two adjacent separators) is
silently ignored. After a WD index is created, any insertions into its column are parsed using the separators
and maximum word size determined at create time. These separators and maximum word size cannot be
changed after the index is created.
NOTIFY

Gives notification messages after n records are successfully added for the index. The messages are sent to
the standard output device. A message contains information about memory usage, database space, and
how many buffers are in use. The default is 100,000 records. To turn off NOTIFY, set it to 0.

SAP IQ SQL Reference


1296 INTERNAL SQL Statements
Remarks

(back to top)

● There is no way to specify the index owner in the CREATE INDEX statement. Indexes are automatically
owned by the owner of the table on which they are defined. The index name must be unique for each
owner.
● Indexes cannot be created for views. The name of each index must be unique for a given table.
● CREATE INDEX is prevented whenever the statement affects a table currently being modified by another
connection. However, queries are allowed on a table that is also adding an index.
● After a WD index is created, any insertions into its column are parsed using the separators, and maximum
word size cannot be changed after the index is created. For CHAR columns, specify a space as at least one
of the separators or use the default separator set. SAP IQ automatically pads CHAR columns to the
maximum column width. If your column contains blanks in addition to the character data, queries on WD
indexed data might return misleading results. For example, column CompanyName contains two words
delimited by a separator, but the second word is blank padded:

'Concord' 'Farms '

Suppose that a user entered this query:

SELECT COUNT(*)FROM Customers WHERE CompanyName contains ('Farms')

The parser determines that the string contains the following, instead of 'Farms', and returns 0 instead of
1:

'Farms '

You can avoid this problem by using VARCHAR instead of CHAR columns.
● Data types:
○ You cannot use CREATE INDEX to create an index on a column with BIT data.
○ Only the default index, CMP index, or WD index can be created on CHAR and VARCHAR data with more
than 255 bytes.
○ Only the default and WD index types can be created on LONG VARCHAR data.
○ Only the default index, CMP index, and TEXT index types can be created on BINARY and VARBINARY
data with more than 255 bytes.
○ An HNG index or a CMP index cannot be created on a column with FLOAT, REAL, or DOUBLE data.
○ A TIME index can be created only on a column having the data type TIME.
○ A DATE index can be created only on a column having the data type DATE.
○ A DTTM index can be created only on a column having the data type DATETIME or TIMESTAMP.
● You can create a unique or nonunique HG index with more than one column. SAP IQ implicitly creates a
nonunique HG index on a set of columns that makes up a foreign key.
HG and CMP are the only types of indexes that can have multiple columns. You cannot create a DATE, TIME,
or index with more than one column.
The maximum width of a multicolumn concatenated key is 5 KB (5300 bytes). The number of columns
allowed depends on how many columns can fit into 5 KB. CHAR or VARCHAR data greater than 255 bytes are
not allowed as part of a composite key in single-column HG, DATE, TIME, or DTTM indexes.
An INSERT on a multicolumn index must include all columns of the index.

SAP IQ SQL Reference


SQL Statements INTERNAL 1297
Queries with a single column in the ORDER BY clause run faster using multicolumn HG indexes. In the
following example the HG index vertically projects <x> in sorted order:

SELECT abs (x) from t1


ORDER BY x

To enhance query performance, use multicolumn HG indexes to run ORDER BY operations on more than
one column (that can also include ROWID) in the SELECT or ORDER BY clause with these conditions:
○ All projected columns, plus all ordering columns (except ROWID), exist within the index
○ The ordering keys match the leading columns, in order
If more than one multicolumn HG index with the lowest distinct counts is used. index satisfies these
conditions, the index with the lowest distinct counts is used.If a query has an ORDER BY clause, and the
ORDER BY column list is a prefix of a multicolumn index where all columns referenced in the If a query has
an ORDER BY clause, and the ORDER BY column list is a prefix of a multicolumn index where all columns
referenced in the
index with the lowest distinct counts is used. index satisfies these conditions, the index with the lowest
distinct counts is used.If a query has an ORDER BY clause, and the ORDER BY column list is a prefix of a
multicolumn index where all columns referenced in the If a query has an ORDER BY clause, and the ORDER
BY column list is a prefix of a multicolumn index where all columns referenced in the SELECT list are
present in a multicolumn index, then the multicolumn index performs vertical projection; for example:

SELECT x,z,y FROM T


ORDER BY x,y

If expressions exist on base columns in the SELECT list, and all the columns referenced in all the
expressions are present in the multicolumn index, then the query will use a multicolumn index; for
example:

SELECT power(x,2), x+y, sin(z) FROM T


ORDER BY x,y

In addition to the two previous examples, if the ROWID() function is in the SELECT list expressions,
multicolumn indexes will be used. For example:

SELECT rowid()+x, z FROM T


ORDER BY x,y,z

In addition to the three previous examples, if ROWID() is present at the end of an ORDER BY list, and if the
columns of that list — except for ROWID() — use multicolumn indexes in the exact order, multicolumn
indexes will be used for the query. For example:

SELECT z,y FROM T


ORDER BY x,y,z,ROWID()

SAP IQ allows the use of NULL in data values on a user created unique multicolumn HG index, if the column
definition allows for NULL values and a constraint (primary key or unique) is not being enforced. The rules
for this feature are as follows:
○ A NULL is treated as an undefined value.
○ Multiple rows with NULL values in a unique index column or columns are allowed.
1. In a single column index, multiple rows with a NULL value in an index column are allowed.
2. In a multicolumn index, multiple rows with a NULL value in index column or columns are allowed,
as long as non-NULL values in the rest of the columns guarantee uniqueness in that index.

SAP IQ SQL Reference


1298 INTERNAL SQL Statements
3. In a multicolumn index, multiple rows with NULL values in all columns participating in the index are
allowed.
These examples illustrate these rules. Given the table table1:

CREATE TABLE table1


(c1 INT NULL, c2 INT NULL, c3 INT NOT NULL);

Create a unique single column HG index on a column that allows NULLs:

CREATE UNIQUE HG INDEX c1_hg1 ON table1 (c1);

According to rule 1 above, you can insert a NULL value into an index column in multiple rows:

INSERT INTO table1(c1,c2,c3) VALUES (NULL,1,1);


INSERT INTO table1(c1,c2,c3) VALUES (NULL,2,2);

Create a unique multicolumn HG index on a columns that allows NULLs:

CREATE UNIQUE HG INDEX c1c2_hg2 ON table1(c1,c2);

According to rule 2 above, you must guarantee uniqueness in the index. The following INSERT does not
succeed, since the multicolumn index c1c2_hg2 on row 1 and row 3 has the same value:

INSERT INTO table1(c1,c2,c3) VALUES (NULL,1,3);

These INSERT operations are successful, however, according to rules 1 and 3:

INSERT INTO table1(c1,c2,c3) VALUES (NULL,NULL,3);


INSERT INTO table1(c1,c2,c3) VALUES (NULL,NULL,4);

Uniqueness is preserved in the multicolumn index.


This UPDATE operation is successful, as rule 3 allows multiple rows with NULL values in all columns in the
multicolumn index:

UPDATE table1 SET c2=NULL WHERE c3=1

When a multicolumn HG index is governed by a unique constraint, a NULL value is not allowed in any
column participating in the index.
● You can use the BEGIN PARALLEL IQ … END PARALLEL IQ statement to group CREATE INDEX
statements on multiple IQ main store tables, so that they execute as though they are a single DDL
statement. See BEGIN PARALLEL IQ … END PARALLEL IQ Statement for more information.

 Caution

Using the CREATE INDEX command on a local temporary table containing uncommitted data fails and
generates the error message Local temporary table, <tablename>, must be committed in
order to create an index. Commit the data in the local temporary table before creating an index.

Privileges

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1299
Requires the CREATE object-level privilege on the dbspace where the index is being created. Also requires one
of:

● You own the underlying table of the index.


● CREATE ANY INDEX system privilege.
● CREATE ANY OBJECT system privilege.
● REFERENCES object-level privilege on the underlying table of the index.

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – SAP Adaptive Server Enterprise has a more complex CREATE INDEX statement
than SAP IQ. While the SAP ASE syntax is permitted in SAP IQ, some clauses and keywords are ignored.
For the full syntax of the SAP ASE CREATE INDEX statement, see the SAP Adaptive Server Enterprise
Reference Manual, Volume 2: Commands.

SAP ASE indexes can be either clustered or nonclustered. A clustered index almost always retrieves data faster
than a nonclustered index. Only one clustered index is permitted per table.

SAP IQ does not support clustered indexes. The CLUSTERED and NONCLUSTERED keywords are allowed by
SAP SQL Anywhere, but are ignored by SAP IQ. If no <index-type> is specified, SAP IQ creates an HG index
on the specified column(s).

SAP IQ does not permit the DESC keyword.

Index names must be unique on a given table for both SAP IQ and SAP ASE.

Examples

(back to top)

● The following example creates a Compare index on the projected_earnings and current_earnings
columns. These columns are decimal columns with identical precision and scale:

CREATE CMP INDEX proj_curr_cmp


ON sales_data

SAP IQ SQL Reference


1300 INTERNAL SQL Statements
( projected_earnings, current_earnings )

● The following example creates a High_Group index on the ID column of the SalesOrderItems table. The
data pages for this index are allocated from dbspace Dsp5:

CREATE HG INDEX id_hg


ON SalesOrderItems
( ID ) IN Dsp5

● The following example creates a High_Group index on the SalesOrderItems table for the ProductID
column:

CREATE HG INDEX item_prod_hg


ON Sales_OrderItems
( ProductID)

● The following example creates a WD index on the earnings_report table. Specify that the delimiters of
strings are space, colon, semicolon, and period. Limit the length of the strings to 25:

CREATE WD INDEX earnings_wd


ON earnings_report_table(varchar)
DELIMITED BY ‘ :;.’
LIMIT 25

● The following example creates a DTTM index on the SalesOrders table for the OrderDate column:

CREATE DTTM INDEX order_dttm


ON SalesOrders
( OrderDate )

Related Information

BEGIN PARALLEL IQ … END PARALLEL IQ Statement [page 1221]


DROP Statement [page 1433]
INDEX_PREFERENCE Option [page 1873]
FROM Clause [page 1483]
REVOKE System Privilege Statement [page 1635]

9.4.49 CREATE LDAP SERVER Statement

Creates a new LDAP server configuration object for LDAP user authentication. Parameters defined during the
creation of an LDAP server configuration object are stored in the ISYSLDAPSERVER (system view
SYSLDAPSERVER) system table.

 Syntax

CREATE LDAP SERVER <ldapua-server-name>


[ <ldapua-server-attribs> ]
[ WITH ACTIVATE ]

<ldapua-server-attribs> ::=

SAP IQ SQL Reference


SQL Statements INTERNAL 1301
SEARCH DN
URL { '<URL_string>' | NULL }
| ACCESS ACCOUNT { '<DN_string>' | NULL }
| IDENTIFIED BY { '<password>' | NULL }
| IDENTIFIED BY ENCRYPTED { <encrypted-password> | NULL }
| AUTHENTICATION URL { '<URL_string>' | NULL }
| CONNECTION TIMEOUT <timeout_value>
| CONNECTION RETRIES <retry_value>
| TLS { ON | OFF }

Go to:

● Privileges
● Standards
● Examples

Parameters

(back to top)

URL 'URL_string'

Identifies the host (by name or by IP address), port number, and the search to be performed for the DN
lookup for a given user ID. This value is validated for correct LDAP URL syntax before it is stored in the
ISYSLDAPSERVER system table. The maximum size for this string is 1024 bytes.
ACCESS ACCOUNT { 'DN_string' | NULL }

User created in the LDAP server for use by SAP IQ, not a user within SAP IQ. The distinguished name (DN)
for this user is used to connect to the LDAP server. This user has permissions within the LDAP server to
search for DNs by user ID in the locations specified by the SEARCH DN URL. The maximum size for this
string is 1024 bytes.
IDENTIFIED BY { 'password' | NULL }

Provides the password associated with the ACCESS ACCOUNT user. The password is stored using
symmetric encryption on disk. Use the value NULL to clear the password and set it to none. The maximum
size of a clear text password is 255 bytes.
IDENTIFIED BY ENCRYPTED { encrypted-password | NULL }

Configures the password associated with the ACCESS ACCOUNT distinguished name in an encrypted
format. The binary value is the encrypted password and is stored on disk as is. Use the value NULL to clear
the password and set it to none. The maximum size of the binary is 289 bytes. The encrypted key should
be a valid varbinary value. Do not enclose the encrypted key in quotation marks.
AUTHENTICATION URL { 'URL_string' | NULL }

Identifies the host (by name or IP address) and the port number of the LDAP server to use for
authentication of the user. This is the value defined for URL_string and is validated for correct LDAP URL
syntax before it is stored in ISYSLDAPSERVER system table. The DN of the user obtained from a prior DN
search and the user password bind a new connection to the authentication URL. A successful connection
to the LDAP server is considered proof of the identity of the connecting user. The maximum size for this
string is 1024 bytes.
CONNECTION TIMEOUT timeout_value

SAP IQ SQL Reference


1302 INTERNAL SQL Statements
Specifies the connection timeout from SAP IQ to the LDAP server for both DN searches and
authentication. This value is in milliseconds, with a default value of 10 seconds.
CONNECTION RETRIES retry_value

Specifies the number of retries on connections from SAP IQ to the LDAP server for both DN searches and
authentication. The valid range of values is 1– 60, with a default value of 3.
TLS { ON | OFF }

Defines whether the TLS or Secure LDAP protocol is used for connections to the LDAP server for both DN
searches and authentication. When set to ON, the TLS protocol is used and the URL would begin with
"ldap://" When set to OFF (or not specified), Secure LDAP protocol is used and the URL begins with
“ldaps://”. When using the TLS protocol, specify the database security option
TRUSTED_CERTIFICATES_FILE with a file name containing the certificate of the Certificate Authority (CA)
that signed the certificate used by the LDAP server.
WITH ACTIVATE

Activates the LDAP server configuration object for immediate use upon creation. This permits the
definition and activation of LDAP User Authentication in one statement. The LDAP server configuration
object state changes to READY when WITH ACTIVATE is used.

Privileges

(back to top)

Requires the MANAGE ANY LDAP SERVER system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Standards

(back to top)

ANSI SQL – compliance level: Transact-SQL extension.

Examples

(back to top)

● The following example sets the search parameters, the authentication URL, and sets a three second
timeout, and activates the server so it can begin authenticating users. It connects to the LDAP server
without TLS or SECURE LDAP protocols:

SET OPTION PUBLIC.login_mode = 'Standard,LDAPUA'


CREATE LDAP SERVER apps_primary
SEARCH DN
URL 'ldap://my_LDAPserver:389/dc=MyCompany,dc=com??sub?cn=*'
ACCESS ACCOUNT 'cn=aseadmin, cn=Users, dc=mycompany, dc=com'
IDENTIFIED BY 'Secret99Password'

SAP IQ SQL Reference


SQL Statements INTERNAL 1303
AUTHENTICATION URL 'ldap://my_LDAPserver:389/'
CONNECTION TIMEOUT 3000
WITH ACTIVATE

● The following example uses the same search parameters as example 1, but specifies “ldaps” so that a
Secure LDAP connection is established with the LDAP server on host my_LDAPserver, port 636. Only LDAP
clients using the Secure LDAP protocol may now connect on this port. The database security option
TRUSTED_CERTIFICATE_FILE must be set with a file name containing the certificate of the certificate
authority (CA) that signed the certificate used by the LDAP server at "ldaps://my_LDAPserver:636". During
the handshake with the LDAP server, the certificate presented by the LDAP server is checked by the SAP IQ
server (the LDAP client) to ensure that it is signed by one of the certificates listed in the file. This
establishes trust by the client that the server is who it says it is. The ACCESS ACCOUNT and IDENTIFIED
BY parameters establish trust by the LDAP server that the client is who it says it is.

SET OPTION PUBLIC.login_mode = 'Standard,LDAPUA'


SET OPTION PUBLIC.trusted_certificates_file = '/mycompany/shared/trusted.txt'
CREATE LDAP SERVER secure_primary
SEARCH DN
URL 'ldaps://my_LDPAserver:636/dc=MyCompany,dc=com??sub?cn=*'
ACCESS ACCOUNT 'cn=aseadmin, cn=Users, dc=mycompany, dc=com'
IDENTIFIED BY 'Secret99Password'
AUTHENTICATION URL 'ldaps://my_LDAPserver:636/'
CONNECTION TIMEOUT 3000
TLS OFF
WITH ACTIVATE

 Note

The TLS parameter must be OFF when Secure LDAP is used instead of TLS protocol.

● The following example establishes the TLS protocol on port 389. It also requires database security option
TRUSTED_CERTIFICATE_FILE to be set with a file name and provides the same type of security as example
2. In this example, the TLS protocol is ON to facilitate wider support by LDAP server vendors:

SET OPTION PUBLIC.login_mode = 'Standard,LDAPUA'


SET OPTION PUBLIC.trusted_certificates_file = '/mycompany/shared/trusted.txt'
CREATE LDAP SERVER tls_primary
SEARCH DN
URL 'ldap://my_LDAPserver:389/dc=MyCompany,dc=com??sub?cn=*'
ACCESS ACCOUNT 'cn=aseadmin, cn=Users, dc=mycompany, dc=com'
IDENTIFIED BY 'Secret99Password'
AUTHENTICATION URL 'ldap://my_LDAPserver:389/'
CONNECTION TIMEOUT 3000
TLS ON
WITH ACTIVATE

 Note

Check the requirements of all your LDAP servers when deciding how to configure Secure LDAP or TLS
for an SAP IQ server.

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1304 INTERNAL SQL Statements
9.4.50 CREATE LOGICAL SERVER Statement

Creates a user-defined logical server. This statement enforces consistent shared system temporary store
settings across physical nodes shared by logical servers.

 Syntax

CREATE LOGICAL SERVER <logical-server-name>


[ { <ls-create-clause>, ...} ] [ WITH STOP SERVER ]

<ls-create-clause> ::=
{ MEMBERSHIP ( { <ls-member>, ...} ) | POLICY <ls-policy-name> }

<ls-member> ::=
FOR LOGICAL COORDINATOR | <mpx-server-name>

Parameters

logical-server-name

Any user-specified identifier except the following:

● ALL
● AUTO
● COORDINATOR
● DEFAULT
● NONE
● OPEN
● SERVER
MEMBERSHIP

To define a logical membership to the coordinator, include FOR LOGICAL COORDINATOR in the
MEMBERSHIP clause.

When no members are specified during the creation of a logical server, the logical server is created empty.

 Note

Implicit logical server membership definitions, such as those for OPEN and SERVER logical servers, are
not stored at all.

The SYS.ISYSLOGICALMEMBER system table stores definitions for the logical server memberships.

Changing the ALLOW_COORDINATOR_AS_MEMBER option of the root logical server policy from ON to
OFF does not affect the membership information stored in the catalog. Instead, it affects only the effective
configuration of the logical server.

You can define a logical server membership to the current coordinator either by specifying the multiplex
server name or by using the FOR LOGICAL COORDINATOR clause, even when

SAP IQ SQL Reference


SQL Statements INTERNAL 1305
ALLOW_COORDINATOR_AS_MEMBER option is set to OFF. Membership definition is stored in the catalog,
but is inactive while that multiplex server acts as the coordinator.

The catalog stores the logical server and its membership definitions.
POLICY

Associates a logical server with a user-defined logical server policy. If no POLICY clause is specified, the
logical server is associated with the root policy. The SYS.ISYSIQLOGICALSERVER system table stores
information about the logical server policy for a corresponding logical server.
ls-policy-name

Any user-specified identifier except ROOT.


WITH STOP SERVER

Automatically shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP option
is changed directly or indirectly.

Remarks

Applies to multiplex only.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

● The following example creates a user-defined logical server ls1 with three multiplex nodes as its
members:

CREATE LOGICAL SERVER ls1 MEMBERSHIP ( n1, n2, n3 )

● The following example creates a user-defined logical server ls1 with three member nodes, and defines the
logical server policy name < lsp1>:

CREATE LOGICAL SERVER ls1 MEMBERSHIP ( w1_svr, w2_svr, r2_svr ) POLICY lsp1

● The following example creates servers as in Example 2, except that WITH STOP SERVER automatically
shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP option is changed
directly or indirectly:

CREATE LOGICAL SERVER ls1 MEMBERSHIP ( w1_svr, w2_svr, r2_svr ) POLICY lsp1
WITH STOP SERVER

SAP IQ SQL Reference


1306 INTERNAL SQL Statements
● The following example creates a user-defined logical server ls1 with logical server policy lspolicy1 and
no member nodes:

CREATE LOGICAL SERVER ls1 POLICY lspolicy1

● The following example where n1 is the current coordinator, creates a logical server ls2 with the named
membership of multiplex nodes n1 and n3 and logical membership of the coordinator. Also sets the logical
server policy of ls2 to lspolicy2:

CREATE LOGICAL SERVER ls2 POLICY


MEMBERSHIP FOR LOGICAL COORDINATOR
lspolicy1, n1, n2, n3 POLICY lspolicy2

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.51 CREATE LOGIN POLICY Statement

Creates a login policy in the database.

 Syntax

CREATE LOGIN POLICY <policy-name>

<policy-option> ::=
= <policy-option-value>

<policy-option-name> ::=
AUTO_UNLOCK_TIME
| CHANGE_PASSWORD_DUAL_CONTROL
| DEFAULT_LOGICAL_SERVER
| LOCKED
| MAX_CONNECTIONS
| MAX_DAYS_SINCE_LOGIN
| MAX_FAILED_LOGIN_ATTEMPTS
| MAX_NON_DBA_CONNECTIONS
| PAM_FAILOVER_TO_STD
| PAM_SERVICENAME
| PASSWORD_EXPIRY_ON_NEXT_LOGIN
| PASSWORD_GRACE_TIME
| PASSWORD_LIFE_TIME
| ROOT_AUTO_UNLOCK_TIME
| LDAP_PRIMARY_SERVER
| LDAP_SECONDARY_SERVER
| LDAP_AUTO_FAILBACK_PERIOD
| LDAP_FAILOVER_TO_STD
| LDAP_REFRESH_DN

<policy-option-value> ::=
{ UNLIMITED | DEFAULT | <value> }

SAP IQ SQL Reference


SQL Statements INTERNAL 1307
Parameters

policy-name

The name of the login policy. Specify root to modify the root login policy.
policy-option-name

The name of the policy option. See Login Policy Options and LDAP Login Policy Options for details about
each option.
policy-option-value

The value assigned to the login policy option. If you specify UNLIMITED, no limits are used. If you specify
DEFAULT, the default limits are used. See Login Policy Options and LDAP Login Policy Options for supported
values for each option.
.

Remarks

If you do not specify a policy option, values for this login policy come from the root login policy. New policies do
not inherit the MAX_NON_DBA_CONNECTIONS and ROOT_AUTO_UNLOCK_TIME policy options.

Privileges

Requires the MANAGE ANY LOGIN POLICY system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

The following system privileges can override the noted login policy options:

Exception System Privilege Login Policy Option

SERVER OPERATOR or DROP CONNECTION system MAX_NON_DBA_CONNS


privilege
MAX_CONNECTIONS

MANAGE ANY USER system privilege LOCKED

MAX_DAYS_SINCE_LOGIN

Examples

The following example creates the Test1 login policy:

CREATE LOGIN POLICY Test1


password_life_time=UNLIMITED
max_failed_login_attempts=5;

SAP IQ SQL Reference


1308 INTERNAL SQL Statements
This login policy has an unlimited password life and allows the user a maximum of five attempts to enter a
correct password before the account is locked.

In this section:

Login Policy Options [page 1309]


Available options for root and user-defined login policies.

LDAP Login Policy Options [page 1312]


Available login policy options for LDAP user authentication

Multiplex Login Policy Configuration [page 1312]


Configure login policies for multiplex servers.

Related Information

Login Policy Options


LDAP Login Policy Options
Multiplex Login Policy Configuration
ALTER LOGIN POLICY Statement [page 1155]
ALTER LOGIN POLICY Statement [page 1155]
REVOKE System Privilege Statement [page 1635]

9.4.51.1 Login Policy Options

Available options for root and user-defined login policies.

Option Description Properties

AUTO_UN­ The time period after which locked accounts that ● Values – 0 – UNLIMITED
LOCK_TIME are not granted the MANAGE ANY USER system ● Default – UNLIMITED
privilege are automatically unlocked. You can define ● Applies to all users who are not granted the
this option in any login policy, including the root MANAGE ANY USER system privilege
login policy.

CHANGE_PASS Requires input from two users, each of whom is ● Values – ON; OFF
WORD_DUAL_C granted the CHANGE PASSWORD system privilege, ● Default – OFF
ONTROL to change the password of another user. ● Applies to all users

SAP IQ SQL Reference


SQL Statements INTERNAL 1309
Option Description Properties

DEFAULT_LOG­ If the connection string specifies no logical server, ● Values:


ICAL_SERVER the user connects to the DEFAULT_LOGI­ ○ Name of an existing user-defined logical
CAL_SERVER option specified in the user's login server.
policy. ○ AUTO – value of the default logical server
in the root login policy.
○ COORDINATOR – the current coordinator
node.
○ NONE – denies access to any multiplex
server.
○ OPEN – use alone or with the name of a
user-defined logical server. Allows access
to all multiplex nodes that are not mem­
bers of any user-defined logical servers.
○ SERVER – allows access to all of the multi­
plex nodes, subject to the semantics of
the SERVER logical server.
● Default – AUTO
● Applies to all users. Requires MANAGE MULTI­
PLEX system privilege

LOCKED If set ON, users cannot establish new connections. ● Values – ON; OFF
This setting temporarily denies access to login pol­ ● Default – OFF
icy users. Logical server overrides for this option ● Applies to all users except those with the MAN­
are not allowed. AGE ANY USER system privilege

MAX_CONNEC­ The maximum number of concurrent connections ● Values – 0–2147483647


TIONS allowed for a user. You can specify a per-logical- ● Default – UNLIMITED
server setting for this option. ● Applies to all users except those with the
SERVER OPERATOR or DROP CONNECTION
system privilege

MAX_DAYS_SI The maximum number of days that can elapse be­ ● Values – 0–2147483647
NCE_LOGIN tween two successive logins by the same user. ● Default – UNLIMITED
● Applies to all users except those with the MAN­
AGE ANY USER system privilege

MAX_FAILED_L The maximum number of failed attempts, since the ● Values – 0–2147483647
OGIN_AT­ last successful attempt, to log in to the user ac­ ● Default – UNLIMITED
TEMPTS count before the account is locked. ● Applies to all users

MAX_NON_DB The maximum number of concurrent connections ● Values – 0–2147483647


A_CONNEC­ that a user without SERVER OPERATOR or DROP ● Default – UNLIMITED
TIONS CONNECTION system privileges can make. This op­ ● Applies to all users except those with the
tion is supported only in the root login policy. SERVER OPERATOR or DROP CONNECTION
privilege

SAP IQ SQL Reference


1310 INTERNAL SQL Statements
Option Description Properties

PAM_FAIL­ Use standard authentication if PAM authentication ● Values – ON; OFF


OVER_TO_STD is enabled but the PAM library is unavailable due to ● Default – ON
a system failure. Authentication failures returned by ● Applies to all users
PAM do not fail over to standard authentication.

PAM_SERV­ The PAM service name to use when authenticating.


ICE_NAME The service name identifies the rule set to be used
by PAM during validation. If empty (the default), do
not use PAM. The database server continues to
function when PAM support is unavailable. See Ena­
bling PAM User Authentication in Administration:
User Management and Security.

PASS­ If set ON, the user's password expires at the next ● Values – ON; OFF
WORD_EX­ login. ● Default – OFF
PIRY_ON_NEXT ● Applies to all users
_LOGIN  Note
This functionality is not currently implemented
when logging in to SAP IQ Cockpit. However,
when logging in to SAP IQ outside of SAP IQ
Cockpit (for example, using Interactive SQL),
users are then prompted to enter a new pass­
word.

PASS­ The number of days before password expiration ● Values – 0–2147483647


WORD_GRACE_ during which login is allowed but the default ● Default – 0
TIME post_login procedure issues warnings. ● Applies to all users.

PASS­ The maximum number of days before a password ● Values – 0–2147483647


WORD_LIFE_TI must be changed. ● Default: UNLIMITED
ME ● Applies to all users

ROOT_AUTO_U The time period after which locked accounts that ● Values: 0 – UNLIMITED
NLOCK_TIME are granted the MANAGE ANY USER system privi­ ● Default: 15
lege are automatically unlocked. You can define this ● Applies to all users who are granted the MAN­
option only in the root login policy. AGE ANY USER system privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1311
9.4.51.2 LDAP Login Policy Options

Available login policy options for LDAP user authentication

Option Description Properties

LDAP_PRI­ Specifies the name of the primary LDAP server. ● Values – N/A
MARY_SERVER ● Default – none
● Applies to all users

LDAP_SECON­ Specifies the name of the secondary LDAP server. ● Values – N/A
DARY_SERVER ● Default – none
● Applies to all users

LDAP_AUTO_F Specifies the time period, in minutes, after which ● Values – 0–2147483647
AILBACK_PE­ automatic failback to the primary server is at­ ● Default – 15 minutes
RIOD tempted. ● Applies to all users

LDAP_FAIL­ Permits authentication with standard authentica­ ● Values – ON; OFF


OVER_TO_STD tion when authentication with the LDAP server fails ● Default – ON
due to system resources, network outage, connec­ ● Applies to all users
tion timeouts, or similar system failures. However,
it does not permit an actual authentication failure
returned from an LDAP server to fail over to stand­
ard authentication.

LDAP_RE­ Updates the ldap_refresh_dn value in the ● Values – NOW


FRESH_DN ISYSLOGINPOLICYOPTION system table with ● Initial value for ROOT policy – NULL
the current time, stored in Coordinated Universal ● Initial value for user-defined login policy – cur­
Time (UTC). rent time stored in UTC

Each time a user authenticates with LDAP, if the ● Applies to all users

value of ldap_refresh_dn in
ISYSLOGINPOLICYOPTION is more recent than
the value of user_dn in ISYSUSER, a search for a
new user DN occurs. The user_dn value is then
updated with the new user DN and the
user_dn_changed_at value is again updated
to the current time.

9.4.51.3 Multiplex Login Policy Configuration

Configure login policies for multiplex servers.

This example overrides the login policy settings on a logical server, increasing the maximum number of
connections on logical server ls1:

ALTER LOGIN POLICY lp1 max_connections=20 LOGICAL SERVER ls1;

SAP IQ SQL Reference


1312 INTERNAL SQL Statements
Applies only to multiplex.

Any login management commands you execute on any multiplex server automatically propagate to all servers
in the multiplex. For best performance, execute these commands, or any DDL, on the coordinator.

An override at the logical server level override means that a particular login policy option has different settings
for different logical servers. SYS.ISYSIQLSLOGINPOLICYOPTION stores login policy option values for logical-
server override. For each logical-server override of a login policy option, a corresponding row exists in
ISYSIQLSLOGINPOLICYOPTION.

9.4.52 CREATE LS POLICY Statement

Creates a user-defined logical server policy. This statement enforces consistent shared system temporary
store settings across physical nodes shared by logical servers.

 Syntax

CREATE LS POLICY <ls-policy-name> <ls-option-value-list> [ WITH STOP SERVER ]

<ls-option-value-list> ::=
{ <ls-option-name> = <ls-policy-option-value> } ...

<ls-option-name> ::=
ALLOW_COORDINATOR_AS_MEMBER
| DQP_ENABLED
| ENABLE_AUTOMATIC_FAILOVER
| LOGIN_REDIRECTION
| REDIRECTION_WAITERS_THRESHOLD
| TEMP_DATA_IN_SHARED_TEMP

Parameters

ls-policy-name

The name of the logical server policy. You can specify any identifier except root for the policy name.
ls-option-value-list

The name of the logical server policy option. See Remarks.


ls-policy-option-value

Any unspecified option inherits its value from the root logical server policy. See Remarks.
WITH STOP SERVER

Automatically shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP option
is changed directly or indirectly.

SAP IQ SQL Reference


SQL Statements INTERNAL 1313
Remarks

Applies to multiplex only.

If you want a smaller IQ_SYSTEM_TEMP dbspace, set TEMP_DATA_IN_SHARED_TEMP to ON, which writes
temporary data to IQ_SHARED_TEMP instead of IQ_SYSTEM_TEMP. In a distributed query processing
environment, however, setting both DQP_ENABLED and TEMP_DATA_IN_SHARED_TEMP to ON may saturate
your SAN with additional data in IQ_SHARED_TEMP, where additional I/O operations against IQ_SHARED_TEMP
may adversely affect DQP performance.

Option Description Properties

ALLOW_COORDI­ Can only be set for the ROOT logical server policy. When ON ● Values – ON, OFF
NATOR_AS_MEM­ (the default), the coordinator can be a member of any user- ● Default – ON
BER defined logical server. OFF prevents the coordinator from be­
ing used as a member of any user-defined logical servers.

DQP_ENABLED When set to 0, query processing is not distributed. When set ● Values – 0, 1, 2
to 1 (the default), query processing is distributed as long as a ● Default – 1
writable shared temporary file exists. When set to 2, query
processing is distributed over the network, and the shared
temporary store is not used.

ENABLE_AUTO­ Can only be set for the ROOT logical server policy. When ON, ● Values – ON, OFF, DEFAULT
MATIC_FAILOVER enables automatic failover for logical servers governed by ● Default – OFF
specified login policy. When OFF (the default), disables auto­
matic failover at the logical server level, allowing manual fail­
over. Specify DEFAULT to set back to the default value.

LOGIN_REDIREC­ When ON, enables login redirection for logical servers gov­ ● Values – ON, OFF
TION erned by specified login policy. When OFF (the default), disa­ ● Default – OFF
bles login redirection at the logical server level, allowing ex­
ternal connection management.

REDIREC­ Specifies how many connections can queue before SAP IQ ● Values – Integer
TION_WAIT­ redirects a connection to this logical server to another ● Default – 5
ERS_THRESHOLD server. Can be any integer value; default is 5.

TEMP_DATA_IN_S When ON, all temporary table data and eligible scratch data ● Values – ON, OFF
HARED_TEMP writes to the shared temporary store, provided that the ● Default – OFF
shared temporary store has at least one read-write file
added. You must restart all multiplex nodes after setting this
option or after adding a read-write file to the shared tempo­
rary store. (If the shared temporary store contains no read-
write file, or if you do not restart nodes, data is written to
IQ_SYSTEM_TEMP instead.)

When OFF (the default), all temporary table data and


scratch data writes to the local temporary store.

SAP IQ SQL Reference


1314 INTERNAL SQL Statements
Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example creates a user-defined logical server policy named lspolicy1:

CREATE LS POLICY lspolicy1


ALLOW_COORDINATOR_AS_MEMBER=ON;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.53 CREATE MESSAGE Statement [T-SQL]

Adds a user-defined message to the SYSUSERMESSAGES system table for use by PRINT and RAISERROR
statements.

 Syntax

CREATE MESSAGE <message-number>


... AS '<message-text>'

Parameters

message-number

The message number of the message to add. The message number for a user-defined message must be
20000 or greater.

SAP IQ SQL Reference


SQL Statements INTERNAL 1315
message_text

The text of the message to add. The maximum length is 255 bytes. PRINT and RAISERROR recognize
placeholders in the message text to print out. 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.

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.

There is no parameter corresponding to the <language> argument for sp_addmessage.

Privileges

Requires one of:

● CREATE MESSAGE system privilege


● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

Automatic commit

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – the functionality of CREATE MESSAGE is provided by the sp_addmessage
procedure in SAP Adaptive Server Enterprise.

SAP IQ SQL Reference


1316 INTERNAL SQL Statements
Related Information

PRINT Statement [T-SQL] [page 1593]


RAISERROR Statement [T-SQL] [page 1597]
REVOKE System Privilege Statement [page 1635]

9.4.54 CREATE MULTIPLEX SERVER Statement

Creates a multiplex server.

 Syntax

CREATE MULTIPLEX SERVER <server-name> DATABASE


'<path>/<db_file>' <host-port-list> [ ROLE { READER | WRITER } ]
[ STATUS | { INCLUDED | EXCLUDED } ]
[ { ENABLE | DISABLE } RLV STORE ]

<host-port-list> ::=
{[ PRIVATE ] HOST '<host_name>' PORT <port_number> }

Go to

● Remarks
● Privileges
● Examples

Parameters

(back to top)

server-name

The name of the multiplex secondary server based on the rules for server startup option -n. The name
must be unique across the local area network.
path

The path to the database file on the secondary node, entered as an absolute value. Store the database files
on the local disk of the coordinator or secondary node, not on a remote location. The path must exist
before executing the CREATE MULTIPLEX SERVER statement.
db_file

The name of the database being converted to a multiplex.


PRIVATE

Specifies that the particular HOST PORT pair is for private interconnection. A separate private
interconnection for multiplex interprocess communication (MIPC) enables highly available and high-
performance network configurations. SAP IQ automatically opens private ports; you need not list them in

SAP IQ SQL Reference


SQL Statements INTERNAL 1317
the host-port-list used to start the server. All public and private ports require unique port numbers to avoid
conflicts.
ROLE { READER | WRITER }

Writer role can run read-only and read-write operations against shared IQ objects. Reader Role can only run
read-only operations. Both can manipulate local data in temporary and SA base tables. The default, if not
specified, is READER.
HOST host_name

The IP address or machine name of the coordinator.


PORT port_number

The port number on which the secondary node runs.


{ ENABLE | DISABLE } RLV STORE

Allows the coordinator to use an in-memory store for high-performance row-level updates. Default if not
specified is DISABLED.
STATUS | { INCLUDED | EXCLUDED }

Adds or removes a secondary node as part of a multiplex. The default, if not specified, is INCLUDED. If a
multiplex secondary server will be shut down for an extended period of time, exclude that server from the
multiplex first. After including a server, the server must be synchronized and then started. See
Synchronizing Servers.

Remarks

(back to top)

Applies to multiplex only.

If you plan to use UNIX soft (symbolic) links for server paths, create the soft link before you run CREATE
MULTIPLEX SERVER. When you start the new server, the database file path must match the database file path
specified when creating that server.

When creating the initial multiplex server, both coordinator node and secondary node rows are added to
SYS.ISYSIQMPXSERVER. The transaction log records this operation as two separate CREATE MULTIPLEX
SERVER commands, one for the coordinator node and one for the secondary node.

After creating the first secondary node, the coordinator shuts down automatically.

The SYS.ISYSIQMPXSERVER system table stores the HOST '<hostname>' PORT <port number> pairs in
its connection_info string as host:port[;host:port…].

 Note

Use multiple host:port pairs if the computer the multiplex server is running on has multiple redundant
network cards mapped to different network addresses.

You may specify the clauses DATABASE, host-port list, ROLE and STATUS in any order.

When you add a server, the coordinator must be running, but you can run the CREATE MULTIPLEX SERVER
command from any server in the multiplex.

This statement is automatically committed.

SAP IQ SQL Reference


1318 INTERNAL SQL Statements
Privileges

(back to top)

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

(back to top)

In the following statement, the role of server host_c is converted to a coordinator and the secondary node
mpxnode_w1, running on 2957 is created with a writer role. The statement also defines the path (mympx_c1)
to where the secondary node will run, and where the synchronized copy of the database (mpxtest.db) will
reside on the secondary node.

CREATE MULTIPLEX SERVER mpxnode_w1


DATABASE '/mympx_c1/mpxtest.db' HOST 'host_c' PORT 2957 ROLE WRITER

Related Information

REVOKE System Privilege Statement [page 1635]


Synchronizing Multiplex Servers

9.4.55 CREATE MUTEX statement

Creates or replaces a mutex (lock) that can be used to lock a resource such as a file or a procedure.

 Syntax

CREATE [ OR REPLACE | TEMPORARY ] MUTEX [ IF NOT EXISTS ] [ <owner>.]<mutex-


name>
[ SCOPE { CONNECTION | TRANSACTION } ]

Parameters

owner

The owner of the mutex. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
mutex-name

SAP IQ SQL Reference


SQL Statements INTERNAL 1319
The name of the mutex. Specify a valid identifier in the CHAR database collation. <mutex-name> can also
be specified using an indirect identifier (for example, `[@<variable-name>]`).
OR REPLACE clause

Use this clause to overwrite (update) the definition of a permanent mutex of the same name, if one exists.

If the OR REPLACE clause is specified, and a mutex with this name is in use at the time, then the statement
returns an error.

You cannot use this clause with the TEMPORARY or IF NOT EXISTS clauses.
TEMPORARY clause

Use this clause to create a temporary mutex.

Do not use this clause with the OR REPLACE clause.


IF NOT EXISTS clause

Use this clause to create a mutex only if it doesn't already exist. If a mutex exists with the same name, then
nothing happens and no error is returned.

You cannot use this clause with the OR REPLACE clause.


SCOPE clause

Use this clause to specify whether the mutex applies to a transaction (TRANSACTION), or the connection
(CONNECTION). If the SCOPE clause is not specified, then the default behavior is CONNECTION.

Remarks

Permanent and temporary mutexes and semaphores share the same namespace; therefore, you cannot create
two of these objects with the same name and owner. Use of the OR REPLACE and IF NOT EXISTS clause can
inadvertently cause an error related to naming. For example, if you have a permanent mutex, and you try to
create a temporary semaphore with the same name, an error is returned even if you specify IF NOT EXISTS.
Similarly, if you have a temporary semaphore, and you try to replace it with a permanent semaphore with the
same name by specifying OR REPLACE, an error is returned because this is equivalent to attempting to create
a second object with the same name.

Permanent mutex definitions persist across database restarts. However, their state information (locked or
released), does not.

A temporary mutex persists until the connection that created it is terminated, or until the mutex is dropped
using a DROP MUTEX statement. If another connection is waiting for a temporary mutex and the connection
that created the temporary mutex is terminated, then an error is returned to the waiting connection indicating
that the mutex has been deleted.

CONNECTION scope mutexes are not automatically released other than when the connection is terminated.

Privileges

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

SAP IQ SQL Reference


1320 INTERNAL SQL Statements
Side effects

Automatic commit, but only for permanent mutexes.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement creates a connection scope mutex called protect_my_cr_section to protect a
critical section of a stored procedure.

CREATE MUTEX protect_my_cr_section SCOPE CONNECTION;

Related Information

DROP MUTEX statement [page 1449]


LOCK MUTEX statement [page 1570]
RELEASE MUTEX statement [page 1603]
DROP MUTEX statement [page 1449]
LOCK MUTEX statement [page 1570]
RELEASE MUTEX statement [page 1603]
REVOKE System Privilege Statement [page 1635]

9.4.56 CREATE PROCEDURE Statement

Creates a new user-defined SQL procedure in the database.

To create external procedure interfaces, see CREATE PROCEDURE Statement (External Procedures).

 Syntax

CREATE [ OR REPLACE | TEMPORARY ] PROCEDURE [ <owner>.]<procedure-name>


( [ <parameter>, …] ) {
[ SQL SECURITY { INVOKER | DEFINER } ]
[ RESULT ( <result-column>, …) | NO RESULT SET ]
[ ON EXCEPTION RESUME ] <compound statement> | AT <location-string>

<parameter> ::=
<parameter_mode> <parameter-name> <data-type> [ DEFAULT <expression> ]
| SQLCODE

SAP IQ SQL Reference


SQL Statements INTERNAL 1321
| SQLSTATE

<parameter_mode> ::= IN | OUT | INOUT

<result-column> ::= <column-name> <data-type>

Parameters

parameter-name

Parameter names must conform to the rules for other database identifiers, such as column names, and
must be a valid SQL data type. The keywords have the following meanings:

Parameters can be prefixed by one of the keywords IN, OUT or INOUT. If no keyword is specified,
parameters are INOUT by default. The keywords have the following meanings:

● IN – an expression that provides a value to the procedure.


● OUT – a variable that could be given a value by the procedure.
● INOUT – a variable that provides a value to the procedure, and could be given a new value by the
procedure.

Set the data type explicitly, or specify the %TYPE or %ROWTYPE attribute to set the data type to the data
type of another object in the database. Use %TYPE to set it to the data type of a column in a table or view.
Use %ROWTYPE to set the data type to a composite data type derived from a row in a table or view.
However, defining the data type using a %ROWTYPE that is set to a table reference variable (TABLE REF
(<table-reference-variable>) %ROWTYPE is not allowed.
SQLSTATE and SQLCODE

Special parameters that output the SQLSTATE or SQLCODE value when the procedure ends (they are OUT
parameters). Whether or not a SQLSTATE and SQLCODE parameter is specified, the SQLSTATE and
SQLCODE special values can always be checked immediately after a procedure call to test the return
status of the procedure.

The SQLSTATE and SQLCODE special values are modified by the next SQL statement. Providing SQLSTATE
or SQLCODE as procedure arguments allows the return code to be stored in a variable.
CREATE

Creates a new procedure.


OR REPLACE

Replaces an existing procedure with the same name. This clause changes the definition of the procedure,
but preserves existing permissions.

You cannot use the OR REPLACE clause with temporary procedures. Also, an error is returned if the
procedure being replaced is already in use.
TEMPORARY

The stored procedure is visible only by the connection that created it, and that it is automatically dropped
when the connection is dropped. You can also explicitly drop temporary stored procedures. 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.

SAP IQ SQL Reference


1322 INTERNAL SQL Statements
Temporary procedures execute with the permissions of their creator (current user), or specified owner. You
can specify an owner for a temporary procedure when:

● The temporary procedure is created within a permanent stored procedure


● The temporary and permanent procedure both have the same owner

To drop the owner of a temporary procedure, drop the temporary procedure first.

You can create and drop temporary stored procedures when you are connected to a read-only database;
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 1 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' )

RESULT

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. Allowed data types are
listed in SQL Data Types.

Some procedures can produce more than one result set, depending on how they are executed. For
example, this 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 these limitations:

● Embedded SQL – you must DESCRIBE the procedure call after the cursor for the result set is opened,
but before any rows are returned, in order to get the proper shape of result set. The CURSOR
<cursor-name> clause on the DESCRIBE statement is required.
● ODBC, OLE DB, ADO.NET – variable result-set procedures can be used by ODBC applications. 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, use a RESULT clause. The presence of this clause prevents
ODBC and Open Client applications from describing the result set again after a cursor is open.

SAP IQ SQL Reference


SQL Statements INTERNAL 1323
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

Declares that this procedure returns no result set. This is useful when an external environment needs to
know that a procedure does not return a result set.
SQL SECURITY

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.

Extra memory is used when you specify SQL SECURITY INVOKER, because annotation must be done for
each user that calls the procedure. Also, name resolution is performed as the invoker as well. Therefore,
qualify all object names (tables, procedures, and so on) with their appropriate owner. For example,
suppose user1 creates this 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

The procedure takes an action that depends on the setting of the ON_TSQL_ERROR option. If
ON_TSQL_ERROR option is set to CONDITIONAL (which is the default) the execution continues if the next
statement handles the error; otherwise, it exits.

Error-handling statements include:

● IF
● SELECT @variable
● CASE
● LOOP
● LEAVE
● CONTINUE
● CALL
● EXECUTE
● SIGNAL
● RESIGNAL
● DECLARE
● SET VARIABLE

Do not use explicit error-handling code with an ON EXCEPTION RESUME clause.

See ON_TSQL_ERROR Option [TSQL].

SAP IQ SQL Reference


1324 INTERNAL SQL Statements
AT location-string

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

Remarks

CREATE PROCEDURE creates a procedure in the database. A procedure is invoked with a CALL statement. You
can create permanent or temporary (TEMPORARY) stored procedures. You can use PROC as a synonym for
PROCEDURE.

 Note

There are two ways to create stored procedures: ISO/ANSI SQL and T-SQL. BEGIN TRANSACTION, for
example, is T-SQL-specific when using CREATE PROCEDURE syntax. Do not mix syntax when creating
stored procedures. See CREATE PROCEDURE Statement [T-SQL].

When procedures are executed using CALL, 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.

Remote procedures can return only up to 254 characters in output variables.

If a remote procedure can return a result set, even if it does not return one in all cases, then the local procedure
definition must contain a RESULT clause.

For information on remote servers, see CREATE SERVER Statement.

Privileges

The privilege required depends on the procedure type and ownership of the procedure. See GRANT System
Privilege Statement [page 1511] for assistance with granting privileges.

Procedure Type Ownership Privilege Required

Watcom SQL or Transact SQL proce­ Self Requires CREATE PROCEDURE system
dure privilege.

Owned by another user Requires one of:

● CREATE ANY PROCEDURE system


privilege
● CREATE ANY OBJECT system priv­
ilege

SAP IQ SQL Reference


SQL Statements INTERNAL 1325
Procedure Type Ownership Privilege Required

Remote procedure Self Requires all of:

● CREATE EXTERNAL REFERENCE


system privilege
● CREATE PROCEDURE system priv­
ilege

Owned by another user Requires CREATE EXTERNAL REFER­


ENCE system privilege. Also requires
one of:

● CREATE ANY PROCEDURE system


privilege
● CREATE ANY OBJECT system priv­
ilege

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – the Transact-SQL CREATE PROCEDURE statement is different.
● SQLJ – the syntax extensions for Java result sets are as specified in the proposed SQLJ1 standard.

Examples

● The following example 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 "GROUPO"."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'

SAP IQ SQL Reference


1326 INTERNAL SQL Statements
WHEN 'Shorts' THEN
SET type = 'Shorts'
ELSE
SET type = 'UNKNOWN'
END CASE ;
END

● The following example uses a cursor and loop 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

In this section:

Referencing Temporary Tables Within Procedures [page 1328]


Sharing a temporary table between procedures can cause problems if the table definitions are
inconsistent.

CREATE PROCEDURE Statement [T-SQL] [page 1329]


Creates a new procedure that is compatible with SAP Adaptive Server Enterprise.

CREATE PROCEDURE Statement [External Procedures] [page 1331]


Creates an interface to a native or external procedure.

CREATE PROCEDURE Statement [Java UDF] [page 1338]


Creates an interface to an external Java table UDF.

CREATE PROCEDURE Statement [Table UDF] [page 1340]


Creates an interface to an external Table User-Defined Function (Table UDF), a Table Parameterized
Function (TPF) or a Polymorphic Table Function (PTF).

CREATE PROCEDURE statement [Web service] [page 1343]


Creates a user-defined web client procedure that makes HTTP or SOAP requests to an HTTP server.

SAP IQ SQL Reference


SQL Statements INTERNAL 1327
Related Information

Referencing Temporary Tables Within Procedures [page 1328]


BEGIN … END Statement [page 1218]
CALL Statement [page 1225]
CREATE PROCEDURE Statement [External Procedures] [page 1331]
CREATE PROCEDURE Statement [T-SQL] [page 1329]
CREATE SERVER Statement [page 1363]
DROP Statement [page 1433]
EXECUTE IMMEDIATE Statement [ESQL] [SP] [page 1471]
GRANT EXECUTE Privilege Statement [page 1499]
ON_TSQL_ERROR Option [TSQL] [page 1946]
RAISERROR Statement [T-SQL] [page 1597]
REVOKE System Privilege Statement [page 1635]

9.4.56.1 Referencing Temporary Tables Within Procedures

Sharing a temporary table between procedures can cause problems if the table definitions are inconsistent.

For example, you have two procedures procA and procB, both of which define a temporary table,
temp_table, and call another procedure called sharedProc. Neither procA nor procB have been called yet,
so the temporary table does not yet exist.

Now, if both procA and procB used the same column names and types but their definitions for temp_table
differed slightly, the column order would differ.

When you call procA, it returns the expected result. However, when you call procB, it returns a different result.

This is because when procA was called, it created temp_table, and then called sharedProc. When
sharedProc was called, the SELECT statement inside of it was parsed and validated, and then a parsed
representation of the statement is cached so that it can be used again when another SELECT statement is
executed. The cached version reflects the column ordering from the table definition in procA.

Calling procB causes temp_table to be re-created, but with different column ordering. When procB calls
sharedProc, the database server uses the cached representation of the SELECT statement. So, the results
differ.

To avoid this from happening, doing one of the following:

● Ensure that temporary tables used in this way are defined consistently
● Consider using a global temporary table instead

SAP IQ SQL Reference


1328 INTERNAL SQL Statements
9.4.56.2 CREATE PROCEDURE Statement [T-SQL]

Creates a new procedure that is compatible with SAP Adaptive Server Enterprise.

This subset of the Transact-SQL CREATE PROCEDURE statement is supported in SAP IQ.

 Syntax

CREATE [ OR REPLACE ] PROCEDURE [ <owner>.]<procedure_name>


… [ [ ( ] <@parameter_name> <data-type> [ = <default> ] [ OUTPUT ] [ , … ]
[ ) ] ]
… [ WITH RECOMPILE ]
… AS
… <statement-list>

Go to:

● Remarks
● Privileges
● Side Effects
● Standards

Parameters

(back to top)

CREATE

Creates a new procedure.


OR REPLACE

Replaces an existing procedure with the same name. This clause changes the definition of the procedure,
but preserves existing permissions.

Remarks

(back to top)

Differences between Transact-SQL and SAP IQ SQL statements:

● Variable names prefixed by @ – the “@” sign denotes a Transact-SQL variable name; SAP IQ variables can
be any valid identifier and the @ prefix is optional.
● Input and output parameters – SAP IQ procedure parameters are specified as IN, OUT, or INOUT; Transact-
SQL procedure parameters are INPUT parameters by default or can be specified as OUTPUT. Those
parameters declared as INOUT or as OUT in SAP IQ should be declared with OUTPUT in Transact-SQL.
● Parameter default values – SAP IQ procedure parameters are given a default value using the keyword
DEFAULT; Transact-SQL uses an equality sign (=) to provide the default value.

SAP IQ SQL Reference


SQL Statements INTERNAL 1329
● Returning result sets – SAP IQ 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:

CREATE PROCEDURE showdept @deptname varchar(30)


AS
SELECT Employees.Surname, Employees.givenName
FROM Departments, Employees
WHERE Departments.DepartmentName = @deptname
AND Departments.DepartmentID =
Employees.DepartmentID

The corresponding SAP IQ procedure:

CREATE PROCEDURE showdept(in deptname


varchar(30) )
RESULT ( lastname char(20), firstname char(20))
ON EXCEPTION RESUME
BEGIN
SELECT Employees.SurName, Employees.GivenName
FROM Departments, Employees
WHERE Departments.DepartmentName = deptname
AND Departments.DepartmentID =
Employees.DepartmentID
END

● Procedure body – the body of a Transact-SQL procedure is a list of Transact-SQL statements prefixed by
the AS keyword. The body of an SAP IQ procedure is a compound statement, bracketed by BEGIN and END
keywords.

 Note

There are two ways to create stored procedures: T-SQL and SQL/92. BEGIN TRANSACTION, for
example, is T-SQL specific when using CREATE PROCEDURE syntax. Do not mix syntax when creating
stored procedures.

If the Transact-SQL WITH RECOMPILE optional clause is supplied, it is ignored. SAP SQL Anywhere always
recompiles procedures the first time they are executed after a database is started, and stores the compiled
procedure until the database is stopped.

Groups of procedures are not supported.

Privileges

(back to top)

Watcom SQL or Transact SQL procedure to be owned by self – requires CREATE PROCEDURE system privilege.

Watcom SQL or Transact SQL procedure to be owned by any user – requires one of:

● CREATE ANY PROCEDURE system privilege.


● CREATE ANY OBJECT system privilege.

Remote procedure to be owned by self – requires all of:

● CREATE EXTERNAL REFERENCE system privilege.


● CREATE PROCEDURE system privilege.

SAP IQ SQL Reference


1330 INTERNAL SQL Statements
Remote procedure to be owned by any user – requires CREATE EXTERNAL REFERENCE system privilege. Also
requires one of:

● CREATE ANY PROCEDURE system privilege.


● CREATE ANY OBJECT system privilege.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – SAP IQ supports a subset of the SAP ASE CREATE PROCEDURE statement
syntax.

Related Information

CREATE PROCEDURE Statement [page 1321]

9.4.56.3 CREATE PROCEDURE Statement [External


Procedures]

Creates an interface to a native or external procedure.

For CREATE PROCEDURE reference information for Java UDFs, see CREATE PROCEDURE Statement [Java
UDF]. For CREATE PROCEDURE reference information for table UDFs, see CREATE PROCEDURE Statement
[Table UDF]

 Syntax

CREATE[ OR REPLACE ] PROCEDURE [ <owner>.]<procedure-name> ( [ <parameter>,


…] )
[ SQL SECURITY { INVOKER | DEFINER } ]
[ RESULT ( <result-column>, …) | NO RESULT SET ]
[ DYNAMIC RESULT SETS <integer-expression> ]
[ EXTERNAL NAME '<native-call>'
| EXTERNAL NAME '<c-call>' LANGUAGE { C_ESQL32 | C_ESQL64 | C_ODBC32 |
C_ODBC64 }
| EXTERNAL NAME '<perl-call>' LANGUAGE PERL

SAP IQ SQL Reference


SQL Statements INTERNAL 1331
| 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

<result-column> ::= <column-name> <data-type>

<native-call> ::=
[<system-configuration>:]<function-name>@<library>

<system-configuration> ::=
{ <generic-operating-system> | <specific-operating-system> } [ (<processor-
architecture>) ]

<generic-operating-system> ::= { UNIX | Windows }

<specific-operating-system> ::=
{ AIX | HPUX | Linux | OSX | Solaris | WindowsNT }

<processor-architecture> ::=
{ 32 | 64 | ARM | IA64 | PPC | SPARC | X86 | X86_64 }

<c-call> ::=
[<system-configuration>:]<function-name>@<library>; ...

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

<method-signature> ::=
( [ <field-descriptor>, ... ] ) <return-descriptor>

<field-descriptor> and <return-descriptor> ::=


{ Z | B | S | I | J | F | D | C | V | [<descriptor> | L<class-name>; }

Parameters

CREATE

Creates a new procedure.

SAP IQ SQL Reference


1332 INTERNAL SQL Statements
OR REPLACE

Replaces an existing procedure with the same name. This clause changes the definition of the procedure,
but preserves existing permissions.
parameter

Parameter names must conform to the rules for other database identifiers, such as column names, and
must be a valid SQL data type. The keywords have the following meanings:

Parameters can be prefixed by one of the keywords IN, OUT or INOUT. If no keyword is specified,
parameters are INOUT by default. The keywords have the following meanings:

● IN – an expression that provides a value to the procedure.


● OUT – a variable that could be given a value by the procedure.
● INOUT – a variable that provides a value to the procedure, and could be given a new value by the
procedure.

 Note

TABLE parameters cannot be declared as INOUT or OUT. See CREATE PROCEDURE Statement (Table
UDF).

When procedures are executed using CALL, 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.

 Note

You cannot CALL a table UDF. Use the CREATE PROCEDURE statement.

RESULT

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. Allowed data types are
listed in SQL Data Types.

Embedded SQL (LANGUAGE C_ESQL32, LANGUAGE C_ESQL64) or ODBC (LANGUAGE C_ODBC32,


LANGUAGE C_ODBC64) external procedures can return 0 or 1 result sets.

Perl or PHP (LANGUAGE PERL, LANGUAGE PHP) external procedures cannot return result sets.
Procedures that call native functions loaded by the database server cannot return result sets.

CLR or Java (LANGUAGE CLR, LANGUAGE JAVA) external procedures can return 0, 1, or more result sets.
NO RESULT SET

Declares that this procedure returns no result set. This is useful when an external environment needs to
know that a procedure does not return a result set.
DYNAMIC RESULT SETS

Use this clause with LANGUAGE CLR and LANGUAGE JAVA calls. This clause is useful only if you specify
LANGUAGE. If you specify a RESULT clause, DYNAMIC RESULT SETS defaults to 1. If you do not specify a
RESULT clause, DYNAMIC RESULT SETS defaults to 0. 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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1333
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.

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

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.

Extra memory is used when you specify SQL SECURITY INVOKER, because annotation must be done for
each user that calls the procedure. Also, name resolution is performed as the invoker as well. Therefore,
qualify all object names (tables, procedures, and so on) with their appropriate owner. For example,
suppose user1 creates this 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

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.
This is a formal example:

CREATE PROCEDURE mystring( IN instr LONG VARCHAR )


EXTERNAL NAME
'mystring@mylib.dll;UNIX:mystring@mylib.so';

A simpler way to write the preceding EXTERNAL NAME clause, using platform-specific defaults:

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 executes as part of the server. In this case, if the function causes a fault, then the
database server terminates. 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 continues to run.
EXTERNAL NAME c-call LANGUAGE { C_ESQL32 | C_ESQL64 | C_ODBC32 | C_ODBC64 } :

SAP IQ SQL Reference


1334 INTERNAL SQL Statements
To call a compiled native C function in an external environment instead of within the database server, the
stored procedure or function is defined with the EXTERNAL NAME clause followed by the LANGUAGE
attribute specifying one of C_ESQL32, C_ESQL64, C_ODBC32, or C_ODBC64.

When the LANGUAGE attribute is specified, then the library containing the function is loaded by an
external process and the external function will execute as part of that external process. In this case, if the
function causes a fault, then the database server will continue to run.

The following is a sample procedure definition:

CREATE PROCEDURE ODBCinsert(


IN ProductName CHAR(30),
IN ProductDescription CHAR(50)
)
NO RESULT SET
EXTERNAL NAME 'ODBCexternalInsert@extodbc.dll'
LANGUAGE C_ODBC32;

EXTERNAL NAME perl-call LANGUAGE CLR

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 with the
exception 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).

Sample procedure definition:

CREATE PROCEDURE PerlWriteToConsole( IN str LONG VARCHAR)


NO RESULT SET
EXTERNAL NAME '<file=PerlConsoleExample>
WriteToServerConsole( $sa_perl_arg0 )'
LANGUAGE PERL;

EXTERNAL NAME perl-call LANGUAGE PHP

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 with the
exception 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).

Sample procedure definition:

CREATE PROCEDURE PHPPopulateTable()


NO RESULT SET
EXTERNAL NAME '<file=ServerSidePHPExample>
ServerSidePHPSub()'
LANGUAGE PHP;

EXTERNAL NAME java-call LANGUAGE JAVA

A Java method signature is a compact character representation of the types of the parameters and the
type of the return value.

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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1335
A Java-interfacing stored procedure or function behaves the same as a SQL stored procedure or function
with the exception 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 Virtual Machine).

Sample procedure definition:

CREATE PROCEDURE HelloDemo( IN


name LONG VARCHAR )
NO RESULT SET
EXTERNAL NAME 'Hello.main([Ljava/lang/String;)V'
LANGUAGE JAVA;

The descriptors for arguments and return values from Java methods have the following meanings:

● B – byte
● C – char
● D – double
● F – float
● I – int
● J – long
● L–
● L <class-name>; – an instance of the <class-name> class. The class name must be fully qualified,
and any dot in the name must be replaced by a backslash. For example, java/lang/String
● S – short
● V – void
● Z – Boolean
● [ – use one for each dimension of an array

For example, the following has the signature '(ZILjava/math/BigDecimal;[[B[Ljava/sql/


ResultSet;)D':

double some_method(
boolean a,
int b,
java.math.BigDecimal c,
byte [][] d,
java.sql.ResultSet[] d ) {
}

Remarks

The body of a procedure consists of a compound statement. For information on compound statements, see
BEGIN … END Statement.

 Note

There are two ways to create stored procedures: ISO/ANSI SQL and T-SQL. BEGIN TRANSACTION, for
example, is T-SQL specific when using CREATE PROCEDURE syntax. Do not mix syntax when creating
stored procedures. See CREATE PROCEDURE Statement [T-SQL].

If a stored procedure returns a result set, it cannot also set output parameters or return a return value.

SAP IQ SQL Reference


1336 INTERNAL SQL Statements
You cannot create TEMPORARY external call procedures.

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.

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.

Privileges

External procedure to be owned by self – Requires:

● CREATE EXTERNAL REFERENCE system privilege.


● CREATE PROCEDURE system privilege.

External procedure to be owned by any user – Requires CREATE EXTERNAL REFERENCE system privilege.
Also requires one of:

● CREATE ANY PROCEDURE system privilege.


● CREATE ANY OBJECT system privilege.

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – the Transact-SQL CREATE PROCEDURE statement is different.
● SQLJ – the syntax extensions for Java result sets are as specified in the proposed SQLJ1 standard.

Related Information

ALTER PROCEDURE Statement [page 1163]


BEGIN … END Statement [page 1218]
CALL Statement [page 1225]
CREATE PROCEDURE Statement [page 1321]
CREATE PROCEDURE Statement [T-SQL] [page 1329]
DROP Statement [page 1433]
EXECUTE IMMEDIATE Statement [ESQL] [SP] [page 1471]
GRANT EXECUTE Privilege Statement [page 1499]

SAP IQ SQL Reference


SQL Statements INTERNAL 1337
9.4.56.4 CREATE PROCEDURE Statement [Java UDF]

Creates an interface to an external Java table UDF.

 Syntax

Syntax 1 – Queries Referencing at Least One SAP IQ Table

CREATE[ OR REPLACE ] PROCEDURE


[ <owner>.]<procedure-name> ( [ <parameter>, …] )
[ RESULT (<result-column>, ...)]
[ SQL SECURITY { INVOKER | DEFINER } ]
EXTERNAL NAME '<java-call>' [ LANGUAGE <java> ] }

Syntax 2 – Queries Referencing Catalog Store Tables Only

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 '<java-call>' [ LANGUAGE <java> ] }

<parameter> ::=
[ IN <parameter_mode> <parameter-name> <data-type>
[ DEFAULT <expression> ]

<result-column> ::=
<column-name> <data-type>

<java-call> ::=
'[<package-name>.]<class-name>.<method-name> <method-signature>'

<java> ::=
[ ALLOW | DISALLOW SERVER SIDE REQUESTS ]

Go to:

● Remarks
● Privileges
● Standards

Parameters

(back to top)

java

DISALLOW is the default. ALLOW indicates that server-side connections are allowed.

SAP IQ SQL Reference


1338 INTERNAL SQL Statements
 Note

Do not specify ALLOW unless necessary. A setting of ALLOW slows down certain types of SAP IQ table
joins. If you change a procedure definition from ALLOW to DISALLOW, or vice-versa, the change will not
be recognized until you make a new connection.

Do not use UDFs with both ALLOW SERVER SIDE REQUESTS and DISALLOW SERVER SIDE REQUESTS
in the same query.

Remarks

(back to top)

If your query references SAP IQ tables, note that different syntax and parameters apply compared to a query
that references only catalog store tables.

Java table UDFs are only supported in the FROM clause.

For Java table functions, exactly one result set is allowed. If the Java table functions are joined with an SAP IQ
table or if a column from an SAP IQ table is an argument to the Java table function then only one result set is
supported.

If the Java table function is the only item in the FROM clause then N number of result sets are allowed.

For CREATE PROCEDURE reference information for external procedures, see CREATE PROCEDURE Statement
[External Procedures]. For CREATE PROCEDURE reference information for table UDFs, see CREATE
PROCEDURE Statement [Table UDF].

Privileges

(back to top)

Unless creating a temporary procedure, a user must have the CREATE PROCEDURE system privilege to create
a procedure for themselves. To create UDF procedure for others, a user must specify an owner and have either
the CREATE ANY PROCEDURES or CREATE ANY OBJECT system privilege. If a procedure has an external
reference, a user must also have the CREATE EXTERNAL REFERENCE system privilege, in addition to the
previously mentioned system privileges, regardless of whether or not they are the owner of procedure.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – the Transact-SQL CREATE PROCEDURE statement is different.
● SQLJ – the syntax extensions for Java result sets are as specified in the proposed SQLJ1 standard.

SAP IQ SQL Reference


SQL Statements INTERNAL 1339
9.4.56.5 CREATE PROCEDURE Statement [Table UDF]
Creates an interface to an external Table User-Defined Function (Table UDF), a Table Parameterized Function
(TPF) or a Polymorphic Table Function (PTF).

For CREATE PROCEDURE reference information for external procedures, see CREATE PROCEDURE Statement
[External Procedures]. For CREATE PROCEDURE reference information for Java UDFs, see CREATE PROCEDURE
Statement [Java UDF].

 Syntax

CREATE[ OR REPLACE ] PROCEDURE


[ <owner>.]<procedure-name> ( [ <parameter>[, …]] )
| RESULT <result-type> [, …] )
[ SQL SECURITY { INVOKER | DEFINER } ]
EXTERNAL NAME '<external-call>'

<parameter> ::=
[ IN ] <parameter-name> <data-type> [ DEFAULT <expression> ]
| [ IN ] <parameter-name> <table-type>

<table-type> ::=
TABLE | TABLE ( <column-name> <data-type> [, …] )

<result-type> ::=
<table-name> TABLE | <result-col-type> [, …]

<result-col-type> ::=
<column-name> <data type>

<external-call> ::=
[<column-name>:]<function-name@library>; …

Go to:

● Remarks
● Privileges
● Standards

Parameters

(back to top)

IN

The parameter is an object that provides a value for a scalar parameter or a set of values for a TABLE
parameter to the UDF.

 Note

TABLE parameters cannot be declared as INOUT or OUT. You can only have one TABLE parameter (the
position of which is not important).

SAP IQ SQL Reference


1340 INTERNAL SQL Statements
OR REPLACE

Specifying OR REPLACE (CREATE OR REPLACE PROCEDURE) creates a new procedure, or replaces an


existing procedure with the same name. This clause changes the definition of the procedure, but preserves
existing permissions. An error is returned if you attempt to replace a procedure that is already in use.
RESULT

Declares the column names and their data types for the result set of the external UDF. If the UDF is not
polymorphic, the data types of the columns must be a valid SQL data type. If the result table in a UDF is
polymorphic, it is declared as "RESULT ( TABLE). The set of datums in the result implies the TABLE.
External UDFs can only have one result set of type TABLE.

 Note

A table UDF cannot have LONG VARBINARY or LONG VARCHAR data types in its result set, but a table
parameterized function (TPF) can have large object (LOB) data in its result set.

A TPF cannot produce LOB data, but can have columns in the result set as LOB data types. However,
the only way to get LOB data in the output is to pass a column from an input table to the output table.
The describe attribute EXTFNAPIV4_DESCRIBE_COL_VALUES_SUBSET_OF_INPUT allows this, as
illustrated in the sample file tpf_blob.cxx.

SQL SECURITY

Defines whether the procedure is executed as the INVOKER (the user who is calling the UDF), or as the
DEFINER (the user who owns the UDF). 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. 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 this 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

An external UDF must have EXTERNAL NAME clause, which defines an interface to a function written in a
programming language such as C. The 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.
This is a formal example:

CREATE PROCEDURE mystring( IN instr CHAR(255),


IN input_table TABLE(A INT) )
RESULT (CHAR(255))
EXTERNAL NAME
'mystring@mylib.dll;UNIX:mystring@mylib.so'

SAP IQ SQL Reference


SQL Statements INTERNAL 1341
A simpler way to write the preceding EXTERNAL NAME clause, using platform-specific defaults, is as
follows:

CREATE PROCEDURE mystring( IN instr CHAR(255),


IN input_table TABLE(A INT) )
RESULT (CHAR(255))
EXTERNAL NAME 'mystring@mylib'

Remarks

(back to top)

You define table UDFs using the a_v4_extfn API. CREATE PROCEDURE statement reference information for
external procedures that do not use the a_v3_extfn or a_v4_extfn APIs is located in a separate topic.
CREATE PROCEDURE statement reference information for Java UDFs is located in a separate topic.

The CREATE PROCEDURE statement creates a procedure in the database. To create a procedure for
themselves, a user must have the CREATE PROCEDURE system privilege. To create a procedure for others, a
user must specify the owner of the procedure and must have either the CREATE ANY PROCEDURE or CREATE
ANY OBJECT system privilege. If the procedure contains an external reference, the user must have the CREATE
EXTERNAL REFERENCE system privilege in addition to previously mentioned system privileges, regardless of
who owns the procedure.

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. Use caution when
referencing temporary tables within procedures.

You can use the CREATE PROCEDURE statement to create external table UDFs implemented in a different
programming language than SQL. However, be aware of the table UDF restrictions before creating external
UDFs.

The data type for a scalar parameter, a result column, and a column of a TABLE parameter must be a valid SQL
data type.

Parameter names must conform to the rules for other database identifiers such as column names. They must
be a valid SQL data type.

TPFs support a mix scalar parameters and one or more TABLE parameters. Unless the UDF is polymorphic, a
TABLE parameter must define a schema for an input set of rows to be processed by the UDF. The definition of a
TABLE parameter includes column names and column data types.

The following example defines a schema with the two columns c1 and c2 of types INT and CHAR(20). Each row
processed by the UDF must be a tuple with two (2) values. TABLE parameters, unlike scalar parameters cannot
be assigned a default value:

TABLE(c1 INT, c2 CHAR(20))

SAP IQ SQL Reference


1342 INTERNAL SQL Statements
Privileges

(back to top)

Unless creating a temporary procedure, a user must have the CREATE PROCEDURE system privilege to create
a UDF for themselves. To create a UDF for others, they must specify the owner of the procedure and must have
either the CREATE ANY PROCEDURE or CREATE ANY OBJECT system privilege. If the procedure contains an
external reference, a user must also have the CREATE EXTERNAL REFERENCE system privilege, in addition to
the previously mentioned system privileges.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – the Transact-SQL CREATE PROCEDURE statement is different.
● SQLJ – the syntax extensions for Java result sets are as specified in the proposed SQLJ1 standard.

9.4.56.6 CREATE PROCEDURE statement [Web service]

Creates a user-defined web client procedure that makes HTTP or SOAP requests to an HTTP server.

 Syntax

CREATE [ OR REPLACE ] PROCEDURE [ <owner>.]<procedure-name>


( [ <parameter>, ... ] )
[ RESULT ( <attribute-column-name> <datatype>, <value-column-name>
<datatype> ) ]
URL <url-string>
[ TYPE { <http-type-spec-string> | <soap-type-spec-string> } ]
[ HEADER <header-string> ]
[ CERTIFICATE <certificate-string> ]
[ CLIENTPORT <clientport-string> ]
[ PROXY <proxy-string> ]
[ SET <protocol-option-string> ]
[ SOAPHEADER <soap-header-string> ]
[ NAMESPACE <namespace-string> ]

<http-type-spec-string> :
HTTP[: { GET
| POST[:<MIME-type> ]
| PUT[:<MIME-type> ]
| DELETE
| HEAD
| OPTIONS } ]

<soap-type-spec-string> :
SOAP[:{ RPC | DOC }

<parameter> :

SAP IQ SQL Reference


SQL Statements INTERNAL 1343
<parameter-mode> <parameter-name> <datatype> [ DEFAULT <expression> ]

<parameter-mode> :
IN
| OUT
| INOUT

<url-string> :
{ HTTP | HTTPS | HTTPS_FIPS }://[<user>:<password>@]<hostname>[:<port>][/<path>]

<protocol-option-string> : <option-list> [, <option-list> ...]

<option-list> :
HTTP( <http-option> [ ;<http-option> ...] )
| SOAP( <soap-option> [ ;<soap-option> ...] )
| REDIR( <redir-option> [ ;<redir-option> ...] )

<http-option> :
CHUNK={ ON | OFF | AUTO }
| EXCEPTIONS={ ON | OFF | AUTO }
| VERSION={ 1.0 | 1.1 }
| KTIMEOUT=<number-of-seconds>

<soap-option> :
OPERATION=<soap-operation-name>

<redir-option> :
COUNT=<count>
| STATUS=<status-list>

Parameters

OR REPLACE clause

Specifying CREATE OR REPLACE PROCEDURE creates a new procedure, or replaces an existing procedure
with the same name. This clause changes the definition of the procedure, but preserves existing privileges.
An error is returned if you attempt to replace a procedure that is already in use.
procedure-name

The name of the procedure.


parameter-name

Parameter names must conform to the rules for other database identifiers such as column names. They
must have a valid SQL data type.

If a parameter has a default value, it need not be specified. Parameters with no default value must be
specified.

Parameters can be prefixed with one of the keywords IN, OUT, or INOUT. OUT and INOUT parameters are
only supported for SOAP procedures. If you do not specify one of these values, parameters are INOUT by
default. The keywords have the following meanings:

IN

SAP IQ SQL Reference


1344 INTERNAL SQL Statements
The parameter is an expression that provides a value to the procedure.
OUT

The parameter is a variable that could be given a value by the procedure.


INOUT

The parameter is a variable that provides a value to the procedure, and could be given a new value by
the procedure.
datatype

The data type of the parameter. Set the data type explicitly, or specify the %TYPE or %ROWTYPE attribute
to set the data type to the data type of another object in the database. Use %TYPE to set it to the data type
of a column in a table or view. Use %ROWTYPE to set the data type to a composite data type derived from
a row in a table or view. However, defining the data type using a %ROWTYPE that is set to a table reference
variable (TABLE REF (<table-reference-variable>) %ROWTYPE is not allowed.

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.
RESULT clause

The RESULT clause is required 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

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.

To use a certificate from the operating system certificate store, specify a URL beginning with https://.
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:POST and HTTP:PUT types. When
HTTP:PUT is used, then a MIME-type must be specified.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-

SAP IQ SQL Reference


SQL Statements INTERNAL 1345
length of zero. When a MIME-type is specified then the single body parameter is sent in the request as is,
so the application must ensure that the content is formatted to match the MIME-type.

Some typical MIME-types include:

● text/plain
● text/html
● text/xml

When no MIME-type is specified, parameter names and values (multiple parameters are permitted) are
URL encoded within the body of the HTTP request.

The keywords for the TYPE clause have the following meanings:

HTTP:GET

By default, this type uses the application/x-www-form-urlencoded MIME-type for encoding


parameters specified in the URL.

For example, the following request is produced when a client submits a request from the URL http://
localhost/WebServiceName?arg1=param1&arg2=param2:

GET /WebServiceName?arg1=param1&arg2=param2 HTTP/1.1


// <End of Request - NO BODY>

HTTP:POST

By default, this type uses the application/x-www-form-urlencoded MIME-type for encoding


parameters specified in the body of a POST request. URL parameters are stored in the body of the
request.

For example, the following request is produced when a client submits a request 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 database server running the %IQDIRSAMP%\SQLAnywhere\HTTP\put_data.sql sample:

CREATE OR REPLACE PROCEDURE CPUT([data] LONG VARCHAR, resnm LONG VARCHAR,


mediatype LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:PUT:!mediatype';
CALL CPUT('hello world', 'hello', 'text/plain' );

HTTP:DELETE

A web service client procedure can be configured to delete a resource located on a server. Specifying
the media type is optional.

SAP IQ SQL Reference


1346 INTERNAL SQL Statements
The following example demonstrates how to configure a general purpose client procedure that deletes
a resource from a database server running the put_data.sql sample:

CREATE OR REPLACE PROCEDURE CDEL(resnm LONG VARCHAR)


URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:DELETE';
CALL CDEL('hello', 'text/plain' );

HTTP:HEAD

The HEAD method is identical to a GET method but the server does not return a body. A media type
can be specified.

CREATE OR REPLACE PROCEDURE CHEAD(resnm LONG VARCHAR)


URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:HEAD';
CALL CHEAD( 'hello' );

HTTP:OPTIONS

The OPTIONS method is identical to a GET method but the server does not return a body. A media
type can be specified. This method allows Cross-Origin Resource Sharing (CORS).
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

SAP IQ SQL Reference


SQL Statements INTERNAL 1347
To make a secure (HTTPS) request, a client must have access to the root certificate of the HTTP server's
certificate chain. The necessary information is specified in a string of semicolon-separated keyword=value
pairs. The following keywords are available:

Keyword Abbreviation Description

file The file name of the certificate or


specify * to use a certificate from the
operating system certificate store.
Cannot be specified if either the certif­
icate or certificate_name keyword is
specified.

certificate cert The certificate itself. Cannot be speci­


fied if either the file or certifi-
cate_name keyword is specified.

certificate_name cert_name The name of a certificate stored in the


database. Cannot be specified if ei­
ther the file or certificate keyword is
specified.

company co The company specified in the certifi-


cate.

unit The company unit specified in the cer­


tificate.

name The common name specified in the


certificate.

skip_certificate_name_check Controls whether the client library


skips the check of the server host
name against the database server cer­
tificate host names.

allow_expired_certs Controls whether the client libraries


accept a root certificate and database
server certificate that have either ex­
pired or are not yet valid.

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. The
<proxy-string> is usually an HTTP or HTTPS url-string. This is site specific information that you usually
need to obtain from your network administrator. This clause indicates that the procedure is to connect to

SAP IQ SQL Reference


1348 INTERNAL SQL Statements
the proxy server and send the request to the web service through it. For an example, the following PROXY
clause sets the proxy server to proxy.example.com:

PROXY http://proxy.example.com

SET clause

Specifies protocol-specific behavior options for HTTP, SOAP, and REDIR (redirects). Only one SET clause is
permitted. The following list describes the supported SET options. CHUNK, EXCEPTIONS, VERSION, and
KTIMEOUT apply to the HTTP protocol, OPERATION applies to the SOAP protocol, and COUNT and
STATUS apply to the REDIR option. REDIR options can be included with either HTTP or SOAP protocol
options.

CHUNK={ ON | OFF | AUTO }

(short form CH) This HTTP 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.
EXCEPTIONS={ ON | OFF | AUTO }

(short form EX) This HTTP option allows you to control status code handling. The default is ON.

When set to ON or AUTO, HTTP client procedures will return a result set for HTTP success status
codes (1XX and 2XX) and all codes will raise the exception SQLE_HTTP_REQUEST_FAILED.

SET 'HTTP(EXCEPTIONS=AUTO)'

When set to OFF, HTTP client procedures will always return a result set, independent of the HTTP
status code. The result row with the word Status in the attribute column contains the HTTP status
code in the value column.

Exceptions that are not related to the HTTP status code (for example,
SQLE_UNABLE_TO_CONNECT_TO_HOST) will be raised when appropriate regardless of the
EXCEPTIONS setting.
VERSION={ 1.0 | 1.1 }

(short form VER) This HTTP option allows you to specify the version of the 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)'

SAP IQ SQL Reference


SQL Statements INTERNAL 1349
Possible values are 1.0 and 1.1. If VERSION is not specified:

● if CHUNK is set to ON, 1.1 is used as the HTTP version


● if CHUNK is set to OFF, 1.0 is used as the HTTP version
● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode
KTIMEOUT=number-of-seconds

(short form KTO) This HTTP option allows you to specify the keep-alive timeout criteria, permitting a
web client procedure to instantiate and cache a keep-alive HTTP/HTTPS connection for a period of
time. To cache an HTTP keep-alive connection, the HTTP version must be set to 1.1 and KTIMEOUT set
to a non-zero value. KTIMEOUT may be useful for HTTPS connections particularly, if you notice a
significant performance difference between HTTP and HTTPS connections. A database connection
can only cache a single keep-alive HTTP connection. Subsequent calls to a web client procedure using
the same URI reuse the keep-alive connection. Therefore, the executing web client call must have a URI
whose scheme, destination host and port match that of the cached URI, and the HEADER clause must
not specify Connection: close. When KTIMEOUT is not specified, or is set to zero, HTTP/HTTPS
connections are not cached.
OPERATION=soap-operation-name

(short form OP) This SOAP option allows you to specify the name of the SOAP operation, if it is
different from the name of the procedure you are creating. The value of OPERATION is analogous to
the name of a remote procedure call. For example, if you wanted to create a procedure called
accounts_login that calls a SOAP operation called login, you would specify something like the
following:

CREATE PROCEDURE accounts_login( name LONG VARCHAR, pwd LONG VARCHAR )


SET 'SOAP(OPERATION=login)'

If the OPERATION option is not specified, the name of the SOAP operation must match the name of
the procedure you are creating.
COUNT=count

(short form CNT) This REDIR option allows you to control redirects. See STATUS below.
STATUS=status-list

(short form STAT) This REDIR option allows you to control redirects. HTTP response status codes such
as302 Found and 303 See Other are used to redirect web applications to a new URI, particularly after
an HTTP POST has been performed. For example, a client request could be:

GET /people/alice HTTP/1.1


Host: www.example.com
Accept: text/html, application/xhtml+xml
Accept-Language: en, de

The web server response could be:

HTTP/1.1 302 Found


Location: http://www.example.com/people/alice.en.html

In response, the client would send another HTTP request to the new URI. The REDIR options allow you
to control the maximum number of redirections allowed and which HTTP response status codes to
automatically redirect.

SAP IQ SQL Reference


1350 INTERNAL SQL Statements
For example, SET 'REDIR(COUNT=3; STATUS=301,307)' allows a maximum limit of 3 re-directions
and permits redirection for 301 and 307 statuses. If one of the other redirection status codes such as
302 or 303 is received, an error is issued (SQLE_HTTP_REQUEST_FAILED).

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 (SQLE_HTTP_REQUEST_FAILED). 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
will handle 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 will include these parameters.

Location: alternate_service?a=1&b=2

In the above example, the query parameters are a=1&b=2.

The following example shows how several 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 ), REDIR(COUNT=5;STATUS=302,303)'
...

The following example shows the use of short forms with uppercase and lowercase letters.

CREATE PROCEDURE accounts_login( name LONG VARCHAR, pwd LONG VARCHAR )


SET 'HTTP( CH=ON; Ver=1.1 ), REDIR(CNT=5;Stat=302,303)'
...

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

SAP IQ SQL Reference


SQL Statements INTERNAL 1351
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.

You can specify a variable name for <namespace-string>. If the variable is NULL, the namespace
property is ignored.

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.

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.

You cannot create TEMPORARY web services procedures.

For required parameters that accept variable names, an error is returned if one of the following conditions is
true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

You must have the CREATE PROCEDURE system privilege to create procedures owned by you.

You must have the CREATE ANY PROCEDURE or CREATE ANY OBJECT system privilege to create procedures
owned by others.

To replace an existing procedure, you must own the procedure or have one of the following:

● CREATE ANY PROCEDURE and DROP ANY PROCEDURE system privileges.


● CREATE ANY OBJECT and DROP ANY OBJECT system privileges.
● ALTER ANY OBJECT or ALTER ANY PROCEDURE system privileges.

Side effects

Automatic commit.

SAP IQ SQL Reference


1352 INTERNAL SQL Statements
Standards

ANSI/ISO SQL Standard

Not in the standard.


Transact-SQL

Not supported by Adaptive Server Enterprise.

 Example

1. The following example creates a web service client procedure named FtoC.

CREATE PROCEDURE FtoC( IN temperature FLOAT,


INOUT inoutheader LONG VARCHAR,
IN inheader LONG VARCHAR )
URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'
SOAPHEADER '!inoutheader!inheader';

2. The following example creates a secure web service client procedure named
SecureSendWithMimeType that uses a certificate stored in the database.

CREATE CERTIFICATE client_cert


FROM FILE 'C:\\Users\\Public\\Documents\\SQL Anywhere
17\\Samples\\Certificates\\rsaroot.crt';
CREATE PROCEDURE SecureSendWithMimeType(
value LONG VARCHAR,
mimeType LONG VARCHAR,
urlSpec LONG VARCHAR
)
URL '!urlSpec'
CERTIFICATE 'certificate_name=client_cert'
TYPE 'HTTPS:POST:!mimeType';
CALL SecureSendWithMimeType('<hello>this is xml</hello>',
'text/xml',
'https://localhost:4043/EchoService'
);

3. The following example creates a procedure named SecureSendWithMimeType that uses a certificate
from the operating system certificate store:

CREATE PROCEDURE SecureSendWithMimeType(


value LONG VARCHAR,
mimeType LONG VARCHAR,
urlSpec LONG VARCHAR
)
URL '!urlSpec'
CERTIFICATE 'file=*'
TYPE 'HTTPS:POST:!mimeType';

4. The following example creates a procedure named SecureSendWithMimeType that verifies that the
certificate myrootcert.crt is at the root of the database server's certificate's signing chain, but does no
other checking:

CREATE PROCEDURE SecureSendWithMimeType(


value LONG VARCHAR,
mimeType LONG VARCHAR,
urlSpec LONG VARCHAR
)
URL '!urlSpec'
CERTIFICATE 'file=myrootcert.crt;skip_certificate_name_check=ON'
TYPE 'HTTPS:POST:!mimeType';

SAP IQ SQL Reference


SQL Statements INTERNAL 1353
5. The following example creates a procedure using a variable in the NAMESPACE clause
1. The following statements create a variable for a NAMESPACE clause:

CREATE VARIABLE @ns LONG VARCHAR


SET @ns = 'http://wsdl.domain.com/';

2. The following statement creates a procedure named FtoC that uses a variable in the NAMESPACE
clause:

CREATE PROCEDURE FtoC( IN temperature FLOAT,


INOUT inoutheader LONG VARCHAR,
IN inheader LONG VARCHAR )
URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'
SOAPHEADER '!inoutheader!inheader'
NAMESPACE @ns;

6. The following statement causes a POST request to the URL 'http://localhost/post_data' with the body
of the request equal to the json array '[0,1,2]' and the Content-Type of the request set to 'application/
json'.

CREATE OR REPLACE PROCEDURE CPOST ( [data] LONG VARCHAR, [url] LONG


VARCHAR, mediatype LONG VARCHAR )
URL '!url'
TYPE 'HTTP:POST:!mediatype';
CALL CPOST( '[0,1,2]', 'http://localhost/post_data', 'application/json' );

9.4.57 CREATE ROLE Statement

Creates a new role, extends an existing user to act as a role, or manages role administrators on a role.

 Syntax

CREATE [ OR REPLACE ] ROLE { <role_name> | FOR USER <user_id> }


[ WITH ADMIN [ ONLY ] <admin_name> [...] , [ SYS_MANAGE_ROLES_ROLE ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

role_name

Unless you are using the OR REPLACE clause, <role_name> cannot already exist in the database.

SAP IQ SQL Reference


1354 INTERNAL SQL Statements
OR REPLACE

<role_name> must already exist in the database. If <role_name> does not already exist, a new user-
defined role is created. All current administrators are replaced by those specified in the <admin_name
[..]> clause as follows:

● All existing role administrators granted the WITH ADMIN OPTION not included on the new role
administrators list become members of the role with no administrative rights on the role.
● All existing role administrators granted the WITH ADMIN ONLY OPTION not included on the new role
administrators list are removed as members of the role.

When using the OR REPLACE clause, if an existing role administrator is included on the new role
administrators list he or she retains his or her original administrative rights if they are higher than the
replacement rights. For example, User A is an existing role administrator originally granted WITH ADMIN
rights on the role. New role administrators are granted WITH ADMIN ONLY rights. If User A is included on
this list, User A retains the higher WITH ADMIN rights.
FOR USER user_id

When using the FOR USER clause without the OR REPLACE, <user_id> must be the name of an existing
user that currently does not have the ability to act as a role.
admin_name

List of users to be designated administrators of the role.

WITH ADMIN

Each <admin_name> specified is granted administrative privileges over the role in addition to all
underlying system privileges. WITH ADMIN clause is not valid when SYS_MANAGE_ROLES_ROLE is
included on the list.
WITH ADMIN ONLY

Each <admin_name> specified is granted administrative privileges only over the role, not the underlying
system privileges.
SYS_MANAGE_ROLES_ROLE

Allows global role administrators to administer the role. Can be specified in conjunction with the WITH
ADMIN ONLY clause.

Remarks

(back to top)

If you specify role administrators (<admin_name>), but do not include the global role administrator
(SYS_MANAGE_ROLES_ROLE), global role administrators will be unable to manage the new role. For this
reason, do not specify role administrators during the creation process, but instead use the OR REPLACE clause
to add them afterwards.

If you do not specify an ADMIN clause, the default WITH ADMIN ONLY clause is used and the default
administrator is the global roles administrator (SYS_MANAGE_ROLES_ROLE).

When replacing role administrators, if the role has a global role administrator, it must be included on the new
role administrators list or it is removed from the role.

SAP IQ SQL Reference


SQL Statements INTERNAL 1355
However, when using the WITH ADMIN clause to grant role administrators, since the clause is not valid for
global role administrators, you must use the GRANT ROLE statement to re-add the global role administrator
(SYS_MANAGE_RILES_ROLE) to the role. Failure to perform this grant means global role administrators are
unable to manage the role.

Privileges

(back to top)

Create a new role requires the MANAGE ROLES system privilege.

To use the OR REPLACE clause requires the MANAGE ROLES system privilege along with administrative rights
over the role being replaced.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

ANSI SQL – compliance level: Transact-SQL extension

Examples

(back to top)

● The following example creates the role Sales. Only global role administrator can administer the role.

CREATE ROLE Sales

● The following example extends the existing user Jane to act as a role.

CREATE OR REPLACE ROLE FOR USER Jane

● The following example creates the role Finance with Mary and Jeff as role administrators with
administrative rights to the role. Global role administrators cannot administer this role.

CREATE ROLE Finance WITH ADMIN Mary, Jeff

● The following example creates the role Marketing with Mary and Jeff as role administrators. Global role
administrators can also manage this role.

CREATE ROLE Finance


WITH ADMIN ONLY Mary, Jeff, SYS_MANAGE_ROLES_ROLE

● In the following example, Finance is an existing role with Harry and Susan as role administrators with
administrative rights. You want to keep Susan as an administrator, replace Harry, and add the global role
administrator. The new role administrators will have administrative rights only. This statement keeps

SAP IQ SQL Reference


1356 INTERNAL SQL Statements
Susan as an administrator, but Susan retains administrative rights to the role since the original
administrative rights granted were higher. Harry is replaced by Bob and Sarah, with administrative rights
only, and the global role administrator is added to the role. Harry remains a member of the role, but has no
administrative rights.

CREATE OR REPLACE ROLE Finance


WITH ADMIN ONLY Susan, Bob, Sarah, SYS_MANAGE_ROLE_ROLE

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.58 CREATE SCHEMA Statement

Creates a schema, which is a collection of tables, views, and permissions and their associated permissions, for
a database user.

 Syntax

CREATE SCHEMA AUTHORIZATION <userid>


... [ { <create-table-statement>
| <create-view-statement>
| <grant-statement> } ] …

Remarks

The <userid> must be the user ID of the current connection. You cannot create a schema for another user.
The user ID is not case-sensitive.

If any of the statements in the CREATE SCHEMA statement fail, the entire CREATE SCHEMA statement is rolled
back.

CREATE SCHEMA statement is simply a way to collect 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, use a REVOKE statement for each
permission granted.

 Note

The CREATE SCHEMA statement is invalid on an active multiplex.

Individual CREATE or GRANT statements are not separated by statement delimiters. The statement delimiter
marks the end of the CREATE SCHEMA statement itself.

SAP IQ SQL Reference


SQL Statements INTERNAL 1357
The individual CREATE or GRANT statements must be ordered such that the objects are created before
permissions are granted on them.

Creating more than one schema for a user is not recommended and might not be supported in future releases.

Privileges

Requires the CREATE ANY OBJECT system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – SAP IQ does not support the use of REVOKE statements within the CREATE
SCHEMA statement, and does not allow its use within Transact-SQL batches or procedures.

Related Information

CREATE TABLE Statement [page 1377]


CREATE VIEW Statement [page 1408]
GRANT CREATE Privilege Statement [page 1498]
REVOKE System Privilege Statement [page 1635]

9.4.59 CREATE SEMAPHORE statement

Creates or replaces a semaphore and establishes the initial value for its counter. A semaphore is a locking
mechanism that uses a counter to communicate and control the availability of a resource such as an external
library or procedure.

 Syntax

CREATE [ OR REPLACE | TEMPORARY ] SEMAPHORE [ IF NOT EXISTS ]


[ <owner>.]<semaphore-name>
[ START WITH <initial-count> ]

SAP IQ SQL Reference


1358 INTERNAL SQL Statements
Parameters

owner

The owner of the semaphore. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
semaphore-name

The name of the semaphore. Specify a valid identifier in the CHAR database collation. <semaphore-
name> can also be specified using an indirect identifier (for example, `[@<variable-name>]`).
OR REPLACE clause

Use this clause to overwrite (update) the definition of a permanent semaphore of the same name, if one
exists.

If the OR REPLACE clause is specified, and a semaphore with this name is in use at the time, then the
statement returns an error.

You cannot use this clause with the TEMPORARY or IF NOT EXISTS clauses.
TEMPORARY clause

Use this clause to create a temporary semaphore.

Do not use this clause with the OR REPLACE clause.


IF NOT EXISTS clause

Use this clause to create a semaphore only if it doesn't already exist. If a semaphore exists with the same
name and same lifespan (permanent or temporary), then nothing happens and no error is returned.

You cannot use this clause with the OR REPLACE clause.


START WITH clause

Use this clause to specify the initial value for the semaphore counter. If this clause is not specified, then
<initial-count> is set to 0.

<initial-count> can be specified using a variable (for example, START WITH @initial-count).

If you set <initial-count> to NULL, or if it is set to a variable and the variable value is NULL, the
behavior is equivalent to not specifying the clause.

Remarks

The CREATE SEMAPHORE statement creates a semaphore and establishes a counter for it. Each time a
NOTIFY SEMAPHORE statement is executed, the counter for the associated semaphore is incremented. Each
time a WAITFOR SEMAPHORE statement is executed, and assuming the current count is a positive integer, the
counter for the associated semaphore is decremented.

Permanent and temporary mutexes and semaphores share the same namespace, therefore you cannot create
two of these objects with the same name. Use of the OR REPLACE and IF NOT EXISTS clause can inadvertently

SAP IQ SQL Reference


SQL Statements INTERNAL 1359
cause an error related to naming. For example, if you have a permanent mutex, and you try to create a
temporary semaphore with the same name, an error is returned even if you specify IF NOT EXISTS. Similarly, if
you have a temporary semaphore, and you try to replace it with a permanent semaphore with the same name
by specifying OR REPLACE, an error is returned because this is equivalent to attempting to create a second
object with the same name.

Permanent semaphore definitions persist across database restarts. However, their count returns to
<initial-count> after a restart.

A temporary semaphore persists until the connection that created it is terminated, or until an explicit DROP
operation is performed. If another connection is waiting for a temporary semaphore and the connection that
created the temporary semaphore is terminated, then an error is returned to the waiting connection.

When replacing (OR REPLACE clause) a permanent semaphore, the old semaphore is deleted, and all
connections waiting for the semaphore are notified.

If the OR REPLACE clause is specified, and a permanent semaphore with that name exists and connections are
blocked waiting for the semaphore, the semaphore is still replaced. In this case, the waiting connections are
unblocked and an error is returned to them indicating that the semaphore has been dropped. There is one
exception however. If the replacement semaphore definition has identical settings, there is no impact to waiting
connections.

Privileges

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

Automatic commit, but only for permanent semaphores.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement creates a semaphore called license_counter and sets its counter to 3:

CREATE SEMAPHORE license_counter START WITH 3;

SAP IQ SQL Reference


1360 INTERNAL SQL Statements
Related Information

DROP SEMAPHORE statement [page 1452]


NOTIFY SEMAPHORE statement [page 1580]
WAITFOR SEMAPHORE statement [page 1715]
DROP SEMAPHORE statement [page 1452]
NOTIFY SEMAPHORE statement [page 1580]
WAITFOR SEMAPHORE statement [page 1715]
REVOKE System Privilege Statement [page 1635]

9.4.60 CREATE SEQUENCE statement

Creates a sequence that can be used to generate primary key values that are unique across multiple tables,
and for generating default values for a table. This statement applies to SAP IQ catalog store tables only.

 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

SAP IQ SQL Reference


SQL Statements INTERNAL 1361
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.

Sequences can generate values in one of the following ways:

● Increment or decrement monotonically without bound


● Increment or decrement monotonically to a user-defined limit and stop
● Increment or decrement monotonically to a user-defined limit and cycle back to the beginning and start
again

You control the behavior when the sequence runs out of values using the CYCLE clause.

If a sequence is increasing and it exceeds the MAXVALUE, MINVALUE is used as the next sequence value if
CYCLE is specified. If a sequence is decreasing and it falls below MINVALUE, MAXVALUE is used as the next
sequence value if CYCLE is specified. If CYCLE is not specified, an error is returned.

Sequence values cannot be used with views or materialized view definitions.

Privileges

You must have the CREATE ANY SEQUENCE or CREATE ANY OBJECT system privilege to create sequences.

To replace an existing sequence, you must have one of the following:

● CREATE ANY SEQUENCE and DROP ANY SEQUENCE system privileges.


● CREATE ANY OBJECT and DROP ANY OBJECT system privileges.
● ALTER ANY OBJECT or ALTER ANY SEQUENCE system privileges.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

SAP IQ SQL Reference


1362 INTERNAL SQL Statements
Side effects

None

Standards

ANSI/ISO SQL Standard

Sequences comprise SQL Language Feature T176. The software does not allow optional specification of the
sequence data type. This behavior can be achieved with a CAST when using the sequence.

In addition, the following are not in the standard:

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

Related Information

ALTER SEQUENCE statement [page 1168]


ALTER SEQUENCE statement [page 1168]
DROP SEQUENCE statement [page 1454]
DROP SEQUENCE statement [page 1454]
REVOKE System Privilege Statement [page 1635]

9.4.61 CREATE SERVER Statement

Adds a server to the ISYSSERVER table.

 Syntax

CREATE SERVER <server-name>

SAP IQ SQL Reference


SQL Statements INTERNAL 1363
CLASS '<server-class>'
USING '<connection-info>'
[ READ ONLY ]

<server-class> ::=
{ SAODBC
| ASEODBC
| DB2ODBC
| MSSODBC
| ORAODBC
| ODBC }

<connection-info> ::=
{ <machine-name>:<port-number> [ /<dbname> ] | <data-source-name> }

Parameters

USING

If a JDBC-based server class is used, the USING clause is <machine-name>:<port-number> [ /


<dbname> ], where:

● <hostname> – is the machine on which the remote server runs.


● <portnumber> – is the TCP/IP port number on which the remote server listens. The default port
number for SAP IQ and SAP SQL Anywhere is 2638.
● <dbname> – for SAP SQL Anywhere remote servers, if you do not specify a <dbname>, the default
database is used. For SAP ASE, the default is the master database, and an alternative to using
<dbname> is to another database by some other means (for example, in the FORWARD TO statement).

If an ODBC-based server class is used, the USING clause is the <data-source-name>, which is the ODBC
Data Source Name.
READ ONLY

Specifies that the remote server is a read-only data source. Any update request is rejected by SAP IQ.

Remarks

CREATE SERVER defines a remote server from the SAP IQ catalogs.

Privileges

Requires the SERVER OPERATOR system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

SAP IQ SQL Reference


1364 INTERNAL SQL Statements
Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example creates a remote server for the Oracle server named oracle723. Its ODBC Data Source
Name is “oracle723”:

CREATE SERVER oracle723


CLASS 'oraodbc'
USING 'oracle723'

Related Information

ALTER SERVER Statement [page 1170]


DROP SERVER Statement [page 1455]
REVOKE System Privilege Statement [page 1635]

9.4.62 CREATE SERVICE Statement

Permits a database server to act as a Web server.

 Syntax

CREATE SERVICE <service-name-string>


TYPE <service-type-string>
[ <attributes> ] [
AS <statement> ]

<service-type-string> ::=
{ 'RAW'
| 'HTML'
| 'XML'
| 'SOAP'
| 'DISH' }

SAP IQ SQL Reference


SQL Statements INTERNAL 1365
<attributes> ::=
[ AUTHORIZATION { ON | OFF } ]
[ SECURE { ON | OFF } ]
[ USER { <user-name> | NULL } ]
[ URL [ PATH/ ] { ON | OFF | ELEMENTS } ]
[ USING { <SOAP-prefix> | NULL } ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

service-name-string

Web service names may be any sequence of alphanumeric characters or “/”, “-”, “_”, “.”, “!”, “~”, “*”, “'”, “(“,
or “”)”, except that the first character cannot begin with a slash (/) and the name cannot contain two or
more consecutive slash characters.
AUTHORIZATION

Determines whether users must specify a user name and password when connecting to the service. The
default value is ON.

● If authorization is OFF, the AS clause is required and a single user must be identified by 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 role name using the USER clause. If
the user name is NULL, all known users can access the service.

Run production systems with authorization turned on. Grant permission to use the service by adding users
to a role.
SECURE

Indicates whether unsecure connections are accepted. ON indicates that only HTTPS connections are to
be accepted. Service requests received on the HTTP port are automatically redirected to the HTTPS port. If
set to OFF, both HTTP and HTTPS connections are accepted. The default value is OFF.
USER

If authorization is disabled, this parameter becomes mandatory and specifies the user ID used to execute
all service requests. If authorization is enabled (the default), this optional clause identifies the user or role
permitted access to the service. The default value is NULL, which grants access to all users.
URL

Determines whether URI paths are accepted and, if so, how they are processed. OFF indicates that nothing
must follow the service name in a URI request. ON indicates that the remainder of the URI is interpreted as
the value of a variable named <url>. ELEMENTS indicates that the remainder of the URI path is to be split
at the slash characters into a list of up to 10 elements. The values are assigned to variables named url plus

SAP IQ SQL Reference


1366 INTERNAL SQL Statements
a numeric suffix of between 1 and 10; for example, the first three variable names are url1, url2, and url3. If
fewer than 10 values are supplied, the remaining variables are set to NULL. If the service name ends with
the character /, then URL must be set to OFF. The default value is OFF.
USING

Applies only to DISH services. The parameter specifies a name prefix. Only SOAP services whose names
begin with this prefix are handled.
service-type-string

Identifies the type of the service. The type must be one of the listed service types. There is no default value.

● RAW – Sends the result set to the client without any further formatting. You can produce formatted
documents by generating the required tags explicitly within your procedure.
● HTML – Formats the result set of a statement or procedure into an HTML document that contains a
table.
● XML – Assumes the result set is an XML format. If it is not already so, it is automatically converted to
XML RAW format.
● SOAP – Formats the result set as a Simple Object Access Protocol (SOAP) response. The request must
be a valid SOAP request. For more information about the SOAP standards, see www.w3.org/TR/SOAP
.
● DISH – Determine SOAP Handler, or DISH, service acts as a proxy for one or more SOAP services. In
use, it acts as a container that holds and provides access to a number of SOAP services. A Web
Services Description Language (WSDL) file is automatically generated for each of the included SOAP
services. The included SOAP services are identified by a common prefix, which must be specified in
the USING clause.
statement

If the statement is NULL, the URI must specify the statement to be executed. Otherwise, the specified
SQL statement is the only one that can be executed through the service. The statement is mandatory for
SOAP services, and ignored for DISH services. The default value is NULL.

All services that are run in production systems must define a statement. The statement can be NULL only
if authorization is enabled.

Remarks

(back to top)

The CREATE SERVICE statement causes the database server to act as a web server. A new entry is created in
the SYSWEBSERVICE system table.

In a multiplex, execute CREATE SERVICE on both the coordinator and each secondary node that will act as a
web server.

Privileges

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1367
Requires the MANAGE ANY WEB SERVICE system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

The following example sets up a Web server quickly, start a database server with the -xs switch, then execute
this statement:

CREATE SERVICE tables TYPE 'HTML'


AUTHORIZATION OFF USER DBA
AS SELECT * FROM SYS.ISYSTAB

After executing this statement, use any Web browser to open the URL http://localhost/tables.

Related Information

ALTER SERVICE Statement [page 1173]


DROP SERVICE Statement [page 1456]
REVOKE System Privilege Statement [page 1635]

9.4.63 CREATE SPATIAL REFERENCE SYSTEM Statement

Creates or replaces a spatial reference system.

 Syntax

{ CREATE [ OR REPLACE ] SPATIAL REFERENCE SYSTEM


| CREATE SPATIAL REFERENCE SYSTEM IF NOT EXISTS }
<srs-name>
[ <srs-attribute> ] [ <srs-attribute> ... ]

<srs-attribute> ::=
SRID <srs-id>
| DEFINITION { <definition-string> | NULL }
| ORGANIZATION { <organization-name> IDENTIFIED BY <organization-srs-id>

SAP IQ SQL Reference


1368 INTERNAL SQL Statements
| 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> }
| TOLERANCE { <tolerance-distance> | DEFAULT }
| SNAP TO GRID { <grid-size> | DEFAULT }
| AXIS ORDER <axis-order>
| POLYGON FORMAT <polygon-format>
| STORAGE FORMAT <storage-format>
| SNAP TO GRID { <grid-size> | DEFAULT }
| AXIS ORDER <axis-order>
| POLYGON FORMAT <polygon-format>
| STORAGE FORMAT <storage-format>

<grid-size> ::=
DOUBLE : usually between 0 and 1

<axis-order> ::=
{ 'x/y/z/m' | 'long/lat/z/m' | 'lat/long/z/m' }

<polygon-format> ::=
{ 'CounterClockWise' | 'Clockwise' | 'EvenOdd' }

<storage-format> ::=
{ 'Internal' | 'Original' | 'Mixed' }

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

OR REPLACE

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.
IF NOT EXISTS

Specifying CREATE SPATIAL REFERENCE IF NOT EXISTS checks to see if a spatial reference system by
that name already exists. If it does not exist, the database server creates the spatial reference system. If it
does exist, no further action is performed and no error is returned.
IDENTIFIED BY

SAP IQ SQL Reference


SQL Statements INTERNAL 1369
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 SAP IQ 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 SAP IQ 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
2147483547 - 2147483647.

Also, since the SRID is stored as a signed 32-bit integer, the number cannot exceed 231-1 or 2147483647.
DEFINITION

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

Information about the organization that created the spatial reference system that the spatial reference
system is based on.
TRANSFORM DEFINITION

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.
LINEAR UNIT OF MEASURE

SAP IQ SQL Reference


1370 INTERNAL SQL Statements
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. 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. While both METRE and METER are accepted
spellings, METRE is preferred as it conforms to the SQL/MM standard.
ANGULAR UNIT OF MEASURE

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.

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

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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1371
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

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

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

SAP IQ SQL Reference


1372 INTERNAL SQL Statements
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)

SAP IQ uses the ellipsoid definition when computing distance in geographic spatial reference systems.
SNAP TO GRID

Flat-Earth (planar) spatial reference systems, use the SNAP TO GRID clause to define the size of the grid
SAP IQ uses when performing calculations. By default, SAP IQ 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.
TOLERANCE

Flat-Earth (planar) spatial reference systems, use the TOLERANCE clause to specify the precision to use
when comparing points. If the distance between two points is less than tolerance-distance, the two points
are considered equal. Setting tolerance-distance allows you to control the tolerance for imprecision in the
input data or limited internal precision. By default, tolerance-distance is set to be equal to grid-size.

When set to 0, two points must be exactly equal to be considered equal.

For round-Earth spatial reference systems, TOLERANCE must be set to 0.


POLYGON FORMAT

Internally, SAP IQ 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 SAP IQ 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 – input follows SAP IQ's internal interpretation: the inside of the polygon is on the
left side while following ring orientation.
● Clockwise – input follows the opposite of SAP IQ's approach: the inside of the polygon is on the right
side while following ring orientation.
● EvenOdd – (default) 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

Control what is stored when spatial data is loaded into the database. Possible values are:

● Internal – SAP IQ 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).
● Original – SAP IQ 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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1373
● Mixed – SAP IQ stores the internal version and, if it is different from the original version, SAP 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

(back to top)

For a geographic spatial reference system, you can specify both a LINEAR and an ANGULAR unit of measure;
otherwise for non-geographic, you specify only a LINEAR unit of measure. The LINEAR unit of measure is used
for computing distance between points and areas. The ANGULAR unit of measure tells how the angular
latitude/longitude are interpreted and is NULL for projected coordinate systems, non-NULL for geographic
coordinate systems.

All derived geometries returned by operations are normalized.

When working with data that is being synchronized with a non-SQL Anywhere database, STORAGE FORMAT
should be set to either 'Original' or 'Mixed' so that the original characteristics of the data can be preserved.

Privileges

(back to top)

Requires one of:

● MANAGE ANY SPATIAL OBJECT system privilege


● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

ANSI SQL – compliance level: Transact-SQL extension

Examples

(back to top)

SAP IQ SQL Reference


1374 INTERNAL SQL Statements
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';

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.64 CREATE SPATIAL UNIT OF MEASURE Statement

Creates or replaces a spatial unit of measurement.

 Syntax

CREATE [ OR REPLACE ] SPATIAL UNIT OF MEASURE <identifier>


TYPE { LINEAR | ANGULAR }
[ CONVERT USING <number> ]

Parameters

OR REPLACE

SAP IQ SQL Reference


SQL Statements INTERNAL 1375
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 privileges. An error is returned if you attempt
to replace a spatial unit that is already in use.
TYPE

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

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

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.

Privileges

Requires one of:

● MANAGE ANY SPATIAL OBJECT system privilege


● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

SAP IQ SQL Reference


1376 INTERNAL SQL Statements
Examples

The following example creates a spatial unit of measure named Test:

CREATE SPATIAL UNIT OF MEASURE Test


TYPE LINEAR
CONVERT USING 15;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.65 CREATE TABLE Statement

Creates a new table in the database or on a remote server.

 Syntax

CREATE [ { GLOAL | LOCAL } TEMPORARY ] TABLE


[ IF NOT EXISTS ] [ <owner>. ]<table-name>
… ( <column-definition> [ <column-constraint> ] …
[ , <column-definition> [ <column-constraint> ] …]
[ , <table-constraint> ] … )
|{ ENABLE | DISABLE } RLV STORE

…[ IN <dbspace-name> ]
…[ ON COMMIT { DELETE | PRESERVE } ROWS ]
[ AT <location-string> ]
[PARTITION BY
<range-partitioning-scheme>
| <hash-partitioning-scheme>
| <composite-partitioning-scheme> ]

<column-definition> ::=
<column-name> <data-type>
[ [ NOT ] NULL ]
[ DEFAULT <default-value> | IDENTITY ]
[ PARTITION | SUBPARTITION ( <partition-name> IN <dbspace-name>
[ , ... ] ) ]

<default-value> ::=
<special-value>
| <string>
| <global variable>
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function>( <constant-expression> )
| AUTOINCREMENT
| CURRENT DATABASE
| CURRENT REMOTE USER
| NULL
| TIMESTAMP
| LAST USER

SAP IQ SQL Reference


SQL Statements INTERNAL 1377
<special-value> ::=
CURRENT
{ DATE | TIME | TIMESTAMP | USER | PUBLISHER }
| USER

<column-constraint> ::=
[ CONSTRAINT <constraint-name> ] {
{ UNIQUE
| PRIMARY KEY
| REFERENCES <table-name> [ ( <column-name> ) ] [ <action> ]
}
[ IN <dbspace-name> ]
| CHECK ( <condition> )
| IQ UNIQUE ( <integer> )
}
}

<table-constraint> ::=
[ CONSTRAINT <constraint-name> ]
{ { UNIQUE ( <column-name> [ , <column-name> ] … )
| PRIMARY KEY ( <column-name> [ , <column-name> ] … )
}
[ IN <dbspace-name> ]
| <foreign-key-constraint>
| CHECK ( <condition> )
| IQ UNIQUE ( <integer> )

<foreign-key-constraint> ::=
FOREIGN KEY [ <role-name> ] [ ( <column-name> [ , <column-name> ] … ) ]
…REFERENCES <table-name> [ ( <column-name> [ , <column-name> ] … ) ]
…[ <actions> ] [ IN <dbspace-name> ]

<actions> ::=
[ ON { UPDATE | DELETE } RESTRICT ]

<location-string> ::=
{ <remote-server-name>. [ <db-name> ].[ <owner> ].<object-name>
| <remote-server-name>; [ <db-name> ]; [ <owner> ];<object-name> }

<range-partitioning-scheme> ::=
RANGE ( <partition-key> ) ( <range-partition-decl> [,<range-partition-
decl> ... ] )

<partition-key> ::= <column-name>

<range-partition-decl> ::=
VALUES <= ( {<constant-expr>
| MAX } [ , { <constant-expr>
| MAX }]... )
[ IN <dbspace-name> ]

<hash-partitioning-scheme> ::=
HASH ( <partition-key> [ , <partition-key>, … ] )

<composite-partitioning-scheme> ::=
<hash-partitioning-scheme> SUBPARTITION <range-partitioning-scheme>

SAP IQ SQL Reference


1378 INTERNAL SQL Statements
Parameters

{ ENABLE | DISABLE } RLV STORE

Registers this table with the RLV store for real-time in-memory updates. Not supported for IQ temporary
tables. This value overrides the value of the database option BASE_TABLES_IN_RLV. In a multiplex, the
RLV store can only be enabled on the coordinator.
IN

Used in the <column-definition>, <column-constraint>, <table-constraint>, <foreign-key>,


and <partition-decl> clauses to specify the dbspace where the object is to be created. If the IN clause
is omitted, SAP IQ creates the object in the dbspace where the table is assigned.

Specify SYSTEM with this clause to put either a permanent or temporary table in the catalog store. Specify
IQ_SYSTEM_TEMP to store temporary user objects (tables, partitions, or table indexes) in
IQ_SYSTEM_TEMP or, if the TEMP_DATA_IN_SHARED_TEMP option is set 'ON', and the IQ_SHARED_TEMP
dbspace contains RW files, in IQ_SHARED_TEMP (you cannot specify the IN clause with
IQ_SHARED_TEMP). All other use of the IN clause is ignored. By default, all permanent tables are placed in
the main IQ store, and all temporary tables are placed in the temporary IQ store. Global temporary and
local temporary tables can never be in the IQ store.

The following syntax is unsupported:

CREATE LOCAL TEMPORARY TABLE tab1(c1 int) IN IQ_SHARED_TEMP

A BIT data type column cannot be explicitly placed in a dbspace. The following is not supported for BIT
data types:

CREATE TABLE t1(c1_bit bit IN iq_main);

ON COMMIT

Allowed for temporary tables only. By default, the rows of a temporary table are deleted on COMMIT.
AT

Creates a proxy table that maps to a remote location specified by the location-string clause. Proxy table
names must be 30 characters or less. The AT clause supports semicolon (;) delimiters. If a semicolon is
present anywhere in the location-string clause, the semicolon is the field delimiter. 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.

Semicolon field delimiters are used primarily with server classes not currently supported; however, you can
also use them in situations where a period would also work as a field delimiter. For example, this statement
maps the table proxy_a to the SAP SQL Anywhere database mydb on the remote server myasa:

CREATE TABLE proxy_a1


AT 'myasa;mydb;;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 server supports
primary keys.

In a simplex environment, you cannot create a proxy table that refers to a remote table on the same node.
In a multiplex environment, you cannot create a proxy table that refers to the remote table defined within
the multiplex.

SAP IQ SQL Reference


SQL Statements INTERNAL 1379
IF NOT EXISTS

If the named object already exists, no changes are made and an error is not returned.
column-definition

Defines a table column. Allowable data types are described in Data Types. Two columns in the same table
cannot have the same name. You can create up to 45,000 columns; however, there might be performance
penalties in tables with more than 10,000 columns:

● [ NOT ] NULL] – Includes or excludes NULL values. If NOT NULL is specified, or if the column is in a
UNIQUE or PRIMARY KEY constraint, the column cannot contain any NULL values. The limit on the
number of columns per table that allow NULLs is approximately 8*(database-page-size - 30).
● DEFAULT default-value – Specify a default column value with the DEFAULT keyword in the CREATE
TABLE (and ALTER TABLE) statement. A DEFAULT value is used as the value of the column in any
INSERT (or LOAD) statement that does not specify a column value.
● DEFAULT AUTOINCREMENT – The value of the DEFAULT AUTOINCREMENT column uniquely
identifies every row in a table. Columns of this type are also known as IDENTITY columns, for
compatibility with SAP Adaptive Server Enterprise.
The IDENTITY/DEFAULT AUTOINCREMENT column stores sequential numbers that are automatically
generated during inserts and updates. When using IDENTITY or DEFAULT AUTOINCREMENT, the
column must be one of the integer data types, or an exact numeric type, with scale 0. The column
value might also be NULL. You must qualify the specified table name with the owner name.
ON inserts into the table. If a value is not specified for the IDENTITY/DEFAULT AUTOINCREMENT
column, a unique value larger than any other value in the column is generated. If an INSERT specifies a
value for the column, it is used; if the specified value is not larger than the current maximum value for
the column, that value is used as a starting point for subsequent inserts.
Deleting rows does not decrement the IDENTITY/AUTOINCREMENT counter. Gaps created by deleting
rows can only be filled by explicit assignment when using an insert.

 Note

To perform an explicit insert or update into an IDENTITY/AUTOINCREMENT column, set the


IDENTITY_INSERT database option to the table name. For information on IDENTITY_INSERT, see
SAP IQ SQL Reference.

For example, this creates a table with an IDENTITY column and explicitly adds some data to it:

CREATE TABLE mytable(c1 INT IDENTITY);


SET TEMPORARY OPTION IDENTITY_INSERT = "DBA".mytable;
INSERT INTO mytable VALUES(5);

After an explicit insert of a row number 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.
● IDENTITY – A Transact-SQL-compatible alternative to using the AUTOINCREMENT default. In SAP IQ,
the identity column may be created using either the IDENTITY or the DEFAULT AUTOINCREMENT
clause
table-constraint

Helps ensure the integrity of data in the database. There are four types of integrity constraints:

SAP IQ SQL Reference


1380 INTERNAL SQL Statements
● UNIQUE – identifies one or more columns that uniquely identify each row in the table. No two rows in
the table can have the same values in all the named columns. A table may have more than one unique
constraint.
● PRIMARY KEY – the same as a UNIQUE constraint except that a table can have only one primary-key
constraint. You cannot specify the PRIMARY KEY and UNIQUE constraints for the same column. The
primary key usually identifies the best identifier for a row. For example, the customer number might be
the primary key for the customer table.
● FOREIGN KEY – restricts the values for a set of columns to match the values in a primary key or
uniqueness constraint of another table. For example, a foreign-key constraint could be used to ensure
that a customer number in an invoice table corresponds to a customer number in the customer table.
You cannot create foreign-key constraints on local temporary tables. Global temporary tables must be
created with ON COMMIT PRESERVE ROWS.
● CHECK – allows arbitrary conditions to be verified. For example, a check constraint could be used to
ensure that a column called Gender contains only the values male or female. No row in a table is
allowed to violate a constraint. If an INSERT or UPDATE statement would cause a row to violate a
constraint, the operation is not permitted and the effects of the statement are undone.
Column identifiers in column check constraints that start with the symbol ‘@’ are placeholders for the
actual column name. The following two statements are exactly the same:

CREATE TABLE t1(c1 INTEGER CHECK (@foo < 5))

CREATE TABLE t1(c1 INTEGER CHECK (c1 < 5))

Column identifiers appearing in table check constraints that start with the symbol ‘@’are not
placeholders.

If a statement would cause changes to the database that violate an integrity constraint, the statement is
effectively not executed and an error is reported. This means that any changes made by the statement
before the error was detected are undone.

SAP IQ enforces single-column UNIQUE constraints by creating an HG index for that column.

 Note

You cannot define a column with a BIT data type as a UNIQUE or PRIMARY KEY constraint. Also, the
default for columns of BIT data type is to not allow NULL values; you can change this by explicitly
defining the column as allowing NULL values.

column-constraint

Restricts the values the column can hold. Column and table constraints help ensure the integrity of data in
the database. If a statement would cause a violation of a constraint, execution of the statement does not
complete, any changes made by the statement before error detection are undone, and an error is reported.
Column constraints are abbreviations for the corresponding table constraints. For example, these are
equivalent:

CREATE TABLE Products (


product_num integer UNIQUE
)

CREATE TABLE Products (


product_num integer,
UNIQUE ( product_num )
)

SAP IQ SQL Reference


SQL Statements INTERNAL 1381
Column constraints are normally used unless the constraint references more than one column in the table.
In these cases, use a table constraint.

IQ UNIQUE defines the expected cardinality of a column and determines whether the column loads as Flat
FP or NBit FP. An IQ UNIQUE(n) value explicitly set to 0 loads the column as Flat FP. Columns without an IQ
UNIQUE constraint implicitly load as NBit up to the limits defined by the FP_NBIT_AUTOSIZE_LIMIT,
FP_NBIT_LOOKUP_MB, and FP_NBIT_ROLLOVER_MAX_MB options:

● FP_NBIT_AUTOSIZE_LIMIT limits the number of distinct values that load as NBit


● FP_NBIT_LOOKUP_MB sets a threshold for the total NBit dictionary size
● FP_NBIT_ROLLOVER_MAX_MB sets the dictionary size for implicit NBit rollovers from NBit to Flat FP
● FP_NBIT_ENFORCE_LIMITS enforces NBit dictionary sizing limits. This option is OFF by default

Using IQ UNIQUE with an n value less than the FP_NBIT_AUTOSIZE_LIMIT is not necessary. Auto-size
functionality automatically sizes all low or medium cardinality columns as NBit. Use IQ UNIQUE in cases
where you want to load the column as Flat FP or when you want to load a column as NBit when the number
of distinct values exceeds the FP_NBIT_AUTOSIZE_LIMIT.

 Note

● Consider memory usage when specifying high IQ UNIQUE values. If machine resources are limited,
avoid loads with FP_NBIT_ENFORCE_LIMITS='OFF' (default).
Prior to SAP IQ 16.1, an IQ UNIQUE <n> value > 16777216 would rollover to Flat FP. In 16.1, larger IQ
UNIQUE values are supported for tokenization, but may require significant memory resource
requirements depending on cardinality and column width.
● BIT, BLOB, and CLOB data types do not support NBit dictionary compression. If
FP_NBIT_IQ15_COMPATIBILITY=’OFF’, a non-zero IQ UNIQUE column specification in a CREATE
TABLE or ALTER TABLE statement that includes these data types returns an error.

column-constraint and table-constraint clauses

Column and table constraints help ensure the integrity of data in the database:

● PRIMARY KEY or PRIMARY KEY ( <column-name>, … )


The primary key for the table consists of the listed columns, and none of the named columns can
contain any NULL values. SAP IQ ensures that each row in the table has a unique primary key value. A
table can have only one PRIMARY KEY.
When the second form is used (PRIMARY KEY followed by a list of columns), the primary key is created
including the columns in the order in which they are defined, not the order in which they are listed.
When a column is designated as PRIMARY KEY, FOREIGN KEY, or UNIQUE, SAP IQ creates a
High_Group index for it automatically. For multicolumn primary keys, this index is on the primary key,
not the individual columns. For best performance, you should also index each column with an HG index
separately.
● REFERENCES <primary-table-name> [(<primary-column-name>)]
Defines the column as a foreign key for a primary key or a unique constraint of a primary table.
Normally, a foreign key would be for a primary key rather than an unique constraint. If a primary
column name is specified, it must match a column in the primary table, which is subject to a unique
constraint or primary key constraint, and that constraint must consist of only that one column.
Otherwise the foreign key references the primary key of the second table. Primary key and foreign key
must have the same data type and the same precision, scale, and sign. Only a non-unique single-
column HG index is created for a single-column foreign key. For a multi-column foreign key, SAP IQ
creates a non unique composite HG index. The maximum width of a multi-column composite key for a
unique or non unique HG index is 1 KB.

SAP IQ SQL Reference


1382 INTERNAL SQL Statements
A temporary table cannot have a foreign key that references a base table and a base table cannot have
a foreign key that references a temporary table. Local temporary tables cannot have or be referenced
by a foreign key.
● FOREIGN KEY [<role-name>] [(...)] REFERENCES <primary-table-name> [(...)]
Defines foreign-key references to a primary key or a unique constraint in another table. Normally, a
foreign key would be for a primary key rather than an unique constraint. (In this description, this other
table is called the primary table.)
If the primary table column names are not specified, the primary table columns are the columns in the
table's primary key. If foreign key column names are not specified, the foreign-key columns have the
same names as the columns in the primary table. If foreign-key column names are specified, then the
primary key column names must be specified, and the column names are paired according to position
in the lists.
If the primary table is not the same as the foreign-key table, either the unique or primary key
constraint must have been defined on the referenced key. Both referenced key and foreign key must
have the same number of columns, of identical data type with the same sign, precision, and scale.
The value of the row's foreign key must appear as a candidate key value in one of the primary table's
rows unless one or more of the columns in the foreign key contains nulls in a null allows foreign key
column.
Any foreign-key column not explicitly defined is automatically created with the same data type as the
corresponding column in the primary table. These automatically created columns cannot be part of
the primary key of the foreign table. Thus, a column used in both a primary key and foreign key must
be explicitly created.
<role-name> is the name of the foreign key. The main function of <role-name> is to distinguish two
foreign keys to the same table. If no <role-name> is specified, the role name is assigned as follows:
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 3-digit number unique to the table.
The referential integrity action defines the action to be taken to maintain foreign-key relationships in
the database. Whenever a primary key value is changed or deleted from a database table, there may be
corresponding foreign key values in other tables that should be modified in some way. You can specify
an ON DELETE clause, followed by the RESTRICT clause.
● RESTRICT
Generates an error if you try to update or delete a primary key value while there are corresponding
foreign keys elsewhere in the database. Generates an error if you try to update a foreign key so that you
create new values unmatched by a candidate key. This is the default action, unless you specify that
LOAD optionally reject rows that violate referential integrity. This enforces referential integrity at the
statement level.
If you use CHECK ON COMMIT without specifying any actions, then RESTRICT is implied as an action
for DELETE. SAP IQ does not support CHECK ON COMMIT.
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. Local temporary tables cannot
have or be referenced by a foreign key.
● CHECK ( <condition> )
No row is allowed to fail the condition. If an INSERT statement would cause a row to fail the condition,
the operation is not permitted and the effects of the statement are undone.
The change is rejected only if the condition is FALSE; in particular, the change is allowed if the
condition is UNKNOWN. CHECK condition is not enforced by SAP IQ.

SAP IQ SQL Reference


SQL Statements INTERNAL 1383
 Note

If possible, do not define referential integrity foreign key-primary key relationships in SAP IQ unless
you are certain there are no orphan foreign keys.

PARTITION BY

Divides large tables into smaller, more manageable storage objects. Partitions share the same logical
attributes of the parent table, but can be placed in separate dbspaces and managed individually. SAP IQ
supports several table partitioning schemes:

● Hash-partitions
● Range-partitions
● Composite-partitions

A partition-key is the column or columns that contain the table partitioning keys. Partition keys can contain
NULL and DEFAULT values, but cannot contain:

● LOB (BLOB or CLOB) columns


● BINARY, or VARBINARY columns
● CHAR or VARCHAR columns whose length is over 255 bytes
● BIT columns
● FLOAT/DOUBLE/REAL columns
PARTITION BY RANGE

Partitions rows by a range of values in the partitioning column. Range partitioning is restricted to a single
partition key column and a maximum of 1024 partitions. In a range-partitioning-scheme, the partition-key
is the column that contains the table partitioning keys:

range-partition-decl:
<partition-name> VALUES <= ( {<constant-expr> | MAX } [ , { <constant-
expr> | MAX }]... )
[ IN <dbspace-name> ]

The partition-name is the name of a new partition on which table rows are stored. Partition names must be
unique within the set of partitions on a table. The partition-name is required.

● <VALUE> – Specifies the inclusive upper bound for each partition (in ascending order). The user must
specify the partitioning criteria for each range partition to guarantee that each row is distributed to
only one partition. NULLs are allowed for the partition column and rows with NULL as partition key
value belong to the first table partition. However, NULL cannot be the bound value.
There is no lower bound (MIN value) for the first partition. Rows of NULL cells in the first column of the
partition key will go to the first partition. For the last partition, you can either specify an inclusive upper
bound or MAX. If the upper bound value for the last partition is not MAX, loading or inserting any row
with partition key value larger than the upper bound value of the last partition generates an error.
● MAX – Denotes the infinite upper bound and can only be specified for the last partition.
● IN – specifies the dbspace in the partition-decl on which rows of the partition should reside.

These restrictions affect partitions keys and bound values for range partitioned tables:

● Partition bounds must be constants, not constant expressions.


● Partition bounds must be in ascending order according to the order in which the partitions were
created. That is, the upper bound for the second partition must be higher than for the first partition,
and so on.

SAP IQ SQL Reference


1384 INTERNAL SQL Statements
In addition, partition bound values must be compatible with the corresponding partition-key column
data type. For example, VARCHAR is compatible with CHAR.
● If a bound value has a different data type than that of its corresponding partition key column, SAP IQ
converts the bound value to the data type of the partition key column, with these exceptions:
○ Explicit conversions are not allowed. This example attempts an explicit conversion from INT to
VARCHAR and generates an error:

CREATE TABLE Employees(emp_name VARCHAR(20))


PARTITION BY RANGE(emp_name)
(p1 VALUES <=(CAST (1 AS VARCHAR(20))),
p2 VALUES <= (CAST (10 AS VARCHAR(20)))

○ Implicit conversions that result in data loss are not allowed. In this example, the partition bounds
are not compatible with the partition key type. Rounding assumptions may lead to data loss and an
error is generated:

CREATE TABLE emp_id (id INT) PARTITION BY RANGE(id) (p1 VALUES <=
(10.5), p2 VALUES <= (100.5))

● In this example, the partition bounds and the partition key data type are compatible. The bound values
are directly converted to float values. No rounding is required, and conversion is supported:

CREATE TABLE id_emp (id FLOAT)


PARTITION BY RANGE(id) (p1 VALUES <= (10),
p2 VALUES <= (100))

● Conversions from non-binary data types to binary data types are not allowed. For example, this
conversion is not allowed and returns an error:

CREATE TABLE newemp (name BINARY)


PARTITION BY RANGE(name)
(p1 VALUES <= ('Maarten'),
p2 VALUES <= ('Zymmerman')

● NULL cannot be used as a boundary in a range-partitioned table.


● The row will be in the first partition if the cell value of the 1st column of the partition key evaluated to be
NULL. SAP IQ supports only single column partition keys, so any NULL in the partition key distributes
the row to the first partition.
PARTITION BY HASH

Maps data to partitions based on partition-key values processed by an internal hashing function. Hash
partition keys are restricted to a maximum of eight columns with a combined declared column width of
5300 bytes or less. For hash partitions, the table creator determines only the partition key columns; the
number and location of the partitions are determined internally.

In a hash-partitioning declaration, the partition-key is a column or group of columns, whose composite


value determines the partition where each row of data is stored:

hash-partitioning-scheme:
HASH ( <partition-key> [ , <partition-key>, … ] )

Restrictions:

● You can only hash partition a base table. Attempting to partitioning a global temporary table or a local
temporary table raises an error.
● You cannot add, drop, merge, or split a hash partition.
● You cannot add or drop a column from a hash partition key.

SAP IQ SQL Reference


SQL Statements INTERNAL 1385
PARTITION BY HASH RANGE

Subpartitions a hash-partitioned table by range. In a hash-range-partitioning-scheme declaration, a


SUBPARTITION BY RANGE clause adds a new range subpartition to an existing hash-range partitioned
table:

hash-range-partitioning-scheme:
PARTITION BY HASH ( <partition-key> [ , <partition-key>, … ] )
[ SUBPARTITION BY RANGE ( <range-partition-decl> [ , <range-partition-
decl> … ] ) ]

The hash partition specifies how the data is logically distributed and colocated; the range subpartition
specifies how the data is physically placed. The new range subpartition is logically partitioned by hash with
the same hash partition keys as the existing hash-range partitioned table. The range subpartition key is
restricted to one column.

Restrictions:

● You can only hash partition a base table. Attempting to partitioning a global temporary table or a local
temporary table raises an error.
● You cannot add, drop, merge, or split a hash partition.
● You cannot add or drop a column from a hash partition key.

 Note

Range-partitions and composite partitioning schemes, like hash-range partitions, require the
separately licensed VLDB Management option.

Remarks

If the table is in a SAN dbspace but its columns or range partitions are in a DAS dbspace, the CREATE TABLE
statement results in an error. Table subcomponents cannot be created on DAS dbspaces if the parent table is
not a DAS dbspace table.

You can create a table for another user by specifying an owner name. If GLOBAL TEMPORARY or LOCAL
TEMPORARY is not specified, the table is referred to as a base table. Otherwise, the table is a temporary table.

A created global temporary table exists in the database like a base table and remains in the database until it is
explicitly removed by a DROP TABLE statement. The rows in a temporary table are visible only to the
connection that inserted the rows. Multiple connections from the same or different applications can use the
same temporary table at the same time and each connection sees only its own rows. A given connection
inherits the schema of a global temporary table as it exists when the connection first refers to the table. The
rows of a temporary table are deleted when the connection ends.

When you create a local temporary table, omit the owner specification. If you specify an owner when creating a
temporary table, for example, CREATE TABLE dbo.#temp(col1 int), a base table is incorrectly created.

An attempt to create a base table or a global temporary table will fail, if a local temporary table of the same
name exists on that connection, as the new table cannot be uniquely identified by owner.table.

You can, however, create a local temporary table with the same name as an existing base table or global
temporary table. References to the table name access the local temporary table, as local temporary tables are
resolved first.

SAP IQ SQL Reference


1386 INTERNAL SQL Statements
For example, consider this sequence:

CREATE TABLE t1 (c1 int);


INSERT t1 VALUES (9);
CREATE LOCAL TEMPORARY TABLE t1 (c1 int);
INSERT t1 VALUES (8);
SELECT * FROM t1;

The result returned is 8. Any reference to t1 refers to the local temporary table t1 until the local temporary
table is dropped by the connection.

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.

Local temporary tables created in IF statements using CREATE LOCAL TEMPORARY TABLE also persist after
the IF statement completes.

SAP IQ does not support the CREATE TABLE ENCRYPTED clause for table-level encryption of SAP IQ tables.
However, the CREATE TABLE ENCRYPTED clause is supported for SAP SQL Anywhere tables in an SAP IQ
database.

Privileges

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Table Type Privileges Required

Base table in the IQ main Table owned by self requires CREATE object-level privilege on the dbspace where the table is
store
created along with one of:

● CREATE TABLE system privilege


● CREATE ANY OBJECT system privilege

Table owned by another user requires CREATE object-level privilege on the dbspace where the
table is created along with one of:

● CREATE ANY TABLE system privilege


● CREATE ANY OBJECT system privilege

To enable RLV store during creation requires the CREATE TABLE system privilege and CREATE
object-level permissions on the RLV store dbspace.

Global temporary table Table owned by self requires one of:

● CREATE TABLE system privilege


● CREATE ANY OBJECT system privilege

Table owned by any user requires one of:

● CREATE ANY TABLE system privilege


● CREATE ANY OBJECT system privilege

SAP IQ SQL Reference


SQL Statements INTERNAL 1387
Table Type Privileges Required

Proxy table Table owned by self requires one of:

● CREATE PROXY TABLE system privilege


● CREATE ANY TABLE system privilege
● CREATE ANY OBJECT system privilege

Table owned by any user requires one of:

● CREATE ANY TABLE system privilege


● CREATE ANY OBJECT system privilege

Side Effects

Automatic commit

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar. Vendor extensions are:


○ The { IN | ON } <dbspace-name> clause
○ The ON COMMIT clause
○ Some of the default values
● SAP database products – supported by SAP Adaptive Server Enterprise, with some differences:
○ Temporary tables – you can create a temporary table by preceding the table name in a CREATE TABLE
statement with a pound sign (#). These temporary tables are SAP IQ declared temporary tables, which
are available only in the current connection. For information about declared temporary tables, see
DECLARE LOCAL TEMPORARY TABLE Statement.
○ Physical placement – physical placement of a table is carried out differently in SAP IQ and in SAP ASE.
The ON <segment-name> clause supported by SAP ASE is supported in SAP IQ, but <segment-
name> refers to an IQ dbspace.
○ Constraints – SAP IQ does not support named constraints or named defaults, but does support user-
defined data types that allow constraint and default definitions to be encapsulated in the data type
definition. It also supports explicit defaults and CHECK conditions in the CREATE TABLE statement.
○ NULL – (default) by default, columns in SAP ASE default to NOT NULL, whereas in SAP IQ the default
setting is NULL, to allow NULL values. This setting can be controlled using the
ALLOW_NULLS_BY_DEFAULT option. See ALLOW_NULLS_BY_DEFAULT Option [TSQL]. To make your
data definition statements transferable, explicitly specify NULL or NOT NULL.

Examples

● This example creates a table named SalesOrders2 with five columns. Data pages for columns
FinancialCode, OrderDate, and ID are in dbspace Dsp3. Data pages for integer column CustomerID

SAP IQ SQL Reference


1388 INTERNAL SQL Statements
are in dbspace Dsp1. Data pages for CLOB column History are in dbspace Dsp2. Data pages for the
primary key, HG for ID, are in dbspace Dsp4:

CREATE TABLE SalesOrders2 (


FinancialCode CHAR(2),
CustomerID int IN Dsp1,
History CLOB IN Dsp2,
OrderDate TIMESTAMP,
ID BIGINT,
PRIMARY KEY(ID) IN Dsp4
) IN Dsp3

● This example creates a table fin_code2 with four columns. Data pages for columns code, type, and id
are in the default dbspace, which is determined by the value of the database option DEFAULT_DBSPACE.
Data pages for CLOB column description are in dbspace Dsp2. Data pages from foreign key fk1, HG for
c1 are in dbspace Dsp4:

CREATE TABLE fin_code2 (


code INT,
type CHAR(10),
description CLOB IN Dsp2,
id BIGINT,
FOREIGN KEY fk1(id) REFERENCES SalesOrders(ID) IN Dsp4
)

● This example creates a table t1 where partition p1 is adjacent to p2 and partition p2 is adjacent to p3:

CREATE TABLE t1 (c1 INT, c2 INT)


PARTITION BY RANGE(c1)
(p1 VALUES <= (0), p2 VALUES <= (10), p3 VALUES <= (100))

● This example creates a RANGE partitioned table bar with six columns and three partitions, mapping data
to partitions based on dates:

CREATE TABLE bar (


c1 INT IQ UNIQUE(65500),
c2 VARCHAR(20),
c3 CLOB PARTITION (P1 IN Dsp11, P2 IN Dsp12,
P3 IN Dsp13),
c4 DATE,
c5 BIGINT,
c6 VARCHAR(500) PARTITION (P1 IN Dsp21,
P2 IN Dsp22),
PRIMARY KEY (c5) IN Dsp2) IN Dsp1
PARTITION BY RANGE (c4)
(P1 VALUES <= ('2006/03/31') IN Dsp31,
P2 VALUES <= ('2006/06/30') IN Dsp32,
P3 VALUES <= ('2006/09/30') IN Dsp33
) ;

● Data page allocation for each partition:

Partition Dbspaces Columns

P1 Dsp31 c1, c2, c4, c5

P1 Dsp11 c3

P1 Dsp21 c6

P2 Dsp32 c1, c2, c4, c5

SAP IQ SQL Reference


SQL Statements INTERNAL 1389
Partition Dbspaces Columns

P2 Dsp12 c3

P2 Dsp22 c6

P3 Dsp33 c1, c2, c4, c5, c6

P3 Dsp13 c3

P1, P2, P3 Dsp1 lookup store of c1 and other shared data

P1, P2, P3 Dsp2 primary key (HG for c5)

● This example creates a HASH partitioned (table tbl42) that includes a PRIMARY KEY (column c1) and a
HASH PARTITION KEY (columns c4 and c3):

CREATE TABLE tbl42 (


c1 BIGINT NOT NULL,
c2 CHAR(2) IQ UNIQUE(50),
c3 DATE IQ UNIQUE(36524),
c4 VARCHAR(200),
PRIMARY KEY (c1)
)
PARTITION BY HASH ( c4, c3 )

● This example creates a hash-ranged partitioned table with a PRIMARY KEY (column c1), a hash partition
key (columns c4 and c2) and a range subpartition key (column c3):

CREATE TABLE tbl42 (


c1 BIGINT NOT NULL,
c2 CHAR(2) IQ UNIQUE(50),
c3 DATE,
c4 VARCHAR(200),
PRIMARY KEY (c1)) IN Dsp1

PARTITION BY HASH ( c4, c2 )


SUBPARTITION BY RANGE ( c3 )
( P1 VALUES <= (2011/03/31) IN Dsp31,
P2 VALUES <= (2011/06/30) IN Dsp32,
P3 VALUES <= (2011/09/30) IN Dsp33) ;

● This example creates a table for a library database to hold information on borrowed books:

CREATE TABLE borrowed_book (


date_borrowed DATE NOT NULL,
date_returned DATE,
book CHAR(20)
REFERENCES library_books (isbn),
CHECK( date_returned >= date_borrowed )
)

● This example creates table t1 at the remote server SERVER_A and create 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'

SAP IQ SQL Reference


1390 INTERNAL SQL Statements
● This example creates table tab1 that contains a column c1 with a default value of the special constant
LAST USER:

CREATE TABLE tab1(c1 CHAR(20) DEFAULT LAST USER)

● This example creates a local temporary table tab1 that contains a column c1:

CREATE LOCAL TEMPORARY TABLE tab1(c1 int) IN IQ_SYSTEM_TEMP

● The example creates tab1 in the IQ_SYSTEM_TEMP dbspace in the following cases:
○ DQP_ENABLED logical server policy option is set ON but there are no read-write files in
IQ_SHARED_TEMP
○ DQP_ENABLED option is OFF, TEMP_DATA_IN_SHARED_TEMP logical server policy option is ON, but
there are no read-write files in IQ_SHARED_TEMP
○ Both the DQP_ENABLED option and the TEMP_DATA_IN_SHARED_TEMP option are set OFF
● The example creates the same table tab1 in the IQ_SHARED_TEMP dbspace in the following cases:
○ DQP_ENABLED is ON and there are read-write files in IQ_SHARED_TEMP
○ DQP_ENABLED is OFF, TEMP_DATA_IN_SHARED_TEMP is ON, and there are read-write files in
IQ_SHARED_TEMP
● This example creates a table tab1 that is enabled to use row-level versioning, and real-time storage in the
in-memory RLV store:

CREATE TABLE tab1 ( c1 INT, c2 CHAR(25) ) ENABLE RLV STORE

Related Information

%TYPE and %ROWTYPE attributes [page 93]


ALLOW_NULLS_BY_DEFAULT Option [TSQL] [page 1756]
ALTER TABLE Statement [page 1181]
CREATE DBSPACE Statement [page 1254]
CREATE INDEX Statement [page 1294]
DECLARE LOCAL TEMPORARY TABLE Statement [page 1422]
DROP Statement [page 1433]
FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]
FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1391
9.4.66 CREATE TEXT CONFIGURATION Statement

Creates a text configuration object.

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

 Syntax

CREATE TEXT CONFIGURATION [ <owner>.]<new-config-name>


FROM [ <owner>.]<existing-config-name>

Parameters

FROM

Specifies the name of a text configuration object to use as the template for creating the new text
configuration object. The names of the default text configuration objects are DEFAULT_CHAR and
DEFAULT_NCHAR. DEFAULT_CHAR is supported for SAP IQ tables only; DEFAULT_NCHAR is supported on
SAP SQL Anywhere tables only.

Remarks

Create a text configuration object using another text configuration object as a template, then alter the options
as needed using the ALTER TEXT CONFIGURATION statement.

To view the list of all text configuration objects and their settings in the database, query the SYSTEXTCONFIG
system view.

Privileges

Text Configuration Ownership Privilege Required

Self Requires the CREATE TEXT CONFIGURATION system privilege

Other user Requires one of:

● CREATE ANY TEXT CONFIGURATION system privilege


● CREATE ANY OBJECT system privilege

All text configuration objects have PUBLIC access. Any user with privilege to create a TEXT index can use any
text configuration object.

SAP IQ SQL Reference


1392 INTERNAL SQL Statements
See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side Effects

Automatic commit

Examples

The following example creates a text configuration object, max_term_sixteen, using the default_char text
configuration object, then use ALTER TEXT CONFIGURATION to change the maximum term length for
max_term_sixteen to 16:

CREATE TEXT CONFIGURATION max_term_sixteen FROM default_char;

ALTER TEXT CONFIGURATION max_term_sixteen MAXIMUM TERM LENGTH 16;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.67 CREATE TEXT INDEX Statement

Creates a TEXT index and specifies the text configuration object to use.

 Syntax

CREATE TEXT INDEX <text-index-name>


ON [ <owner.>]<table-name>( <column-name>, ...)
[ IN <dbspace-name> ]
[ CONFIGURATION [ <owner.>]<text-configuration-name>]
[ IMMEDIATE REFRESH ]

Parameters

ON

Specifies the table and column on which to build the TEXT index.
IN

SAP IQ SQL Reference


SQL Statements INTERNAL 1393
Specifies 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 underlying table.
CONFIGURATION

Specifies the text configuration object to use when creating the TEXT index. If this clause is not specified,
the default_char text configuration object is used.
IMMEDIATE REFRESH

(Default) refreshes the TEXT index each time changes in the underlying table impact data in the TEXT
index. Only permitted value for tables in SAP IQ main store. Once created, the IMMEDIATE REFRESH
clause cannot be changed.

Remarks

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

You cannot create a TEXT index on views or temporary tables, or on an IN SYSTEM materialized view. The
BEGIN PARALLEL IQ…END PARALLEL IQ statement does not support CREATE TEXT INDEX.

Privileges

Requires one of:

● CREATE ANY INDEX system privilege along with CREATE object-level privilege on the dbspace where the
index is being created.
● CREATE ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Side Effects

Automatic commit

Examples

The following example creates a TEXT index, myTxtIdx, on the CompanyName column of the Customers table
in the iqdemo database, using the max_term_sixteen text configuration object:

CREATE TEXT INDEX myTxtIdx ON Customers (CompanyName );

SAP IQ SQL Reference


1394 INTERNAL SQL Statements
CONFIGURATION max_term_sixteen;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.68 CREATE TRIGGER statement

Creates a trigger on a table. This statement applies to SAP IQ catalog store tables only.

 Syntax

CREATE [ OR REPLACE ] TRIGGER <trigger-name> <trigger-type>


{ <trigger-event-list> | UPDATE OF <column-list> }
[ ORDER <integer> ] ON <table-name>
[ REFERENCING [ OLD AS <old-name> ]
[ NEW AS <new-name> ]
[ REMOTE AS <remote-name> ] ]
[ FOR EACH { ROW | STATEMENT } ]
[ WHEN ( <search-condition> ) ]
<trigger-body>

<column-list> : <column-name>[, ...]

<trigger-type> :
BEFORE
| AFTER
| INSTEAD OF
| RESOLVE

<trigger-event-list> : <trigger-event>[, ... ]

<trigger-event> :
DELETE
| INSERT
| UPDATE

<trigger-body> : a BEGIN statement that optionally includes boolean logic


keywords ({ IF | ELSIF } { INSERTING | UPDATING | DELETING } THEN <some-
action>)

Parameters

OR REPLACE clause

Specifying OR REPLACE creates a new trigger, or replaces an existing trigger with the same name.

SAP IQ SQL Reference


SQL Statements INTERNAL 1395
trigger-type

Row-level triggers can be defined to execute BEFORE, AFTER, or INSTEAD OF an insert, update, or delete
operation. Statement-level triggers can be defined to execute INSTEAD OF or AFTER the statement.

BEFORE UPDATE triggers fire any time an UPDATE occurs on a row, whenever the new value differs from
the old value. That is, if a <column-list> is specified for a BEFORE UPDATE trigger, then 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, then 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 as a row-level
or a statement-level trigger. A statement-level INSTEAD OF trigger replaces the entire statement, including
all row-level operations. If a statement-level INSTEAD OF trigger fires, then 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, then you cannot use the UPDATE OF <column-list> clause,
the ORDER clause, or the WHEN clause.
trigger-event

When defining a trigger, you can combine DELETE, INSERT, and UPDATE events in the same definition, but
triggers for UPDATE OF events must be defined separately. You can define any number of DELETE, INSERT,
and UPDATE triggers on a table. You can define any number of triggers for UPDATE OF events on a table,
but only one per column.

Triggers can be fired by the following events:

DELETE event

The trigger is invoked whenever one or more rows of the table are deleted.
INSERT event

The trigger is invoked whenever one or more rows are inserted into the table.
UPDATE event

The trigger is invoked whenever one or more rows of the table are updated.

The keyword UPDATING is also supported for this clause for compatibility with other SQL dialects. The
argument for UPDATING is a quoted string (for example, UPDATING( 'mycolumn' )), whereas the
argument for UPDATE is an identifier (for example, UPDATE( mycolumn )).
UPDATE OF column-list event

The trigger is 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 only specify one UPDATE OF trigger per column.

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.
ORDER clause

SAP IQ SQL Reference


1396 INTERNAL SQL Statements
It is good practice to specify order for triggers when defining multiple triggers on a table, even if they are
not the same type. This ensures predictable results and makes easier to confirm which order they are
processed in.

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, then 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.

Typically, if you omit the ORDER clause, or specify 0, then the database server assigns the order of 1.
However, if another same-type trigger is already set to 1, then an error is returned.

When you create additional triggers that contain multiple event types, if you omit the ORDER clause, and
one or more of the event types is the same as in other triggers (for example, the trigger-event-list for one
trigger is UPDATE, INSERT, and the trigger-event-list for another trigger is UPDATE), the database server
does not return an error. In this case, the database server processes the triggers in an implementation-
specific order that may not be expected and is subject to change. Therefore, it is strongly recommended
that you always specify an ORDER clause when defining more than one trigger on a table.

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, then the new trigger must
have an ORDER value unique from other 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 meanings of REFERENCING OLD and REFERENCING NEW differ, 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.
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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1397
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.

You can also use Boolean conditions { INSERTING | DELETING | UPDATING [ ( '<col-
name>' ) ] } anywhere a condition can be used in the body of the trigger. This special syntax enables
you to specify an additional action to take when performing some <trigger-event>. For example, IF
INSERTING THEN SET msg = msg || 'insert'.

Remarks

The CREATE TRIGGER statement creates a trigger associated with a table in the database, and stores the
trigger in the database.

You cannot define a trigger on a materialized view. If you do, a SQLE_INVALID_TRIGGER_MATVIEW error is
returned.

A trigger is declared as either a row-level trigger, in which case it executes before or after each row is modified,
or a statement-level trigger, in which case it executes after the entire triggering statement is completed.

CREATE TRIGGER puts a table lock on the table and requires exclusive use of the table.

Privileges

You must have the CREATE ANY TRIGGER or CREATE ANY OBJECT system privilege. Additionally, you must be
the owner of the table the trigger is built on or have one of the following privileges:

● ALTER privilege on the table


● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege

To create a trigger on a view owned by someone else, you must have either the CREATE ANY TRIGGER or
CREATE ANY OBJECT system privilege, and you must have either the ALTER ANY VIEW or ALTER ANY OBJECT
system privilege.

To replace an existing trigger, you must be the owner of the table the trigger is built on, or have one of the
following:

● CREATE ANY TRIGGER system privilege.

SAP IQ SQL Reference


1398 INTERNAL SQL Statements
● CREATE ANY OBJECT and DROP ANY OBJECT system privileges.
● ALTER ANY OBJECT or ALTER ANY TRIGGER system privileges.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

Automatic commit.

Standards

ANSI/ISO SQL Standard

CREATE TRIGGER is part of optional ANSI/ISO SQL Language Feature T211 "Basic trigger capability". Row
triggers are optional ANSI/ISO SQL Language Feature T212, while INSTEAD OF triggers are optional
ANSI/ISO SQL Language Feature T213.

Some trigger features in the software are not in the standard. 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 the ANSI/ISO SQL Standard, triggers are fired in the order they were created.
● RESOLVE triggers.
Transact-SQL

ROW and RESOLVE triggers are not supported by Adaptive Server Enterprise. The SAP IQ 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. First, create a table as shown in this CREATE TABLE
statement (requires the CREATE TABLE system privilege):

CREATE TABLE t0
( id INTEGER NOT NULL,
times TIMESTAMP NULL DEFAULT CURRENT TIMESTAMP,
remarks TEXT NULL,
PRIMARY KEY ( id )
);

Next, create a statement-level trigger for this table:

CREATE TRIGGER myTrig AFTER INSERT ORDER 4 ON t0


REFERENCING NEW AS new_name
FOR EACH STATEMENT
BEGIN
DECLARE @id1 INTEGER;
DECLARE @times1 TIMESTAMP;
DECLARE @remarks1 LONG VARCHAR;
DECLARE @err_notfound EXCEPTION FOR SQLSTATE VALUE '02000';
//declare a cursor for table new_name

SAP IQ SQL Reference


SQL Statements INTERNAL 1399
DECLARE new1 CURSOR FOR
SELECT id, times, remarks FROM new_name;
OPEN new1;
//Open the cursor, and get the value
LoopGetRow:
LOOP
FETCH NEXT new1 INTO @id1, @times1,@remarks1;
IF SQLSTATE = @err_notfound THEN
LEAVE LoopGetRow
END IF;
//print the value or for other use
PRINT (@remarks1);
END LOOP LoopGetRow;
CLOSE new1
END;

The following example replaces the myTrig trigger created in the previous example.

CREATE OR REPLACE TRIGGER myTrig AFTER INSERT ORDER 4 ON t0


REFERENCING NEW AS new_name
FOR EACH STATEMENT
BEGIN
FOR L1 AS new1 CURSOR FOR
SELECT id, times, remarks FROM new_name
DO
//print the value or for other use
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. You must have the SELECT, ALTER,
and UPDATE object-level privileges on GROUPO.Employees to execute this statement:

CREATE TRIGGER emp_upper_postal_code


BEFORE UPDATE OF PostalCode
ON GROUPO.Employees
REFERENCING NEW AS new_emp
FOR EACH ROW
WHEN ( ISNUMERIC( new_emp.PostalCode ) = 0 )
BEGIN
-- Ensure postal code is uppercase (employee might be
-- in Canada where postal codes contain letters)
SET new_emp.PostalCode = UPPER(new_emp.PostalCode)
END;
UPDATE GROUPO.Employees SET state='ON', PostalCode='n2x 4y7' WHERE
EmployeeID=191;
SELECT PostalCode FROM GROUPO.Employees WHERE EmployeeID = 191;

The next example shows how you can use REFERENCING OLD in a BEFORE DELETE trigger. This example
prevents deleting an employee from the Employees table who has not been terminated.

CREATE TRIGGER TR_check_delete_employee


BEFORE DELETE
ON Employees
REFERENCING OLD AS current_employee
FOR EACH ROW WHEN ( current_employee.Terminate IS NULL )
BEGIN
RAISERROR 30001 'You cannot delete an employee who has not been fired';
END;

SAP IQ SQL Reference


1400 INTERNAL SQL Statements
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 GROUPO.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 in a BEFORE INSERT and UPDATE trigger.
The following example creates a trigger that fires before a row in the SalesOrderItems table is inserted or
updated.

CREATE TRIGGER TR_update_date


BEFORE INSERT, UPDATE
ON GROUPO.SalesOrderItems
REFERENCING NEW AS new_row
FOR EACH ROW
BEGIN
SET new_row.ShipDate = CURRENT TIMESTAMP;
END;

The following trigger displays a message on the History 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;

Related Information

ALTER TRIGGER statement [page 1201]


ALTER TRIGGER statement [page 1201]
DROP TRIGGER statement [page 1463]
DROP TRIGGER statement [page 1463]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1401
9.4.69 CREATE USER Statement

Creates a user.

 Syntax

CREATE USER <user-name> [ IDENTIFIED BY <password> ]


[ LOGIN POLICY <policy-name> ]
[ FORCE PASSWORD CHANGE { ON | OFF } ]

Parameters

user-name

Name of the user.


IDENTIFIED BY password

The password for the user.

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 role and do not want anyone to connect to the database using
the role user ID. A user ID must be a valid identifier. User IDs and passwords cannot:

● Begin with white space, single quotes, or double quotes


● End with white space
● Contain semicolons

A password can be either a valid identifier, or a string (maximum 255 characters) placed in single quotes.
Passwords are case-sensitive. The password should be composed of 7-bit ASCII characters, as other
characters may not work correctly if the database server cannot convert them from the client's character
set to UTF-8.

You can use the VERIFY_PASSWORD_FUNCTION option to specify a function to implement password rules
(for example, passwords must include at least one digit). If you do use a password verification function, you
cannot specify more than one user ID and password in the GRANT CONNECT statement.

The encryption algorithm used for hashing the user passwords is FIPS-certified encryption support:

● The DLL is called dbfips10.dll.


● The HASH function accepts the algorithms: SHA1_FIPS SHA256_FIPS.
● If the -fips server option is specified and an algorithm that is not FIPS-certified is given to the HASH
function, the database server uses SHA1_FIPS instead of SHA1, SHA256_FIPS instead of SHA256, and
returns an error if MD5 is used (MD5 is not a FIPS-certified algorithm).
● If the -fips option is specified, the database server uses SHA256_FIPS for password hashing.
LOGIN POLICY policy-name

Name of the login policy to assign the user. No change is made if you do not specify a login policy.
FORCE PASSWORD CHANGE

Controls whether the user must specify a new password upon logging in. This setting overrides the
PASSWORD_EXPIRY_ON_NEXT_LOGIN option setting in the user's login policy.

SAP IQ SQL Reference


1402 INTERNAL SQL Statements
 Note

This functionality is not currently implemented when logging in to SAP IQ Cockpit. However, when
logging in to SAP IQ outside of SAP IQ Cockpit (for example, using Interactive SQL), users are then
prompted to enter a new password.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

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;

Related Information

(Deprecated) sp_iqaddlogin Procedure [page 585]


COMMENT Statement [page 1233]
CREATE LOGIN POLICY Statement [page 1307]
DROP LOGIN POLICY Statement [page 1445]
DROP USER Statement [page 1464]
GRANT ROLE Statement [page 1504]
GRANT System Privilege Statement [page 1511]
VERIFY_PASSWORD_FUNCTION Option [page 2066]
ALTER LOGIN POLICY Statement [page 1155]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1403
9.4.70 CREATE VARIABLE Statement

Creates data type or a connection- or database-scope variable.

 Syntax

Syntax 1 – Creates a Connection-Scope Variable

CREATE [OR REPLACE] VARIABLE <identifier> <data-type>


[ { = | DEFAULT} <initial-value> ]

<initial-value> ::=
<expression>

Syntax 2 – Creates a Data Type or Database-Scope Variable

CREATE [ OR REPLACE ] DATABASE VARIABLE [ IF NOT EXISTS ]


[ <owner>.]<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

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

OR REPLACE

Specifying the OR REPLACE clause drops the named variable if it already exists and re-creates it with the
new definition. OR REPLACE only replaces the value of the variable if the data type of the current and new
value are the same.

SAP IQ SQL Reference


1404 INTERNAL SQL Statements
Do not use this clause with the IF NOT EXISTS clause.
owner

This parameter applies only to database-scope variables. Specify a valid user ID or role, or PUBLIC to set
ownership of the variable. If set to a user, only that user can use the database variable. If set to a role, users
who have that role are able to use the database variable. If set to PUBLIC, all users are able to use the
variable.

If <owner> is not specified, it is set to the user executing the CREATE VARIABLE statement.
identifier

A valid identifier for the variable.


data-type

The data type for the variable. Set the data type explicitly, or use the %TYPE or %ROWTYPE attribute to
set the data type to the data type of another object in the database. Use %TYPE to set it to the data type of
a variable or a column in a table or view. Use %ROWTYPE to set the data type to a composite data type
derived from a row in a cursor, table, or view.

%ROWTYPE and TABLE REF is not supported as data types for database-scope variables.
IF NOT EXISTS

Specify this clause to allow the statement to complete without returning an error if a database-scope
variable with the same name already exists. This parameter is only for use when creating owned database-
scope variables.

Do not use this clause with the OR REPLACE clause.


= | DEFAULT

The default value for the variable. For database-scope variables, this is also the initial value after the
database is restarted.

<initial-value> must match the data type defined by <data-type>. If you do not specify an
<initial-value>, then the variable contains the NULL value until a different value is assigned, for
example by using a SET statement, a SELECT ... INTO statement, or in an UPDATE statement. If
<initial-value> is set by using an expression, then the expression is evaluated at creation time and the
resulting constant is stored (not the expression).

Remarks

(back to top)

A variable can be used in a SQL expression anywhere a column name is allowed. If a column name exists with
the same name as the variable, the variable value is used. Name resolution is performed as follows:

● Match any aliases specified in the query's SELECT list.


● Match column names for any referenced tables.
● Assume the name is a variable.

Variables belong to the current connection, and disappear when you disconnect from the database, or when
you use the DROP VARIABLE statement. Variables are not visible to other connections. COMMIT or ROLLBACK
statements do not affect variables.

SAP IQ SQL Reference


SQL Statements INTERNAL 1405
Variables created with the CREATE VARIABLE statement persist for a connection even when the statement is
issued within a (BEGIN...END) statement. You must use DECLARE to create variables that only persist within
a (BEGIN...END) statement, for example, within stored procedures.

Variables are useful for creating large text or binary objects for INSERT or UPDATE statements from Embedded
SQL programs.

Use the CREATE VARIABLE syntax to create a connection-scope variable that is available in the context of the
connection.

Use the CREATE DATABASE VARIABLE syntax to create a database-scope variable that can be used by other
users and other connections.

Use the OR REPLACE clause as an alternative to the VAREXISTS function in SQL scripts.

If you specify a variable name for <initial-value>, then the variable must already be initialized in the
database.

Local variables in procedures and triggers are declared within a compound statement.

Privileges

(back to top)

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Scope Privilege Required

Connection-scope variables No privileges are required to create or replace a connection-scope variable.

Database-scope variables To create or replace a self-owned database-scope variable requires one of:

● CREATE DATABASE VARIABLE system privilege


● MANAGE ANY DATABASE VARIABLE system privilege

To create or replace a database-scope variable owned by another user or by


PUBLIC requires the MANAGE ANY DATABASE VARIABLE system privilege.

Side Effects

(back to top)

● Connection-scope variables – there are no side effects associated with creating a connection-scope
variable.
● Database-scope variables – creating and replacing a database-scope variable causes an automatic
commit.

SAP IQ SQL Reference


1406 INTERNAL SQL Statements
Standards

(back to top)

SQL – not in the ISO/ANSI SQL standard

Examples

(back to top)

● The following example creates (or updates) a database-scope variable called site_name of type
VARCHAR(50).

CREATE OR REPLACE DATABASE VARIABLE @site_name VARCHAR(50);

● The following example creates (or updates) a database-scope variable owned by PUBLIC called
database_name of type CHAR(66) and sets it to the special value CURRENT DATABASE.

CREATE OR REPLACE DATABASE VARIABLE PUBLIC.@database_name CHAR(66) DEFAULT


CURRENT DATABASE;

● The following example creates a connection-scope variable named first_name, of data type VARCHAR(50).

CREATE VARIABLE first_name VARCHAR(50);

● The following example creates a connection-scope variable named birthday, of data type DATE.

CREATE VARIABLE birthday DATE;

● The following example creates a connection-scope variable named v1 as an INT with the initial setting of 5.

CREATE VARIABLE v1 INT = 5;

● The following example creates a connection-scope variable named v1 and sets its value to 10, regardless of
whether the v1 variable already exists.

CREATE OR REPLACE VARIABLE v1 INT = 10;

● The following example creates a connection-scope variable, ProductID, and uses the %TYPE attribute to
set its data type to the data type of the ID column in the Products table:

CREATE VARIABLE ProductID Products.ID%TYPE;

● The following example creates a connection-scope variable, ItemsForSale, and uses the %ROWTYPE
attribute to set its data type to a composite data type comprised of the columns defined for the Products
table. It then creates another variable, ItemID, and declares its type to be the data type of the ID column in
the ItemsForSale variable:

CREATE VARIABLE ItemsForSale Products%ROWTYPE;


CREATE VARIABLE ItemID ItemsForSale.ID%TYPE;

● The following example this code fragment inserts a large text value into the database:

EXEC SQL BEGIN DECLARE SECTION;


char buffer[5000];
EXEC SQL END DECLARE SECTION;

SAP IQ SQL Reference


SQL Statements INTERNAL 1407
EXEC SQL CREATE VARIABLE hold_blob VARCHAR;
EXEC SQL SET hold_blob = '';
for(;;) {
/* read some data into buffer ... */
size = fread( buffer, 1, 5000, fp );
if( size <= 0 ) break;
/* add data to blob using concatenation
Note that concatenation works for binary
data too! */
EXEC SQL SET hold_blob = hold_blob || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES ( 1, hold_blob );
EXEC SQL DROP VARIABLE hold_blob;

Related Information

%TYPE and %ROWTYPE attributes [page 93]


BEGIN … END Statement [page 1218]
DECLARE Statement [page 1413]
DROP VARIABLE statement [page 1466]
SET Statement [ESQL] [page 1670]
REVOKE System Privilege Statement [page 1635]

9.4.71 CREATE VIEW Statement

Creates a view on the database. Views are used to give a different perspective on the data even though it is not
stored that way.

 Syntax

CREATE [ OR REPLACE ] VIEW


… [ <owner>.]<view-name> [ ( <column-name> [ , … ] ) ]
… AS <select-without>-<order-by>
… [ WITH CHECK OPTION ]

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

SAP IQ SQL Reference


1408 INTERNAL SQL Statements
OR REPLACE

Replaces an existing view with the same name. Existing permissions are preserved , but INSTEAD OF
triggers on the view are dropped.
view-name

The default owner of a view is the current user ID. A view name can be used in place of a table name in
SELECT, DELETE, UPDATE, and INSERT statements. Views, however, do not physically exist in the database
as tables. They are derived each time they are used. The view is derived as the result of the SELECT
statement specified in the CREATE VIEW statement. Table names used in a view should be qualified by the
user ID of the table owner. Otherwise, a different user ID might not be able to find the table or might get the
wrong table.
AS

The SELECT statement on which the view is based must not contain an ORDER BY clause, a subquery in
the SELECT list, or a TOP or FIRST qualification. It may have a GROUP BY clause and may be a UNION.
WITH CHECK OPTION

Rejects any updates and inserts to the view that do not meet the criteria of the views as defined by its
SELECT statement. However, SAP IQ currently ignores this option (it supports the syntax for compatibility
reasons).

Remarks

(back to top)

You cannot add or drop IDENTIFY or AUTOINCREMENT columns from a view.

Views can be updated unless the SELECT statement defining the view contains a GROUP BY clause, an
aggregate function, or involves a UNION operation. An update to the view causes the underlying tables to be
updated.

Privileges

(back to top)

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

View Type Ownership Privilege Required

View Self Requires the CREATE VIEW system privilege along with one of:

● SELECT ANY TABLE system privilege.


● SELECT object-level permission on the underlying tables of the
view.

SAP IQ SQL Reference


SQL Statements INTERNAL 1409
View Type Ownership Privilege Required

Other user ● CREATE ANY VIEW system privilege.


● CREATE ANY OBJECT system privilege.

Also requires:

● SELECT ANY TABLE system privilege.


● SELECT object-level privilege on the underlying tables of the
view.

Materialize View Self Requires CREATE MATERIALIZED VIEW system privilege. Also re­
quires one of:

● CREATE ANY OBJECT system privilege.


● CREATE object-privilege on the dbspace where the material­
ized view is being created.

Also requires one of:

● SELECT ANY TABLE system privilege.


● SELECT object-privilege on the underlying tables of the materi­
alized view.

Other User Requires one of:

● CREATE ANY MATERIALIZED VIEW system privilege.


● CREATE ANY OBJECT system privilege.

Also requires one of:

● CREATE ANY OBJECT system privilege.


● CREATE object-level privilege on the dbspace where the mate­
rialized view is being created.

And also requires one of:

● SELECT ANY TABLE system privilege.


● SELECT object-level privilege on the underlying tables of the
materialized view.

Side Effects

(back to top)

Automatic commit

Standards

(back to top)

SAP IQ SQL Reference


1410 INTERNAL SQL Statements
● SQL – vendor extension to ISO/ANSI SQL grammar
● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example creates a view showing all information for male employees only. This view has the
same column names as the base table:

CREATE VIEW male_employee


AS SELECT *
FROM Employees
WHERE Sex = 'M'

● The following example creates a view showing employees and the departments to which they belong:

CREATE VIEW emp_dept


AS SELECT Surname, GivenName, DepartmentName
FROM Employees JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID

Related Information

CREATE TABLE Statement [page 1377]


DROP Statement [page 1433]
SELECT Statement [page 1659]
REVOKE System Privilege Statement [page 1635]

9.4.72 DEALLOCATE DESCRIPTOR Statement [ESQL]

Frees memory associated with a SQL descriptor area.

 Syntax

DEALLOCATE DESCRIPTOR <descriptor-name>:


<string>

Remarks

Frees all memory associated with a descriptor area, including the data items, indicator variables, and the
structure itself.

SAP IQ SQL Reference


SQL Statements INTERNAL 1411
Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

Examples

See ALLOCATE DESCRIPTOR Statement [ESQL].

Related Information

ALLOCATE DESCRIPTOR Statement [ESQL] [page 1131]


SET DESCRIPTOR Statement [ESQL] [page 1676]
REVOKE System Privilege Statement [page 1635]

9.4.73 Declaration Section [ESQL]

Declares host variables in an Embedded SQL program. Host variables are used to exchange data with the
database.

 Syntax

EXEC SQL BEGIN DECLARE SECTION;


... <C declarations>
EXEC SQL END DECLARE SECTION;

Remarks

A declaration section is 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.

SAP IQ SQL Reference


1412 INTERNAL SQL Statements
Privileges

None

Standards

SQL – vendor extension to ISO/ANSI SQL grammar

Examples

EXEC SQL BEGIN DECLARE SECTION;


char *emp_lname, initials[5];
int dept;
EXEC SQL END DECLARE SECTION;

Related Information

BEGIN … END Statement [page 1218]


REVOKE System Privilege Statement [page 1635]

9.4.74 DECLARE Statement

Declares a SQL variable within a compound statement (BEGIN... END).

 Syntax

DECLARE
<variable_name> [ , … ]
<data-type> [{
=
| DEFAULT}
<initial-value>]

<initial-value> ::=
<special-value>
| <string>
| [ - ] <number>
| ( <constant-expression> )
| <built-in-function> ( <constant-expression> )
| NULL

<special-value> ::=
CURRENT

SAP IQ SQL Reference


SQL Statements INTERNAL 1413
{ DATABASE
| DATE
| PUBLISHER
| TIME
| TIMESTAMP
| USER
| UTC TIMESTAMP }
| USER

Parameters

initial-value

The variable is set to that value. The data type must match the type defined by <data-type>. If you do not
specify an initial-value, the variable contains the NULL value until a SET statement assigns a different
value.
data-type

Set the data type explicitly, or you can set it by using the %TYPE or %ROWTYPE attribute. Use %TYPE to
set it to the data type of a variable or a column in a table or view. Use %ROWTYPE to set the data type to a
composite data type derived from a row in a cursor, table, or view.

Remarks

Use the DECLARE statement to declare variables used in the body of a procedure. The variable persists for the
duration of the compound statement in which it is declared and must be unique within the compound
statement.

The body of a procedure is a compound statement, and variables must be declared immediately following
BEGIN. In a Transact-SQL procedure or trigger, there is no such restriction.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – compatible with SAP Adaptive Server Enterprise.
○ To be compatible with SAP ASE, the variable name must be preceded by an @.
○ In SAP ASE, a variable that is declared in a procedure or trigger exists for the duration of the procedure
or trigger. In SAP IQ, if a variable is declared inside a compound statement, it exists only for the

SAP IQ SQL Reference


1414 INTERNAL SQL Statements
duration of that compound statement (whether it is declared in an SAP IQ SQL or Transact-SQL
compound statement).

Examples

The following example illustrates the use of the DECLARE statement and prints a message on the server
window:

BEGIN
DECLARE varname CHAR(61);
SET varname = 'Test name';
MESSAGE varname;
END

Related Information

%TYPE and %ROWTYPE attributes [page 93]


BEGIN … END Statement [page 1218]
REVOKE System Privilege Statement [page 1635]

9.4.75 DECLARE CURSOR Statement [ESQL] [SP]

Declares a cursor. Cursors are the primary means for manipulating the results of queries.

 Syntax

DECLARE <cursor-name>
[ SCROLL
| NO SCROLL
| DYNAMIC SCROLL
]
CURSOR FOR
{ <select-statement> FOR <for-clause>
| <statement-name>
| USING <variable-name> }

<for-clause> ::=
READ ONLY | UPDATE

Go to:

● Remarks
● Privileges
● Standards
● Examples

SAP IQ SQL Reference


SQL Statements INTERNAL 1415
Parameters

(back to top)

statement-name

Identifier or host-variable. Statements are named using the PREPARE statement. Cursors can be declared
only for a prepared SELECT or CALL.
SCROLL

A cursor declared as SCROLL supports the NEXT, PRIOR, FIRST, LAST, ABSOLUTE, and RELATIVE options
of the FETCH statement. A SCROLL cursor lets you fetch an arbitrary row in the result set while the cursor
is open.
NO SCROLL

A cursor declared as NO SCROLL is restricted to moving forward through the result set using only the
FETCH NEXT and FETCH ABSOLUTE (0) seek operations.
DYNAMIC SCROLL

A cursor declared as DYNAMIC SCROLL supports the NEXT, PRIOR, FIRST, LAST, ABSOLUTE, and
RELATIVE clauses of the FETCH statement. A DYNAMIC SCROLL cursor lets you fetch an arbitrary row in
the result set while the cursor is open.

Since rows cannot be returned to once the cursor leaves the row, there are no sensitivity restrictions on the
cursor. Consequently, when a NO SCROLL cursor is requested, SAP IQ supplies the most efficient kind of
cursor, which is an asensitive cursor.
READ ONLY

(Default) A cursor declared FOR READ ONLY may not be used in a positioned UPDATE or a positioned
DELETE operation.

A cursor declared FOR READ ONLY sees the version of table(s) on which the cursor is declared when the
cursor is opened, not the version of table(s) at the time of the first FETCH.

For example, when the cursor is fetched, only one row can be fetched from the table:

CREATE TABLE t1 ( c1 INT );


INSERT t1 VALUES ( 1 );
BEGIN
DECLARE t1_cursor CURSOR FOR SELECT * FROM t1
FOR READ ONLY;
OPEN t1_cursor;
INSERT t1 VALUES ( 2 );
FETCH T1_CURSOR;
END

UPDATE

You can update the cursor result set of a cursor declared FOR UPDATE. Only asensitive behavior is
supported for updatable cursors; any other sensitivity is ignored.

When the cursor is opened, exclusive table locks are taken on all tables that are opened for update.
Standalone LOAD TABLE, UPDATE, INSERT, DELETE, and TRUNCATE statements are not allowed on tables
that are opened for update in the same transaction, since SAP IQ permits only one statement to modify a
table at a time. You can open only one updatable cursor on a specific table at a time.

Updatable cursors are allowed to scroll, except over Open Client.

SAP IQ SQL Reference


1416 INTERNAL SQL Statements
USING

You can declare a cursor on a variable in stored procedures and user-defined functions. 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:

create function get_row_count(in qry varchar)


returns int
begin
declare crsr cursor using qry;
declare rowcnt int;
set rowcnt = 0;
open crsr;
lp: loop
fetch crsr;
if SQLCODE <> 0 then leave lp end if;
set rowcnt = rowcnt + 1;
end loop;
return rowcnt;
end

A parameter to the procedure. For example:

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 varchar;
set qry = 'select table_name from SYS.ISYSTAB ' ||
'where table_id=' || string(id_value);
begin
declare crsr cursor using qry;
open crsr;
fetch crsr into tabname;
close crsr;
end
end

Remarks

(back to top)

The DECLARE CURSOR statement declares a cursor with the specified name for a SELECT statement or a CALL
statement.

Embedded SQL statements are named using the PREPARE statement. Cursors can be declared only for a
prepared SELECT or CALL.

SAP IQ supports updatable cursors on single tables.

SAP IQ supports one type of cursor sensitivity, which is defined in terms of which changes to underlying data
are visible. All SAP IQ cursors are asensitive, which means that changes might be reflected in the membership,
order, or values of the result set seen through the cursor, or might not be reflected at all.

With an asensitive cursor, changes effected by positioned UPDATE and positioned DELETE statements are
visible in the cursor result set, except where client-side caching prevents seeing these changes. Inserted rows
are not visible.

SAP IQ SQL Reference


SQL Statements INTERNAL 1417
Rows that are updated so that they no longer meet the requirements of the WHERE clause of the open cursor
are still visible.

When using cursors, there is always a trade-off between efficiency and consistency. Asensitive cursors provide
efficient performance at the expense of consistency.

LONG VARCHAR and LONG BINARY data types are not supported in updatable cursors.

Scalar user-defined functions and user-defined aggregate functions are not supported in updatable cursors.

Supported query specifications for updatable cursors in SAP IQ are:

● Expressions in the select list against columns that are not functionally dependent on columns being
updated
● Arbitrary subqueries with asensitive behavior, that is, changes to data referenced by subqueries are not
visible in the cursor result set
● ORDER BY clause; the ORDER BY columns may be updated, but the result set does not reorder
● Columns that meet these requirements:
○ No CAST on a column
○ Base columns of a base table in the SELECT clause
○ There are no expressions or functions on that column in the SELECT clause and it is not duplicated in
the select list (for example, SELECT c1, c1).
○ Base columns of a base table restricted to those listed in the FOR UPDATE OF <column-name-
list> clause, if the clause is specified.

SAP IQ does not permit updatable cursors on queries that contain any operator that precludes a one-to-one
mapping of result set rows to rows in a base table; specifically:

● SELECT DISTINCT
● Operator that has a UNION
● Operator that has a GROUP BY
● Operator that has a SET function
● Operator that has an OLAP function, with the exception of RANK()

See the description of the UPDATE (positioned) Statement [ESQL] [SP] for information on the columns and
expressions allowed in the SET clause for the update of a row in the result set of a cursor.

SAP IQ supports inserts only on updatable cursors where all nonnullable, nonidentity columns are both
selected and updatable.

In SAP IQ, COMMIT and ROLLBACK are not allowed inside an open updatable cursor, even if the cursor is opened
as a hold cursor. SAP IQ does support ROLLBACK TO SAVEPOINT inside an updatable cursor.

Any failure that occurs after the cursor is open results in a rollback of all operations that have been performed
through this open cursor.

Updatable Cursor Limitations

A declared cursor is read-only and not updatable in cases where:

● The data extraction facility is enabled with the TEMP_EXTRACT_NAME1 option set to a pathname
● ANSI_CLOSE_CURSORS_ON_ROLLBACK is set OFF
● CHAINED is set OFF
● The statement is INSERT SELECT or SELECT INTO

SAP IQ SQL Reference


1418 INTERNAL SQL Statements
● More than one table is included
● No updatable columns exist

If SAP IQ fails to set an updatable cursor when requested, see the .iqmsg file for related information.

There is a limitation regarding updatable cursors and ODBC. A maximum of 65535 rows or records can be
updated, deleted, or inserted at a time using these ODBC functions:

● SQLSetPos SQL_UPDATE, SQL_DELETE, and SQL_ADD


● SQLBulkOperations SQL_ADD, SQL_UPDATE_BY_BOOKMARK, and SQL_DELETE_BY_BOOKMARK

There is an implementation-specific limitation to the maximum value in the statement attribute that controls
the number of effected rows to the largest value of an UNSIGNED SMALL INT, which is 65535:

SQLSetStmtAttr(HANDLE,SQL_ATTR_ROW_ARRAY_SIZE, VALUE,0)

SAP IQ updatable cursors differ from ANSI SQL3 standard behavior as follows:

● Hold cursor update close on commit.


● SAP IQ locks tables when the cursor is open.
● All updates, deletes, and insert operations are applied when the cursor is closed, in this order: deletes first,
then updates, then inserts.

 Note

Use the sp_iqcursorinfo system procedure to display detailed information about cursors currently
open on the server.

Privileges

(back to top)

None

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

Examples

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1419
● The following example declares a scroll cursor in Embedded SQL:

EXEC SQL DECLARE cur_employee SCROLL CURSOR


FOR SELECT * FROM Employees;

● The following example declares a cursor for a prepared statement in Embedded SQL:

EXEC SQL PREPARE employee_statement


FROM 'SELECT emp_lname FROM Employees';
EXEC SQL DECLARE cur_employee CURSOR
FOR employee_statement ;

● The following example uses cursors in a stored procedure:

BEGIN
DECLARE cur_employee CURSOR FOR
SELECT emp_lname
FROM Employees;
DECLARE name CHAR(40);
OPEN cur_employee;
LOOP
FETCH NEXT cur_employee INTO name;
...
END LOOP;
CLOSE cur_employee;
END

Related Information

CALL Statement [page 1225]


DELETE (Positioned) Statement [ESQL] [SP] [page 1427]
FETCH Statement [ESQL] [SP] [page 1475]
OPEN Statement [ESQL] [SP] [page 1582]
PREPARE Statement [ESQL] [page 1590]
SELECT Statement [page 1659]
UPDATE (Positioned) Statement [ESQL] [SP] [page 1705]
REVOKE System Privilege Statement [page 1635]

9.4.76 DECLARE CURSOR Statement [T-SQL]

Declares a cursor that is compatible with SAP Adaptive Server Enterprise.

 Syntax

DECLARE <cursor-name>
… CURSOR FOR <select-statement>
…[ FOR { READ ONLY | UPDATE } ]

SAP IQ SQL Reference


1420 INTERNAL SQL Statements
Remarks

SAP IQ supports a DECLARE CURSOR syntax that is not supported in SAP ASE. For information on the full
DECLARE CURSOR syntax, see DECLARE CURSOR Statement [ESQL] [SP].

 Note

Use the sp_iqcursorinfo system procedure to display detailed information about cursors currently
open on the server.

Privilege

None

Standards

● SQL – the FOR UPDATE and FOR READ ONLY options are Transact-SQL extensions to ISO/ANSI SQL
grammar.
● SAP database products – there are some features of the SAP ASE DECLARE CURSOR statement that are
not supported in SAP IQ.
○ In the SAP IQ dialect, DECLARE CURSOR in a procedure or batch must immediately follow the BEGIN
keyword. In the Transact-SQL dialect, there is no such restriction.
○ In SAP ASE, when a cursor is declared in a procedure or batch, it exists for the duration of the
procedure or batch. In SAP IQ, if a cursor is declared inside a compound statement, it exists only for
the duration of that compound statement (whether it is declared in an SAP IQ or Transact-SQL
compound statement).

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


sp_iqcursorinfo Procedure [page 628]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1421
9.4.77 DECLARE LOCAL TEMPORARY TABLE Statement

Declares a local temporary table.

 Syntax

DECLARE LOCAL TEMPORARY TABLE <table-name>


… ( <column-definition> [ <column-constraint> ] …
[ , <column-definition> [ <column-constraint> ] … ]
[ , <table-constraint> ] … )
…[ ON COMMIT { DELETE | PRESERVE } ROWS
]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Remarks

(back to top)

DECLARE LOCAL TEMPORARY TABLE declares a temporary table.

A local temporary table and the rows in it are visible only to the connection that created the table and inserted
the rows. By default, the rows of a temporary table are deleted on COMMIT.

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.

See CREATE TABLE Statement for definitions of <column-definition>, <column-constraint>, and


<table-constraint> syntax. See SELECT Statement for an example of how to select data into a temporary
table.

Once you create a local temporary table, either implicitly or explicitly, you cannot create another temporary
table of that name for as long as the temporary table exists. For example, you can create a local temporary
table implicitly:

select * into #tmp from table1

Alternatively, you can create a local temporary table with an explicit by declaration:

declare local temporary table foo

Then if you try to select into #tmp or foo, or declare #tmp or foo again, you receive an error indicating that
#tmp or foo already exists.

SAP IQ SQL Reference


1422 INTERNAL SQL Statements
When you declare a local temporary table, omit the owner specification. If you specify the same owner.table
in more than one DECLARE LOCAL TEMPORARY TABLE statement in the same session, a syntax error is
reported. For example, an error is reported when these statements are executed in the same session:

DECLARE LOCAL TEMPORARY TABLE user1.temp(col1 int);


DECLARE LOCAL TEMPORARY TABLE user1.temp(col1 int);

If the owner name is omitted, then the error Item temp already exists is reported:

DECLARE LOCAL TEMPORARY TABLE temp(col1 int);


DECLARE LOCAL TEMPORARY TABLE temp(col1 int);

An attempt to create a base table or a global temporary table fails, if a local temporary table of the same name
exists on that connection, as the new table cannot be uniquely identified by <owner.table>.

You can, however, create a local temporary table with the same name as an existing base table or global
temporary table. References to the table name access the local temporary table, as local temporary tables are
resolved first.

For example, consider this sequence:

CREATE TABLE t1 (c1 int);


INSERT t1 VALUES (9);
DECLARE LOCAL TEMPORARY TABLE t1 (c1 int);
INSERT t1 VALUES (8);
SELECT * FROM t1;

The result returned is 8. Any reference to t1 refers to the local temporary table t1 until the local temporary
table is dropped by the connection.

You cannot use the following on local temporary tables:

● Statements – ALTER TABLE, DROP INDEX.


● Stored procedures – sp_iqindex, sp_iqtablesize, and sp_iqindexsize.

Privileges

(back to top)

None

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Statements INTERNAL 1423
Examples

(back to top)

● The following example declares a local temporary table in Embedded SQL:

EXEC SQL DECLARE LOCAL TEMPORARY TABLE MyTable (


number INT
);

● The following example declares a local temporary table in a stored procedure:

BEGIN
DECLARE LOCAL TEMPORARY TABLE TempTab (
number INT
);
...
END

Related Information

CREATE TABLE Statement [page 1377]


SELECT Statement [page 1659]
REVOKE System Privilege Statement [page 1635]

9.4.78 DELETE Statement

Deletes all the rows from the named table that satisfy the search condition. If no WHERE clause is specified, all
rows from the named table are deleted.

 Syntax

DELETE
[ FROM ] [ <owner>.]<table-name> [[AS <correlation-name]>
...[ FROM <table-expression> ]
[ WHERE <search-condition> ]]

<table-expression> ::=
<table-spec>
| <table-expression join-type table-spec> [ ON <condition> ]
| <table-expression>, ...

Go to:

● Remarks
● Privileges
● Standards
● Examples

SAP IQ SQL Reference


1424 INTERNAL SQL Statements
Parameters

(back to top)

FROM clause

Indicates the table from which rows will be deleted. The optional second FROM clause in the DELETE
statement determines the rows to be deleted from the specified table based on joins with other tables. If
the second FROM clause is present, the WHERE clause qualifies the rows of this second FROM clause.
Rows are deleted from the table name given in the first FROM clause.

 Note

You cannot use the DELETE statement on a join virtual table. If you attempt to delete from a join virtual
table, an error is reported.

WHERE clause

If specified, only rows satisfying the search condition are deleted. If no WHERE clause is specified, every
row is deleted.

Remarks

(back to top)

DELETE can be used on views provided the SELECT statement defining the view has only one table in the FROM
clause and does not contain a GROUP BY clause, an aggregate function, or involve a UNION operation.

If the same table name from which you are deleting rows is used in both FROM clauses, they are considered to
reference the same table if one of the following is true:

● Both table references are not qualified by specifying a user ID


● Both table references are qualified by specifying a user ID
● Both table references are specified with a correlation name

In cases where the server cannot determine if the table references are identical, an error appears. This prevents
the user from unintended semantics by deleting unintended rows.

Potential Ambiguity in Table Names


There is a potential ambiguity in table names in DELETE statements when the FROM clauses do not both use
correlation names. Consider this example:

DELETE
FROM table_1
FROM table_1 AS alias_1, table_2 AS alias_2
WHERE ...

table_1 is identified without a correlation name in the first FROM clause, but with a correlation name in the
second FROM clause. The use of a correlation name for table_1 in the second FROM clause ensures that only
one instance of table_1 exists in the statement. This is an exception to the general rule that where the same
table is identified with and without a correlation name in the same statement, two instances of the table are
considered.

SAP IQ SQL Reference


SQL Statements INTERNAL 1425
Now consider this example:

DELETE
FROM table_1
FROM table_1 AS alias_1, table_1 AS alias_2
WHERE ...

There are two instances of table_1 in the second FROM clause. Since there is no way to identify which
instance the first FROM clause should be identified with, the general rule of correlation names means that
table_1 in the first FROM clause is identified with neither instance of table_1 in the second clause: there are
three instances of table_1 in the statement.

Privileges

(back to top)

Requires the DELETE object-level privilege on the table. See GRANT Object-Level Privilege Statement [page
1502] for assistance with granting privileges

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – supported by SAP Adaptive Server Enterprise, including the vendor extension.

Examples

(back to top)

● The following example removes employee 105 from the database:

DELETE
FROM Employees
WHERE EmployeeID = 105

● The following example removes all data prior to 1993 from the FinancialData table:

DELETE
FROM FinancialData
WHERE Year < 1993

● The following example removes all names from the Contacts table if they are already present in the
Customers table:

DELETE
FROM Contacts
FROM Contacts, Customers
WHERE Contacts.Surname = Customers.Surname

SAP IQ SQL Reference


1426 INTERNAL SQL Statements
AND Contacts.GivenName = Customers.GivenName

Related Information

Row Limitation Clauses in SELECT Query Blocks [page 1669]


FROM Clause [page 1483]
INSERT Statement [page 1534]
TRUNCATE Statement [page 1695]
REVOKE System Privilege Statement [page 1635]

9.4.79 DELETE (Positioned) Statement [ESQL] [SP]

Deletes the data at the current location of a cursor.

 Syntax

DELETE [ FROM <table-spec> ]


WHERE CURRENT OF <cursor-name>

<table-spec> ::=
[ <owner>.]<correlation-name>

<cursor-name> ::=
<identifier> | <hostvar>

Parameters

FROM

The table FROM which rows are deleted is determined as follows:

● If no FROM clause is included, the cursor can only be on a single table.


● If the cursor is for a joined query (including using a view containing a join), you must use the FROM
clause. Only the current row of the specified table is deleted. The other tables involved in the join are
not affected.
● If you include a FROM clause and do not specify table owner, table-spec is first matched against any
correlation names.
○ If a correlation name exists, table-spec is identified with the correlation name.
○ If a correlation name does not exist, table-spec must be unambiguously identifiable as a table
name in the cursor.
● If a FROM clause is included, and a table owner is specified, table-spec must be unambiguously
identifiable as a table name in the cursor.

SAP IQ SQL Reference


SQL Statements INTERNAL 1427
Remarks

This form of the DELETE statement deletes the current row of the specified cursor. The current row is defined
to be the last row fetched from the cursor.

The positioned DELETE statement can be used on a cursor open on a view as long as the view is updatable.

Changes effected by positioned DELETE statements are visible in the cursor result set, except where client-side
caching prevents seeing these changes.

Privileges

Requires DELETE object-level privilege on tables used in the cursor. See GRANT Object-Level Privilege
Statement [page 1502] for assistance with granting privileges

Standards

● SQL – the range of cursors that can be updated may contain vendor extensions to ISO/ANSI SQL grammar
if the ANSI_UPDATE_CONSTRAINTS option is set to OFF.
● SAP database products – Embedded SQL use is supported by Open Client/Open Server. Procedure and
trigger use is supported in SAP SQL Anywhere.

Examples

The following example removes the current row from the database:

DELETE WHERE CURRENT OF cur_employee

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


INSERT Statement [page 1534]
UPDATE Statement [page 1700]
UPDATE (Positioned) Statement [ESQL] [SP] [page 1705]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1428 INTERNAL SQL Statements
9.4.80 DESCRIBE Statement [ESQL]

Gets information about the host variables required to store data retrieved from the database or host variables
used to pass data to the database.

 Syntax

DESCRIBE
…[ USER TYPES ]
…[ { ALL | BIND VARIABLES FOR | INPUT
| OUTPUT | SELECT LIST FOR } ]
…[ { LONG NAMES [ <long-name-spec> ] | WITH VARIABLE RESULT } ]
…[ FOR ] { <statement-name> | CURSOR <cursor-name> }
…INTO <sqlda-name>

<long-name-spec> ::=
{ OWNER.TABLE.COLUMN
| TABLE.COLUMN
| COLUMN }

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

USER TYPES

Returns information about user-defined data types 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 clause, except that the
sqlname field holds the name of the user-defined data type, instead of the name of the column.

If DESCRIBE uses the LONG NAMES clause, the sqldata field holds this information.
ALL

Describes INPUT and OUTPUT with one request to the database server. This has a performance benefit in
a multiuser environment. The INPUT information is filled in the SQLDA first, followed by the OUTPUT
information. The sqld field contains the total number of INPUT and OUTPUT variables. The
DT_DESCRIBE_INPUT bit in the indicator variable is set for INPUT variables and clear for OUTPUT
variables.
BIND VARIABLES FOR

Equivalent to the INPUT clause. When used with the INPUT clause, DESCRIBE BIND VARIABLES does not
set up the data types in the SQLDA: this needs to be done by the application.
INPUT

SAP IQ SQL Reference


SQL Statements INTERNAL 1429
Fills in the name fields in the SQLDA with the bind variable names. 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. INPUT clause also puts the number of bind variables in the sqld field of the SQLDA.

DESCRIBE uses the indicator variables in the SQLDA to provide additional information.
DT_PROCEDURE_IN and DT_PROCEDURE_OUT are bits that are set in the indicator variable when a CALL
statement is described. DT_PROCEDURE_IN indicates an IN or INOUT parameter and
DT_PROCEDURE_OUT indicates an INOUT or OUT parameter. Procedure RESULT columns 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 sets DT_PROCEDURE_IN and DT_PROCEDURE_OUT appropriately only when a bind
variable is an argument to a CALL statement; bind variables within an expression that is an argument in a
CALL statement sets the bits.
OUTPUT

Fills in the data type and length in the SQLDA for each select list item. 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 is that alias. Otherwise,
the name derives 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 also puts 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, DESCRIBE OUTPUT 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, OUTPUT fills in the data type, length, and name in
the SQLDA for each RESULT column in the procedure definition. DESCRIBE OUTPUT also puts the
number of result columns in the sqld field of the SQLDA.
SELECT LIST FOR

Equivalent to the OUTPUT clause.


LONG NAMES [ long-name-spec ]

Retrieves 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. The
default specification for the long names is TABLE.COLUMN.
WITH VARIABLE RESULT

Describes procedures that might 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 these values:

● 0 – the result set may change. The procedure call should be described again following each OPEN
statement.
● 1 – the result set is fixed. You need not describe again.
statement-name

SAP IQ SQL Reference


1430 INTERNAL SQL Statements
Identifier or host-variable. If you specify a statement name, the statement must have been previously
prepared using the PREPARE statement with the same statement name and the SQLDA must have been
previously allocated (see ALLOCATE DESCRIPTOR Statement [ESQL]).
CURSOR cursor-name

Declared cursor. 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.
INTO sqlda-name

Identifier

Remarks

(back to top)

DESCRIBE sets up the named SQLDA to describe either the OUTPUT (equivalently SELECT LIST) or the
INPUT (BIND VARIABLES) for the named statement.

Privileges

(back to top)

None

Standards

(back to top)

The following applies to some clauses:

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

Examples

(back to top)

● The following example shows how to use the DESCRIBE statement:

sqlda = alloc_sqlda( 3 );
EXEC SQL DESCRIBE OUTPUT
FOR employee_statement

SAP IQ SQL Reference


SQL Statements INTERNAL 1431
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;
}

Related Information

ALLOCATE DESCRIPTOR Statement [ESQL] [page 1131]


DECLARE CURSOR Statement [ESQL] [SP] [page 1415]
OPEN Statement [ESQL] [SP] [page 1582]
PREPARE Statement [ESQL] [page 1590]
REVOKE System Privilege Statement [page 1635]

9.4.81 DISCONNECT Statement [Interactive SQL]

Drops a connection with the database.

 Syntax

DISCONNECT [ { <connection-name> | CURRENT | ALL } ]

Parameters

ALL

Drops all of the connections of the application to all database environments.


CURRENT

(Default) drops the current connection.

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.

An implicit ROLLBACK is executed on connections that are dropped.

SAP IQ SQL Reference


1432 INTERNAL SQL Statements
Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

● The following example uses DISCONNECT in Embedded SQL:

EXEC SQL DISCONNECT :conn_name

● The following example uses DISCONNECT from dbisql to disconnect all connections:

DISCONNECT ALL

Related Information

CONNECT Statement [ESQL] [Interactive SQL] [page 1241]


SET CONNECTION Statement [ESQL] [Interactive SQL] [page 1675]
REVOKE System Privilege Statement [page 1635]

9.4.82 DROP Statement

Removes objects from the database.

 Syntax

DROP
{ DBSPACE <dbspace-name>
| { DATATYPE [ IF EXISTS ]
| DOMAIN } <datatype-name>
| EVENT [ IF EXISTS ] <event-name>
| INDEX [ IF EXISTS ] [ [ <owner>].<table-name>.]<index-name>
| MESSAGE <message-number>
| TABLE [ IF EXISTS ] [ <owner>.]<table-name>
| VIEW [ IF EXISTS ] [ <owner>.]<view-name>
| MATERIALIZED VIEW [ IF EXISTS ] [ <owner>.]<view-name>
| PROCEDURE [ IF EXISTS ] [ <owner>.]<procedure-name>
| FUNCTION [ IF EXISTS ] [ <owner>.]<function-name> }

SAP IQ SQL Reference


SQL Statements INTERNAL 1433
Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

DBSPACE

DROP DBSPACE is prevented whenever the statement affects a table that is currently being used by
another connection.
IF EXISTS

Use if you do not want an error returned when the DROP statement attempts to remove a database object
that does not exist.
INDEX

DROP INDEX deletes any explicitly created index. It deletes an implicitly created index only if there are no
unique or foreign-key constraints or associated primary key.

DROP INDEX is prevented whenever the statement affects a table that is currently being used by another
connection.

For a nonunique HG index, DROP INDEX fails if an associated unenforced foreign key exists.

 Caution

Do not delete views owned by the DBO user. Deleting such views or changing them into tables might
cause problems.

TABLE

DROP TABLE is prevented whenever the statement affects a table that is currently being used by another
connection or if the primary table has foreign-key constraints associated with it, including unenforced
foreign-key constraints. It is also prevented if the table has an IDENTITY column and IDENTITY_INSERT is
set to that table. To drop the table, you must clear IDENTITY_INSERT, that is, set IDENTITY_INSERT to '
' (an empty string), or set to another table name.

A foreign key can have either a nonunique single or a multicolumn HG index. A primary key may have
unique single or multicolumn HG indexes. You cannot drop the HG index implicitly created for an existing
foreign key, primary key, and unique constraint.

The four initial dbspaces are SYSTEM, IQ_SYSTEM_MAIN, IQ_SYSTEM_TEMP, and IQ_SYSTEM_MSG. You
cannot drop these initial dbspaces, but you may drop dbspaces from the IQ main store or catalog store,
which may contain multiple dbspaces, as long as at least one dbspace remains with readwrite mode.

You must drop tables in the dbspace before you can drop the dbspace. An error is returned if the dbspace
still contains user data; other structures are automatically relocated when the dbspace is dropped. You can
drop a dbspace only after you make it read-only.

SAP IQ SQL Reference


1434 INTERNAL SQL Statements
 Note

A dbspace may contain data at any point after it is used by a command, thereby preventing a DROP
DBSPACE on it.

In a multiplex, dropping of RLV-enabled tables is only allowed on the coordinator.


PROCEDURE

DROP PROCEDURE is prevented when the procedure is in use by another connection.


DATATYPE

DROP DATATYPE is prevented if the data type is used in a table. You must change data types on all columns
defined on the user-defined data type to drop the data type. It is recommended that you use DROP DOMAIN
rather than DROP DATATYPE, as DROP DOMAIN is the syntax used in the ANSI/ISO SQL3 draft.

Remarks

(back to top)

DROP removes the definition of the indicated database structure. If the structure is a dbspace, then all tables
with any data in that dbspace must be dropped or relocated prior to dropping the dbspace; other structures
are automatically relocated. If the structure is a table, all data in the table is automatically deleted as part of the
dropping process. Also, all indexes and keys for the table are dropped by DROP TABLE.

Global temporary tables cannot be dropped unless all users that have referenced the temporary table have
disconnected.

Privileges

(back to top)

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

The privilege required varies by clause.

Clause Privilege Required

DBSPACE Requires the DROP ANY OBJECT system privilege and the user must be the
only connection to the database.

DOMAIN Requires one of:

● You own the object


● DROP DATATYPE system privilege
● DROP ANY OBJECT system privilege

SAP IQ SQL Reference


SQL Statements INTERNAL 1435
Clause Privilege Required

FUNCTION Requires one of:

● You own the function


● DROP ANY PROCEDURE system privilege
● DROP ANY OBJECT system privilege

INDEX Requires one of:

● You own the underlying table being indexed.


● DROP ANY INDEX system privilege
● DROP ANY OBJECT system privilege
● REFERENCES object-level privilege on the underlying table being indexed.

DBA or users with the appropriate privilege can drop an index on tables that
are owned other users without using a fully-qualified name. All other users
must provide a fully-qualified index name to drop an index on a base table
owned by the DBA.

MATERIALIZED VIEW Requires one of:

● You own the materialized view


● DROP ANY MATERIALIZED VIEW system privilege
● DROP ANY OBJECT system privilege

PROCEDURE Requires one of:

● You own the procedure


● DROP ANY PROCEDURE system privilege
● DROP ANY OBJECT system privilege

TABLES Requires one of:

● You own the table


● DROP ANY TABLE system privilege
● DROP ANY OBJECT system privilege

VIEW Requires one of:

● You own the view


● DROP ANY VIEW system privilege
● DROP ANY OBJECT system privilege

All other clauses Requires one of:

● You own the object


● DROP ANY OBJECT system privilege

SAP IQ SQL Reference


1436 INTERNAL SQL Statements
Side Effects

(back to top)

● Automatic commit. Clears the Data window in dbisql. DROP TABLE and DROP INDEX close all cursors for
the current connection.
● Local temporary tables are an exception; no commit is performed when one is dropped.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example drop the Departments table from the database:

DROP TABLE Departments

● The following example drop the emp_dept view from the database:

DROP VIEW emp_dept

● The following example drop the myDAS main cache from the simplex or multiplex node you are connected
to:

DROP DBSPACE myDAS

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.83 DROP AGENT Statement


Deletes an SAP IQ agent for SAP IQ Cockpit.

 Syntax

DROP AGENT FOR MULTIPLEX SERVER <server-name>

SAP IQ SQL Reference


SQL Statements INTERNAL 1437
Remarks

Applies to multiplex only.

DROP AGENT removes the association between an SAP IQ agent and a server.

The SYS.ISYSIQMPXSERVERAGENT system table stores the agent connection definitions for the server.

Privileges

Requires the MANAGE MULTIPLEX system privilege.

Side Effects

Automatic commit

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.84 DROP CONNECTION Statement

Drops any user connection to the database.

 Syntax

DROP CONNECTION <connection-id>

Parameters

connection-id

Obtained using the CONNECTION_PROPERTY function to request the connection number. This statement
returns the connection ID of the current connection:

SELECT connection_property( 'number' )

SAP IQ SQL Reference


1438 INTERNAL SQL Statements
Remarks

You cannot drop your current connection; you must first create another connection, then drop your first
connection.

Privileges

Requires the DROP CONNECTION system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example drops the connection with ID number 4:

DROP CONNECTION 4

Related Information

CONNECT Statement [ESQL] [Interactive SQL] [page 1241]


CONNECTION_PROPERTY Function [System] [page 302]
REVOKE System Privilege Statement [page 1635]

9.4.85 DROP DATABASE Statement

Drops a database and its associated dbspace segment files.

 Syntax

DROP DATABASE <db-filename> [ KEY <key-spec> ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1439
Parameters

db-filename

Corresponds to the database file name you defined for the database using CREATE DATABASE. If you
specified a directory path for this value in the CREATE DATABASE command, you must also specify the
directory path for DROP DATABASE. Otherwise, SAP IQ looks for the database files in the default directory
where the server files reside.
key-spec

A string, including mixed cases, numbers, letters, and special characters. It might be necessary to protect
the key from interpretation or alteration by the command shell.

Remarks

DROP DATABASE drops all the database segment files associated with the IQ store and temporary store before
it drops the catalog store files.

You must stop a database before you can drop it. If the connection parameter AUTOSTOP=no is used, you may
need to issue a STOP DATABASE statement.

You cannot execute a DROP DATABASE statement to drop an IQ database that has a DatabaseStart event
defined for it.

Privileges

The permissions required to execute this statement are set using the -gu server command line option, as
follows:

● NONE – No user can issue this statement.


● DBA – Requires the SERVER OPERATOR system privilege.
● UTILITY_DB – Only those users who can connect to the utility_db database can issue this statement.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


1440 INTERNAL SQL Statements
Examples

● The following example drops database mydb:

DROP DATABASE 'mydb.db'

● The following example drops the encrypted database marvin.db, which was created with the key is!
seCret:

DROP DATABASE 'marvin.db' KEY 'is!seCret'

● The following example drops the database temp.db from the /s1/temp directory on a UNIX system:

DROP DATABASE '/s1/temp/temp.db'

Related Information

CREATE DATABASE Statement [page 1245]


STOP DATABASE Statement [Interactive SQL] [page 1690]
REVOKE System Privilege Statement [page 1635]

9.4.86 DROP EXTERNLOGIN Statement

Drops an external login from the SAP IQ system tables.

 Syntax

DROP EXTERNLOGIN <login-name>


TO <remote-server>

Parameters

login-name

Specifies the local user login name.


TO remote-server

Specifies the name of the remote server. The alternate login name of the local user and password for that
server is the external login that is deleted.

SAP IQ SQL Reference


SQL Statements INTERNAL 1441
Remarks

Changes made by DROP EXTERNLOGIN do not take effect until the next connection to the remote server.

 Note

For required parameters that accept variable names, the database server returns an error if any of the
following conditions is true:

● The variable does not exist


● The contents of the variable are NULL
● The variable exceeds the length allowed by the parameter
● The data type of the variable does not match that required by the parameter

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example drops the login dba from the remote database mydb1:

DROP EXTERNLOGIN dba TO mydb1

Related Information

CREATE EXTERNLOGIN Statement [page 1271]

SAP IQ SQL Reference


1442 INTERNAL SQL Statements
REVOKE System Privilege Statement [page 1635]

9.4.87 DROP LDAP SERVER Statement

Removes the named LDAP server configuration object from the SYSLDAPSERVER system view after verifying
that the LDAP server configuration object is not in a READY or ACTIVE state.

 Syntax

DROP LDAP SERVER <ldapua-server-name>


[ WITH DROP ALL REFERENCES ] [ WITH SUSPEND ]

Parameters

WITH DROP ALL REFERENCES

Allows the removal of an LDAP server configuration object from service that has a reference in a login
policy.
WITH SUSPEND

Allows an LDAP server configuration object to be dropped even if in a READY or ACTIVE state.

Remarks

The DROP LDAP SERVER statement fails when it is issued against an LDAP server configuration object that is
in a READY or ACTIVE state. This ensures that an LDAP server configuration object in active use cannot be
accidentally dropped. The DROP LDAP SERVER statement also fails if a login policy exists with a reference to
the LDAP server configuration object.

Privileges

Requires the MANAGE ANY LDAP SERVER system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

SAP IQ SQL Reference


SQL Statements INTERNAL 1443
Examples

In the following example, assuming that references to the LDAP server configuration object have been removed
from all login policies, the following two sets of commands are equivalent:

DROP LDAP SERVER ldapserver1 WITH DROP ALL REFERENCES WITH SUSPEND

ALTER LDAP SERVER ldapserver1 WITH SUSPEND DROP LDAP SERVER ldapserver1 WITH
DROP ALL REFERENCES

Using the WITH DROP ALL REFERENCES and WITH SUSPEND parameters eliminates the need to execute an
ALTER LDAP SERVER statement before the DROP LDAP SERVER statement

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.88 DROP LOGICAL SERVER Statement

Drops a user-defined logical server. This statement enforces consistent shared system temporary store
settings across physical nodes shared by logical servers.

 Syntax

DROP LOGICAL SERVER <logical-server-name>


[ WITH STOP SERVER ]

Parameters

logical-server-name

The name of the logical server.


WITH STOP SERVER

Automatically shuts down all servers in the logical server when the TEMP_DATA_IN_SHARED_TEMP option
is changed directly or indirectly.

Remarks

Applies to multiplex only.

SAP IQ SQL Reference


1444 INTERNAL SQL Statements
SAP IQ performs the following catalog changes internally when dropping a logical server:

● Drops all membership definitions of the logical server.


● Drops its logical server assignment from each login policy that has an explicit assignment to the subject
logical server. If it is the only logical server assigned to the login policy, SAP IQ sets the logical server
assignment for the login policy to NONE.
● Removes the logical server entry from ISYSIQ.LOGICALSERVER.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

The following example drops ls1, a user-defined logical server:

DROP LOGICAL SERVER ls1

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.89 DROP LOGIN POLICY Statement

Removes a login policy from the database.

 Syntax

DROP LOGIN POLICY <policy-name>

Remarks

A DROP LOGIN POLICY statement fails if you attempt to drop a policy that is assigned to a user. You can use
either the ALTER USER statement to change the policy assignment of the user or DROP USER to drop the user.

SAP IQ SQL Reference


SQL Statements INTERNAL 1445
Privileges

Requires the MANAGE ANY LOGIN POLICY system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Examples

The following example creates, then deletes, the Test11 login policy:

CREATE LOGIN POLICY Test11;


DROP LOGIN POLICY Test11 ;

Related Information

ALTER LOGIN POLICY Statement [page 1155]


ALTER USER Statement [page 1203]
CREATE LOGIN POLICY Statement [page 1307]
DROP USER Statement [page 1464]
ALTER LOGIN POLICY Statement [page 1155]
REVOKE System Privilege Statement [page 1635]

9.4.90 DROP LS POLICY Statement

Removes a logical server policy from the multiplex.

 Syntax

DROP LS POLICY <ls-policy-name>

Parameters

ls-policy-name

Any policy name except ROOT and must refer to a policy not currently used for any logical server.

SAP IQ SQL Reference


1446 INTERNAL SQL Statements
Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

The following example deletes the Test20 logical server policy:

DROP LS POLICY Test20

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.91 DROP MULTIPLEX SERVER Statement

Deletes a server from the multiplex.

 Syntax

DROP MULTIPLEX SERVER {<server-name>} [<drop_mpx_server_clause>]


<drop_mpx_server_clause>
{ WITH DROP MEMBERSHIP | WITH DROP LOGICAL SERVER }

Parameters

WITH DROP MEMBERSHIP

Fails with an error, when one or more logical server memberships exist for the multiplex server being
dropped. Use the WITH DROP MEMBERSHIP clause to drop the multiplex server along with all of its
memberships.
WITH DROP LOGICAL SERVER

SAP IQ SQL Reference


SQL Statements INTERNAL 1447
Drops the last secondary server along with all user-defined logical servers. When dropping the last
secondary server, the DROP MULTIPLEX SERVER command fails, when there are one or more user-
defined logical servers.

 Note

The WITH DROP LOGICAL SERVER clause is only valid when dropping the last secondary server. An
error is reported otherwise.

Remarks

Applies to multiplex only.

Shut down each multiplex server before dropping it. This statement automatically commits.

If not already stopped as recommended, the dropped server automatically shuts down after executing this
statement.

Dropping the last secondary server converts the multiplex back to SAP IQ server. After dropping the last
secondary server within the multiplex, the coordinator automatically shuts down. If required, it needs to be
restarted.

Privileges

Requires the MANAGE MULTIPLEX system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Examples

The following example drops a multiplex server named writer1:

DROP MULTIPLEX SERVER writer1

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1448 INTERNAL SQL Statements
9.4.92 DROP MUTEX statement

Drops the specified mutex.

 Syntax

DROP MUTEX [ IF EXISTS ] [ <owner>.]<mutex-name>

Parameters

owner

The owner of the mutex. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
mutex-name

The name of the mutex. <mutex-name> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
IF EXISTS clause

Use this clause to drop a mutex only if it exists. If a mutex does not exist and this clause is specified, then
nothing happens and no error is returned.

Remarks

If the mutex is locked by another connection, the drop operation proceeds without blocking but the mutex will
persist in the namespace until the mutex is released. Connections waiting on the mutex receive an error
immediately indicating that the object has been dropped.

Privileges

For a temporary mutex, you must be the connection that created the mutex.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

Automatic commit, but only for permanent mutexes.

SAP IQ SQL Reference


SQL Statements INTERNAL 1449
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement drops the protect_my_cr_section mutex:

DROP MUTEX protect_my_cr_section;

Related Information

CREATE MUTEX statement [page 1319]


CREATE MUTEX statement [page 1319]
LOCK MUTEX statement [page 1570]
RELEASE MUTEX statement [page 1603]
LOCK MUTEX statement [page 1570]
RELEASE MUTEX statement [page 1603]
REVOKE System Privilege Statement [page 1635]

9.4.93 DROP ROLE Statement

Removes a user-defined role from the database or converts a user-extended role to a regular user.

 Syntax

DROP ROLE [ FROM USER ] <role_name>


[ WITH REVOKE ]

Parameters

role_name

Must be the name of a role that already exists in the database.


FROM USER

Required to convert a user-extended role back to act as a regular user rather than remove it from the
database. The <role_name> must exist in the database.

SAP IQ SQL Reference


1450 INTERNAL SQL Statements
The user retains any login privileges, system privileges, and roles granted to the user-extended role and
becomes the owner of any objects owned by the user-extended role. Any users granted to the user-
extended are immediately revoked.
WITH REVOKE

Required when dropping a standalone or user-extended role to which users have been granted the
underlying system privileges of the role. The grant can have been made with either the WITH ADMIN
OPTION or WITH NO ADMIN OPTION clause.

Remarks

A user-defined role can be dropped from the database or converted back to a regular user at any time as long
as all dependent roles left meet the minimum required number of administrative users with active passwords.

Privileges

Requires administrative rights over the role being dropped. If the role being dropped owns objects, none are in
use by any user in any session at the time the DROP ROLE statement is executed.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example converts a user-extended role named Joe that has not been granted to other users
or roles back to a regular user:

DROP ROLE FROM USER Joe

● The following example drops a user-extended role named Jack that has not been granted to other users or
roles from the database:

DROP ROLE Jack

● The following example converts a user-extended role named Sam that has been granted to other user or
roles back to a regular role:

DROP ROLE FROM USER Sam


WITH REVOKE

SAP IQ SQL Reference


SQL Statements INTERNAL 1451
● The following example drops a standalone role named Sales2 that has been granted to other users or
roles from the database:

DROP ROLE Sales2


WITH REVOKE

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.94 DROP SEMAPHORE statement

Drops a semaphore.

 Syntax

DROP SEMAPHORE [ IF EXISTS ] [ <owner>.]<semaphore-name>

Parameters

owner

The owner of the semaphore. <owner> can also be specified using an indirect identifier (for example,
'[@<variable-name>]').
semaphore-name

The name of the semaphore. <semaphore-name> can also be specified using an indirect identifier (for
example, '[@<variable-name>]').
IF EXISTS clause

Use this clause to drop a semaphore only if it exists. If a semaphore does not exist and this clause is
specified, then nothing happens and no error is returned.

Remarks

An error is returned to any connection that is waiting to decrement the semaphore.

SAP IQ SQL Reference


1452 INTERNAL SQL Statements
Privileges

Requires one of:

● You own the semaphore


● DROP ANY MUTEX SEMAPHORE system privilege

For a temporary semaphore, you must be the connection that created the mutex.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

Automatic commit, but only for permanent semaphores.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement drops a semaphore called license_counter:

DROP SEMAPHORE license_counter;

Related Information

CREATE SEMAPHORE statement [page 1358]


CREATE SEMAPHORE statement [page 1358]
NOTIFY SEMAPHORE statement [page 1580]
WAITFOR SEMAPHORE statement [page 1715]
NOTIFY SEMAPHORE statement [page 1580]
WAITFOR SEMAPHORE statement [page 1715]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1453
9.4.95 DROP SEQUENCE statement

Drops a sequence. This statement applies to SAP IQ catalog store tables only.

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

Privileges

Requires one of:

● You own of the sequence


● DROP ANY SEQUENCE system privilege
● DROP ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None

Standards

ANSI/ISO SQL Standard

Sequences comprise optional ANSI/ISO SQL Language Feature T176.

 Example

The following example creates and then drops a sequence named Test:

CREATE SEQUENCE Test


START WITH 4
INCREMENT BY 2
NO MAXVALUE
NO CYCLE

SAP IQ SQL Reference


1454 INTERNAL SQL Statements
CACHE 15;
DROP SEQUENCE Test;

Related Information

ALTER SEQUENCE statement [page 1168]


CREATE SEQUENCE statement [page 1361]
ALTER SEQUENCE statement [page 1168]
CREATE SEQUENCE statement [page 1361]
REVOKE System Privilege Statement [page 1635]

9.4.96 DROP SERVER Statement

Drops a remote server from the SAP IQ system tables.

 Syntax

DROP SERVER <server-name>

Remarks

Before DROP SERVER succeeds, drop all the proxy tables that have been defined for the remote server.

Privileges

Requires the SERVER OPERATOR system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Side Effects

Automatic commit

SAP IQ SQL Reference


SQL Statements INTERNAL 1455
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example drops the server IQ_prod:

DROP SERVER iq_prod

Related Information

CREATE SERVER Statement [page 1363]


REVOKE System Privilege Statement [page 1635]

9.4.97 DROP SERVICE Statement

Deletes a Web service.

 Syntax

DROP SERVICE <service-name>

Remarks

DROP SERVICE deletes a Web service.

Privileges

Requires the MANAGE ANY WEB SERVICE system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

SAP IQ SQL Reference


1456 INTERNAL SQL Statements
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example drops a Web service named tables:

DROP SERVICE tables

Related Information

ALTER SERVICE Statement [page 1173]


CREATE SERVICE Statement [page 1365]
REVOKE System Privilege Statement [page 1635]

9.4.98 DROP SPATIAL REFERENCE SYSTEM Statement

Drops a spatial reference system.

 Syntax

DROP SPATIAL REFERENCE SYSTEM [ IF EXISTS ] <name>

Parameters

IF EXISTS

Prevents an error from being returned when the DROP SPATIAL REFERENCE SYSTEM statement
attempts to remove a spatial reference system that does not exist.

Privileges

Requires one of:

SAP IQ SQL Reference


SQL Statements INTERNAL 1457
● You own the spatial references system
● MANAGE ANY SPATIAL OBJECT system privilege
● DROP ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.99 DROP SPATIAL UNIT OF MEASURE Statement

Drops a spatial unit of measurement.

 Syntax

DROP SPATIAL UNIT OF MEASURE [ IF EXISTS ] <identifier>

Parameters

IF EXISTS

Prevents an error from being returned when the DROP SPATIAL UNIT OF MEASURE statement attempts
to remove a spatial unit of measure that does not exist.

Privileges

Requires one of:

● You own the spatial unit of measure


● MANAGE ANY SPATIAL OBJECT system privilege
● DROP ANY OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

SAP IQ SQL Reference


1458 INTERNAL SQL Statements
Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

The following example drops a fictitious spatial unit of measure named Test:

DROP SPATIAL UNIT OF MEASURE Test;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.100 DROP STATEMENT Statement [ESQL]

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.

 Syntax

DROP STATEMENT [ <owner>.]<statement-name>

Parameters

statement-name

Identifier or host-variable

Remarks

To drop the statement, you must first have prepared the statement.

SAP IQ SQL Reference


SQL Statements INTERNAL 1459
Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by Open Client/Open Server

Examples

The following example drops the statements s1 and stmt:

EXEC SQL DROP STATEMENT S1;


EXEC SQL DROP STATEMENT :stmt;

Related Information

PREPARE Statement [ESQL] [page 1590]


REVOKE System Privilege Statement [page 1635]

9.4.101 DROP TEXT CONFIGURATION Statement

Drops a text configuration object.

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

 Syntax

DROP TEXT CONFIGURATION [ <owner>.]<text-config-name>

Remarks

Use DROP TEXT CONFIGURATION to drop a text configuration object.

SAP IQ SQL Reference


1460 INTERNAL SQL Statements
Attempting to drop a text configuration object with dependent TEXT indexes results in an error. You must drop
the dependent TEXT indexes before dropping the text configuration object.

Text configuration objects are stored in the ISYSTEXTCONFIG system table.

Privileges

The privilege required to drop a text configuration depends on ownership. See GRANT System Privilege
Statement [page 1511] for assistance with granting privileges.

Ownership Privilege Required

Self None

Another User Requires one of:

● DROP ANY TEXT CONFIGURATION system privilege


● DROP ANY OBJECT system privilege

Side Effects

Automatic commit

Examples

The following example creates and drops the mytextconfig text configuration object:

CREATE TEXT CONFIGURATION mytextconfig FROM default_char;


DROP TEXT CONFIGURATION mytextconfig;

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1461
9.4.102 DROP TEXT INDEX Statement

Removes a TEXT index from the database.

 Note

This statement requires the Unstructured Data Analytics (IQ_UDA) license.

 Syntax

DROP TEXT INDEX <text-index-name>


ON [ <owner> ] <table-name>

Parameters

ON

Specifies the table on which the TEXT index is built.

Remarks

You must drop dependent TEXT indexes before you can drop a text configuration object.

Privileges

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Requires one of:

● You own the underlying table


● DROP ANY INDEX system privilege
● DROP ANY OBJECT system privilege
● REFERENCES object-level privilege on the table being indexed

Side Effects

Automatic commit

SAP IQ SQL Reference


1462 INTERNAL SQL Statements
Examples

The following example creates and drops the TextIdx TEXT index:

CREATE TEXT INDEX TextIdx ON Customers ( Street );


DROP TEXT INDEX TextIdx ON Customers;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.103 DROP TRIGGER statement

Removes a trigger from the database. This statement applies to SAP IQ catalog store tables only.

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

Privileges

The privilege required to drop a trigger depends on ownership. See GRANT System Privilege Statement [page
1511] or GRANT Object-Level Privilege Statement [page 1502] for assistance with granting privileges.

Side effects

Automatic commit.

SAP IQ SQL Reference


SQL Statements INTERNAL 1463
Standards

ANSI/ISO SQL Standard

DROP TRIGGER comprises part of optional ANSI/ISO SQL Language Feature T211, "Basic trigger
capability". The IF EXISTS clause is not in the standard.

 Example

This example creates, and then drops, a trigger called emp_upper_postal_code to ensure that postal codes
are in upper case before updating the Employees table. If the trigger does not exist, an error is returned.

CREATE TRIGGER emp_upper_postal_code


BEFORE UPDATE OF PostalCode
ON GROUPO.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;
DROP TRIGGER MyTrigger;

Related Information

ALTER TRIGGER statement [page 1201]


CREATE TRIGGER statement [page 1395]
ALTER TRIGGER statement [page 1201]
CREATE TRIGGER statement [page 1395]
REVOKE System Privilege Statement [page 1635]

9.4.104 DROP USER Statement

Removes a user.

 Syntax

DROP USER <user-name>

Parameters

user-name

SAP IQ SQL Reference


1464 INTERNAL SQL Statements
Name of the user to remove.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

 Note

When dropping a user, any objects owned by this user and any permissions granted by this user are also
removed.

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

The following example drops the user SQLTester from the database:

DROP USER SQLTester

Related Information

CREATE LOGIN POLICY Statement [page 1307]


CREATE USER Statement [page 1402]
DROP LOGIN POLICY Statement [page 1445]
ALTER LOGIN POLICY Statement [page 1155]
GRANT ROLE Statement [page 1504]
GRANT System Privilege Statement [page 1511]
REVOKE System Privilege Statement [page 1635]
REVOKE ROLE Statement [page 1630]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1465
9.4.105 DROP VARIABLE statement

Drops a SQL variable.

 Syntax

Drop a connection-scope variables:

DROP VARIABLE [ IF EXISTS ] <identifier>

Drop a database-scope variables

DROP DATABASE VARIABLE [ IF EXISTS ] [ <owner>.]<identifier>

Parameters

identifier

A valid identifier for the variable.


owner

Specify the owner of the database-scope variable. If <owner> is not specified, the database server looks
for a database-scope variable named <identifier> owned by the user executing the statement. If none
is found, the database server looks for a database-scope variable named <identifier> owned by
PUBLIC.
IF EXISTS clause

Specify this clause to allow the statement to complete without returning an error if a variable with the
specified name (and/or owner, if specified) is not found.

Remarks

The DROP VARIABLE statement drops a SQL variable.

Connection-scope variables are also automatically dropped when the database connection is terminated.
Database-scope variables must be explicitly dropped.

If a statement is still accessing a database-scope variable at the time it is dropped, then the variable is still
available in memory for that statement only.

Variables are often used for large objects, so dropping them after use or setting them to NULL can free up
significant resources such as disk space and memory.

SAP IQ SQL Reference


1466 INTERNAL SQL Statements
Privileges

The privilege varies by the variable scope and ownership. See GRANT System Privilege Statement [page 1511]
for assistance with granting privileges.

Side effects

Connection-scope variables: No side effects are associated with dropping a connection-scope variable.

Database-scope variables: Dropping a database-scope variable causes an automatic commit.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

CREATE VARIABLE Statement [page 1404]


SET Statement [ESQL] [page 1670]
REVOKE System Privilege Statement [page 1635]

9.4.106 EXECUTE Statement [ESQL]

Executes a SQL statement.

 Syntax

Syntax 1 – Executes a Previously Prepared Named Dynamic Statement

EXECUTE <statement-name>
... [ { USING DESCRIPTOR <sqlda-name> | USING <host-variable-list> } ]
... [ { INTO DESCRIPTOR <into-sqlda-name> | INTO <into-host-variable-
list> ]
... [ ARRAY :<nnn> } ]

Syntax 2 – Short Form to PREPARE and EXECUTE a Statement Not Containing Bind Variables or
Output

EXECUTE IMMEDIATE <statement>

SAP IQ SQL Reference


SQL Statements INTERNAL 1467
Parameters

statement-name

Identifier or host-variable.
sqlda-name

Identifier.
into-sqlda-name

Identifier.
statement

String or host-variable.
USING

OUTPUT from a SELECT statement or a CALL statement is put either into the variables in the variable list
or into 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

If used with an INSERT statement, the inserted row is returned in the second descriptor. For example,
when using autoincrement primary keys that generate primary-key values, EXECUTE provides a
mechanism to refetch the row immediately and determine the primary-key value assigned to the row.
ARRAH

Used with prepared INSERT statements to allow wide inserts, which insert more than one row at a time and
which might improve performance. The value nnn is the number of rows to be inserted. The SQLDA must
contain nnn * (columns per row) variables. The first row is placed in SQLDA variables 0 to (columns per
row)-1, and so on. Similarly, the ARRAY clause can be used for wide updates, deletes, and merges using
prepared UPDATE, DELETE, and MERGE statements.

Remarks

Syntax 1 – If the dynamic statement contains host variable placeholders, which supply information for the
request (bind variables), then either the <sqlda-name> must specify a C variable, which is a pointer to a
SQLDA containing enough descriptors for all bind variables occurring in the statement, or the bind variables
must be supplied in the <host-variable-list>.

Syntax 2 – The SQL statement contained in the string or host variable is immediately executed and is dropped
on completion.

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

 Note

You cannot reference a Table UDF in an EXECUTE statement.

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.

SAP IQ SQL Reference


1468 INTERNAL SQL Statements
Privileges

The required privileges depend on the statement being executed.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

Examples

● The following example executes a DELETE:

EXEC SQL EXECUTE IMMEDIATE


'DELETE FROM Employees WHERE EmployeeID = 105';

● The following example executes a prepared DELETE statement:

EXEC SQL PREPARE del_stmt FROM


'DELETE FROM Employees WHERE EmployeeID = :a';
EXEC SQL EXECUTE del_stmt USING :employee_number;

● The following example executes a prepared query:

EXEC SQL PREPARE sel1 FROM


'SELECT Surname FROM Employees WHERE EmployeeID = :a';
EXEC SQL EXECUTE sel1 USING :employee_number INTO :emp_lname;

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


PREPARE Statement [ESQL] [page 1590]
REVOKE System Privilege Statement [page 1635]

9.4.107 EXECUTE Statement [T-SQL]

Invokes a procedure, as an SAP Adaptive Server Enterprise-compatible alternative to the CALL statement.

 Syntax

EXECUTE [ <@return_status> = ] [<owner>.]<procedure_name>


... { [ <@parameter-name> = ] <expression>

SAP IQ SQL Reference


SQL Statements INTERNAL 1469
| [ <@parameter-name> = ] <@variable> [ <output> ] } ,...

Remarks

EXECUTE executes a stored procedure, optionally supplying procedure parameters and retrieving output values
and return status information.

EXECUTE is implemented for Transact-SQL compatibility, but can be used in either Transact-SQL or SAP IQ
batches and procedures.

 Note

You cannot reference a Table UDF in an EXECUTE statement.

Privileges

Requires one of:

● You own the procedure


● EXECUTE object-level privilege on the procedure
● EXECUTE ANY PROCEDURE system privilege

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Examples

● The following example creates the procedure p1:

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;

● Execute the procedure, supplying the input value of 23 for the parameter. If you are connected from an
Open Client application, PRINT messages are displayed on the client window. If you are connected from an
ODBC or Embedded SQL application, messages display on the database server window:

EXECUTE p1 23

● An alternative way of executing the procedure, which is useful if there are several parameters:

EXECUTE p1 @var = 23

SAP IQ SQL Reference


1470 INTERNAL SQL Statements
● Execute the procedure, using the default value for the parameter:

EXECUTE p1

● Execute the procedure and store the return value in a variable for checking return status:

EXECUTE @status = p1 23

Related Information

CALL Statement [page 1225]


REVOKE System Privilege Statement [page 1635]

9.4.108 EXECUTE IMMEDIATE Statement [ESQL] [SP]

Extends the range of statements that can be executed from within procedures. It lets you execute dynamically
prepared statements, such as statements that are constructed using the parameters passed in to a procedure.

 Syntax

Syntax 1

EXECUTE IMMEDIATE [ <execute-option> ] <string-expression>

<execute-option> ::=
WITH QUOTES [ ON | OFF ]
| WITH ESCAPES { ON | OFF }
| WITH RESULT SET { ON | OFF }

Syntax 2

EXECUTE ( <string-expression> )

Parameters

WITH QUOTES [ON]

Any double quotes in the string expression are assumed to delimit an identifier. When not specified, the
treatment of double quotes in the string expression depends on the current setting of the
QUOTED_IDENTIFIER database 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 QUOTED_IDENTIFIER is set to OFF.

See QUOTED_IDENTIFIER Option [TSQL].

SAP IQ SQL Reference


SQL Statements INTERNAL 1471
WITH ESCAPES

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

You can use WITH ESCAPES OFF for easier execution of dynamically constructed statements referencing
file names that contain backslashes.
string-expression

In some contexts, escape sequences in the <string-expression> are transformed before EXECUTE
IMMEDIATE 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 RESULT SET

When specified with ON, the EXECUTE IMMEDIATE statement returns a result set. With this clause, the
containing procedure is marked as returning a result set. If you do not include this clause, an error is
reported when the procedure is called if the statement does not produce a result set.

 Note

The default option is OFF, meaning that no result set is produced when the statement is executed.

Remarks

Literal strings in the statement must be enclosed in single quotes, and must differ from any existing statement
name in a PREPARE or EXECUTE IMMEDIATE statement. The statement must be on a single line.

Only global variables can be referenced in a statement executed by EXECUTE IMMEDIATE.

Only syntax 2 can be used inside Transact-SQL stored procedures.

The statement is executed with the permissions of the owner of the procedure, not with the permissions of the
user who calls the procedure.

Privileges

None

SAP IQ SQL Reference


1472 INTERNAL SQL Statements
Side Effects

None. However, if the statement is a data definition statement with an automatic commit as a side effect, then
that commit does take place.

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example creates a table, where the table name is supplied as a parameter to the procedure. The
full EXECUTE IMMEDIATE statement must be on a single line:

CREATE PROCEDURE CreateTableProc(


IN tablename char(30)
)
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE ' || tablename ||
' ( column1 INT PRIMARY KEY)'
END;

Call the procedure and create table mytable:

CALL CreateTableProc( 'mytable' )

Related Information

BEGIN … END Statement [page 1218]


CREATE PROCEDURE Statement [page 1321]
QUOTED_IDENTIFIER Option [TSQL] [page 1977]
REVOKE System Privilege Statement [page 1635]

9.4.109 EXIT Statement [Interactive SQL]

Leaves Interactive SQL.

 Syntax

{ EXIT | QUIT | BYE } [ <return-code> ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1473
<return-code> ::=
<number> | <connection-variable>

Remarks

Closes the Interactive SQL window, if you are running Interactive SQL as a windowed program, or terminates
Interactive SQL altogether when run 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 used in batch files to indicate success or failure of the commands in an
Interactive SQL command file. The default return code is 0.

Privileges

None

Side Effects

● Automatically performs a commit, if option COMMIT_ON_EXIT is set to ON (the default); otherwise this
statement performs an implicit rollback.
● On Windows operating systems, the optional return value is available as ERRORLEVEL.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable by SAP Adaptive Server Enterprise.

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

SAP IQ SQL Reference


1474 INTERNAL SQL Statements
SET retcode = 1;
ELSE
SET retcode = 0;
END IF;
EXIT retcode;

 Note

You cannot write the following the 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;

Related Information

SET OPTION Statement [page 1677]


REVOKE System Privilege Statement [page 1635]

9.4.110 FETCH Statement [ESQL] [SP]

Retrieves one row from the named cursor. The cursor must have been previously opened.

 Syntax

FETCH
{ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE <row-count> | RELATIVE <row-count> }
... <cursor-name>
... { [ INTO <host-variable-list> ]
| USING DESCRIPTOR <sqlda-name>
| INTO <variable-list> }
... [ PURGE ] [ BLOCK <n> ] [ ARRAY <fetch-count> ]
... INTO <variable-list>
... IQ CACHE <row-count>

Go to:

● Remarks
● Privileges
● Standards
● Examples

SAP IQ SQL Reference


SQL Statements INTERNAL 1475
Parameters

(back to top)

NEXT

(Default) Causes the cursor to advance one row before the row is fetched.
PRIOR

Moves the cursor back one row before fetching.


ABSOLUTE row-count

Used to go to a particular row. A zero indicates the position before the first row.

A one (1) indicates the first row, and so on. Negative numbers are used to specify an absolute position from
the end of the cursor. A negative one (-1) indicates the last row of the cursor. FIRST is a short form for
ABSOLUTE 1. LAST is a short form for ABSOLUTE -1.

 Note

SAP IQ handles the FIRST, LAST, ABSOLUTE, and negative RELATIVE clauses less efficiently than some
other DBMS products, so there is a performance impact when using them.

RELATIVE

Moves the cursor by a specified number of rows in either direction before fetching.

A positive number indicates moving forward and a negative number indicates moving backwards. Thus, a
NEXT is equivalent to RELATIVE 1 and PRIOR is equivalent to RELATIVE -1. RELATIVE 0 retrieves the same
row as the last fetch statement on this cursor.
row-count

Number or host variable


cursor-name

Identifier or host variable


INTO host-variable-list

(Embedded SQL only) May contain indicator variables


USING DESCRIPTOR sqlda-name

(Embedded SQL only) Identifier


fetch-count

Integer or host variable


INTO variable-list

If it is not specified, then FETCH positions the cursor only .OPEN initially positions the cursor before the
first row. An optional positional parameter can be specified that allows the cursor to be moved before a row
is fetched.
PURGE

(Embedded SQL only) Causes the client to flush its buffers of all rows and then send the fetch request to
the server. This fetch request may return a block of rows.
BLOCK n

SAP IQ SQL Reference


1476 INTERNAL SQL Statements
(Embedded SQL only) Gives the client and server a hint as to how many rows may be fetched by the
application. The special value of 0 means the request is sent to the server and a single row is returned (no
row blocking).

ARRAY fetch-count

(Embedded SQL only) Allows wide fetches, which retrieve more than one row at a time, and which might
improve performance. To use wide fetches in Embedded SQL, include the FETCH statement in your code,
where ARRAY nnn is the last item of the FETCH statement:

EXEC SQL FETCH . . . ARRAY nnn

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.
IQ CACHE row-count

Specifies the maximum number of rows buffered in the FIFO queue. If you do not specify a value for IQ
CACHE, the value of the CURSOR_WINDOW_ROWS database option is used. The default setting of
CURSOR_WINDOW_ROWS is 200.

Remarks

(back to top)

These clauses are for use in Embedded SQL only:

● USING DESCRIPTOR <sqlda-name>


● INTO <host-variable-list>
● PURGE
● BLOCK <n>
● ARRAY <fetch-count>
● Use of <host-variable> in <cursor-name> and <row-count>

One row from the result of SELECT is put into the variables in the variable list. The correspondence from the
select list to the host variable list is one-to-one.

One or more rows from the result of SELECT are put either into the variables in the variable list or into the
program data areas described by the named SQLDA. In either case, the correspondence from the select list to
either the host variable list or the SQLDA descriptor array is one-to-one.

A cursor declared FOR READ ONLY sees the version of table(s) on which the cursor is declared when the cursor
is opened, not the version of table(s) at the time of the first FETCH

If the FETCH includes a positioning parameter and the position is outside the allowable cursor positions, then
the SQLE_NOTFOUND warning is issued.

DECLARE CURSOR must appear before FETCH in the C source code, and the OPEN statement must be executed
before FETCH. If a host variable is being used for the cursor name, then the DECLARE statement actually
generates code and thus must be executed before FETCH.

In the multiuser environment, rows can be fetched by the client more than one at a time. This is referred to as
block fetching or multirow fetching. The first fetch causes several rows to be sent back from the server. The

SAP IQ SQL Reference


SQL Statements INTERNAL 1477
client buffers these rows and subsequent fetches are retrieved from these buffers without a new request to the
server.

If the SQLSTATE_NOTFOUND warning is returned on the fetch, then the sqlerrd[2] field of the SQLCA
(SQLCOUNT) contains the number of rows that the attempted fetch exceeded the allowable cursor positions.
(A cursor can be on a row, before the first row or after the last row.) The value is 0 if the row was not found but
the position is valid, for example, executing FETCH with a RELATIVE 1 clause when positioned on the last row of
a cursor. The value is positive if the attempted fetch was further beyond the end of the cursor, and negative if
the attempted fetch was further 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.

The server returns in SQLCOUNT the number of records fetched and always returns a SQLCOUNT greater than
zero unless there is an error. Older versions of the server only return a single row and the SQLCOUNT is set to
zero. Thus a SQLCOUNT of zero with no error condition indicates one valid row has been fetched.

Privileges

(back to top)

The cursor must be opened and the user must have SELECT object-level permission on the tables referenced in
the declaration of the cursor.

See GRANT Object-Level Privilege Statement [page 1502] for assistance with granting privileges

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following is an embedded SQL example:

EXEC SQL DECLARE cur_employee CURSOR FOR


SELECT EmployeeID, Surname FROM Employees;
EXEC SQL OPEN cur_employee;
EXEC SQL FETCH cur_employee
INTO :emp_number, :emp_name:indicator;

● The following is a procedure example:

BEGIN

SAP IQ SQL Reference


1478 INTERNAL SQL Statements
DECLARE cur_employee CURSOR FOR
SELECT Surname
FROM Employees;
DECLARE name CHAR(40) ;
OPEN cur_employee;
LOOP
FETCH NEXT cur_employee into name ;
.
.
.
END LOOP
CLOSE cur_employee;
END

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


OPEN Statement [ESQL] [SP] [page 1582]
PREPARE Statement [ESQL] [page 1590]
CURSOR_WINDOW_ROWS Option [page 1801]
REVOKE System Privilege Statement [page 1635]

9.4.111 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> | FOR READ ONLY } ]
| USING <variable-name> }
DO <statement-list>
END FOR [ <statement-label> ]

<cursor-type> ::=
NO SCROLL
| DYNAMIC SCROLL
| SCROLL
| INSENSITIVE
| SENSITIVE

<cursor-concurrency> ::=
BY { VALUES | TIMESTAMP | LOCK }

<variable-name> ::= <identifier>

SAP IQ SQL Reference


SQL Statements INTERNAL 1479
Parameters

NO SCROLL

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, the database
server supplies the most efficient kind of cursor, which is an asensitive cursor.
DYNAMIC SCROLL

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, the database server 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

A cursor declared SCROLL can use all formats of the FETCH statement. When a SCROLL cursor is
requested, the database server supplies a value-sensitive cursor. The database server 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

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

A cursor declared SENSITIVE is sensitive to changes to membership or values of the result set.

Remarks

FOR is a control statement that lets you execute a list of SQL statements once for each row in a cursor.

The FOR statement is equivalent to a compound statement with a DECLARE for the cursor and a DECLARE of a
variable for each column in the result set of the cursor, followed by a loop that fetches one row from the cursor
into the local variables and executes <statement-list> once for each row in the cursor.

The name and data type of the local variables that are declared are derived from the <statement> used in the
cursor. With a SELECT statement, the data type is the data type of the expressions in the select list. The names
are the select list item aliases where 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>.

SAP IQ SQL Reference


1480 INTERNAL SQL Statements
Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Example

This code fragment illustrates the use of the FOR loop:

FOR names AS curs CURSOR FOR


SELECT Surname
FROM Employees
DO
CALL search_for_name( Surname );
END FOR;

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


FETCH Statement [ESQL] [SP] [page 1475]
LEAVE Statement [page 1547]
LOOP Statement [page 1576]
REVOKE System Privilege Statement [page 1635]

9.4.112 FORWARD TO Statement

Sends native syntax to a remote server, enabling users to specify the server to which a passthrough connection
is required.

 Syntax

Syntax 1 – Sends a Statement to a Remote Server

FORWARD TO <server-name> { <sql-statement> }

SAP IQ SQL Reference


SQL Statements INTERNAL 1481
Syntax 2 – Places SAP IQ into Passthrough Mode to Send a Series of Statements to a Remote
Server

FORWARD TO [ <server-name> ]

Parameters

server-name

The name of the remote server.


sql-statement

A command in the native syntax of the remote server. The command or group of commands is enclosed in
curly braces ({}) or single quotes.

Remarks

If you specify a <server-name>, but do not specify a statement in the FORWARD TO query, your session enters
passthrough mode, and all subsequent queries are passed directly to the remote server. To turn passthrough
mode OFF, issue the FORWARD TO statement without a <server_name> specification.

 Note

The FORWARD TO statement is a server directive and cannot be used in stored procedures, triggers, events,
or batches.

FORWARD TO enables users to specify the server to which a passthrough connection is required. The statement
can be used:

● To send a statement to a remote server (Syntax 1)


● To place SAP IQ into passthrough mode for sending a series of statements to a remote server (Syntax 2)

When establishing a connection to <server-name> on behalf of the user, the server uses:

● A remote login alias set using CREATE EXTERNLOGIN


● If a remote login alias is not set up, the name and password used to communicate with SAP IQ

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.

Privileges

None

SAP IQ SQL Reference


1482 INTERNAL SQL Statements
Side Effects

The remote connection is set to AUTOCOMMIT (unchained) mode for the duration of the FORWARD TO session.
Any work that was pending prior to the FORWARD TO statement is automatically committed.

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example shows a passthrough session with the remote server ase_prod:

FORWARD TO aseprod
SELECT * from titles
SELECT * from authors
FORWARD TO

Related Information

CREATE EXTERNLOGIN Statement [page 1271]


CREATE SERVER Statement [page 1363]

9.4.113 FROM Clause

Specifies the database tables or views involved in a SELECT statement.

 Syntax

...FROM <table-expression> [,...]


<table-expression> ::=
<table-name>
| <view-name>
| <procedure-name>
| <common-table-expression>
| (<subquery>) [[ AS ] <derived-table-name> ( <column_name, ...>) ]]
| <derived-table>
| <join-expression>
| ( <table-expression> , ... )
| <openstring-expression>
| <apply-expression>
| <contains-expression>

SAP IQ SQL Reference


SQL Statements INTERNAL 1483
| <dml-derived-table>

<table-name> ::=
[ <userid>.] <table-name> ]
[ [ AS ] <correlation-name> ]
[ FORCE INDEX ( <index-name> ) ]

<view-name> ::=
[ <userid>.]<view-name> [ [ AS ] <correlation-name> ]

<procedure-name> ::=
[ <owner>, ] <procedure-name> ([ <parameter>, ...])
[ WITH(<column-name datatype>, )]
[ [ AS ] <correlation-name> ]

<parameter> ::=
<scalar-expression> | <table-parameter>

<table-parameter> ::=
TABLE (<select-statement)> [ OVER ( <table-parameter-over> )]

<table-parameter-over> ::=
[ PARTITION BY {ANY
| NONE|< table-expression> } ]
[ ORDER BY { <expression> | <integer> }
[ ASC | DESC ] [, ...] ]

<derived-table> ::=
( <select-statement> )
[ 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 ]

<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> ]

SAP IQ SQL Reference


1484 INTERNAL SQL Statements
<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>
| DELIMITED BY <string>
| ENCODING <encoding>
| 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>
<update-statement>
<delete-statement>

<table-version-names> ::=
OLD [ AS ] <correlation-name> [ FINAL [ AS ] <correlation-name> ]
| FINAL [ AS ] <correlation-name>

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

table-name

SAP IQ SQL Reference


SQL Statements INTERNAL 1485
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.
parameter

Specifies one of the following clauses:

● <scalar-parameter> – any objects of a valid SQL datatype.


● <table-parameter> – can be specified using a table, view or common table-expression name, which
are treated as new instance of this object if the object is also used outside the table-parameter.

If a subquery is used to define the TABLE parameter, then the following restrictions must hold:

● The table-parameter clause must be of type IN.


● PARTITION BY or ORDER BY clauses must refer to the columns of the derived table and outer
references. An expression in the <expression-list> can be an integer K, which refers to the Kth
column of the TABLE input parameter.

 Note

A Table UDF can only be referenced in a FROM clause of a SQL statement.

PARTITION BY

Logically specifies how the invocation of the function will be performed by the execution engine. The
execution engine must invoke the function for each partition and the function must process a whole
partition in each invocation. PARTITION BY or ORDER BY clauses must refer to the columns of the derived
table and outer references. An expression in the expression-list can be an integer K, which refers to the Kth
column of the TABLE input parameter.

PARTITION BY clause also specifies how the input data must be partitioned such that each invocation of
the function will process exactly one partition of data. The function must be invoked the number of times
equal to the number of partitions. For TPF, the parallelism characteristics are established through dynamic
negotiation between the server and the UDF at the runtime. If the TPF can be executed in parallel, for N
input partitions, the function can be instantiated M times, with M <=N. Each instantiation of the function
can be invoked more than once, each invocation consuming exactly one partition.

You can specify only one TABLE input parameter for PARTITION BY <expression-list> or PARTITION
BY ANY clause. For all other TABLE input parameters you must specify, explicit or implicit PARTITION BY
NONE clause.

SAP IQ SQL Reference


1486 INTERNAL SQL Statements
 Note

The execution engine can invoke the function in any order of the partitions and the function is assumed
to return the same result sets regardless of the partitions order. Partitions cannot be split among two
invocations of the function.

ORDER BY

Specifies that the input data in each partition is expected to be sorted by <expression-list> by the
execution engine. The UDF expects each partition to have this physical property. If only one partition exists,
the whole input data is ordered based on the ORDER BY specification. ORDER BY clause can be specified
for any of the TABLE input parameters with PARTITION BY NONE or without PARTITION BY clause.
derived-table

PARTITION BY or ORDER BY clauses mustYou 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.
join-expression, join-operator, join-type

The join-type keywords are:

● CROSS JOIN – returns the Cartesian product (cross product) of the two source tables
● NATURAL JOIN – compares for equality all corresponding columns with the same names in two tables
(a special case equijoin; columns are of same length and data type)
● KEY JOIN – restricts foreign-key values in the first table to be equal to the primary-key values in the
second table
● INNER JOIN – discards all rows from the result table that do not have corresponding rows in both
tables
● LEFT OUTER JOIN – preserves unmatched rows from the left table, but discards unmatched rows from
the right table
● RIGHT OUTER JOIN – preserves unmatched rows from the right table, but discards unmatched rows
from the left table
● FULL OUTER JOIN – retains unmatched rows from both the left and the right tables

Do not mix comma-style joins and keyword-style joins in the FROM clause. The same query can be written
two ways, each using one of the join styles. The ANSI syntax keyword style join is preferable.

The ON clause filters the data of inner, left, right, and full joins. Cross joins do not have an ON clause. In an
inner join, the ON clause is equivalent to a WHERE clause. In outer joins, however, the ON and WHERE
clauses are different. The ON clause in an outer join filters the rows of a cross product and then includes in
the result the unmatched rows extended with nulls. The WHERE clause then eliminates rows from both the
matched and unmatched rows produced by the outer join. You must take care to ensure that unmatched
rows you want are not eliminated by the predicates in the WHERE clause.

You cannot use subqueries inside an outer join ON clause.


openstring-expression

Specify an OPENSTRING clause to query within a file or a BLOB, treating the content of these sources as a
set of rows. When doing so, you also specify information about the schema of the file or BLOB for the result
set to be generated, since you are not querying a defined structure such as a table or view. This clause
applies to the FROM clause of a SELECT statement. It is not supported for UPDATE or DELETE statements.
apply-expression

SAP IQ SQL Reference


SQL Statements INTERNAL 1487
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 after 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, along 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.
dml-derived-table

Supports the use of a DML statement (INSERT, UPDATE, or DELETE) as a table expression in a query's
FROM clause.

Remarks

(back to top)

The SELECT statement requires a table list to specify which tables are used by the statement.

 Note

Although this description refers to tables, it also applies to views unless otherwise noted.

The FROM table list creates a result set consisting of all the columns from all the tables specified. Initially, all
combinations of rows in the component tables are in the result set, and the number of combinations is usually
reduced by join conditions and/or WHERE conditions.

Tables owned by a different user can be qualified by specifying the <userid>. Tables owned by roles to which
the current user belongs are found by default without specifying the user ID.

The correlation name is used to give a temporary name to the table for this SQL statement only. This is useful
when referencing columns that must be qualified by a table name but the table name is long and cumbersome
to type. The correlation name is also necessary to distinguish between table instances when referencing the
same table more than once in the same query. If no correlation name is specified, then the table name is used
as the correlation name for the current statement.

If the same correlation name is used twice for the same table in a table expression, that table is treated as if it
were only listed once. For example, in:

SELECT *
FROM SalesOrders
KEY JOIN SalesOrderItems,
SalesOrders
KEY JOIN Employees

The two instances of the SalesOrders table are treated as one instance that is equivalent to:

SELECT *
FROM SalesOrderItems
KEY JOIN SalesOrders
KEY JOIN Employees

SAP IQ SQL Reference


1488 INTERNAL SQL Statements
By contrast, the following is treated as two instances of the Person table, with different correlation names
HUSBAND and WIFE:

SELECT *
FROM Person HUSBAND, Person WIFE

Join columns require like data types for optimal performance.

For information on using the FROM clause with TEXT indexes, see SAP IQ Administration: Unstructured Data
Analytics.

Performance Considerations
Depending on the query, SAP IQ allows between 16 and 64 tables in the FROM clause with the optimizer turned
on; however, performance might suffer if you have more than 16 to 18 tables in the FROM clause in very complex
queries.

 Note

If you omit the FROM clause, or if all tables in the query are in the SYSTEM dbspace, the query is processed
by SAP SQL Anywhere instead of SAP IQ and might behave differently, especially with respect to syntactic
and semantic restrictions and the effects of option settings.

If you have a query that does not require a FROM clause, you can force the query to be processed by SAP IQ
by adding the clause FROM iq_dummy, where iq_dummy is a one-row, one-column table that you create in
your database.

Must be connected to the database.

Privileges

(back to top)

The FILE clause of <openstring-expression> requires the READ FILE system privilege.

The TABLE clause of <openstring-expression> requires the user to own the referenced tables, or to have
the SELECT ANY TABLE privilege.

For all other clauses, no additional privilege is required.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – the JOIN clause is not supported in some versions of SAP Adaptive Server
Enterprise. Instead, you must use the WHERE clause to build joins

SAP IQ SQL Reference


SQL Statements INTERNAL 1489
Examples

(back to top)

● The following example shows valid FROM clauses:

...
FROM Employees
...
...
FROM Employees NATURAL JOIN Departments
...
...
FROM Customers
KEY JOIN SalesOrders
KEY JOIN SalesOrderItems
KEY JOIN Products
...

● The following example shows a query that illustrates how to use derived tables in a query:

SELECT Surname, GivenName, number_of_orders


FROM Customers JOIN
( SELECT CustomerID, count(*)
FROM SalesOrders
GROUP BY CustomerID )
AS sales_order_counts ( CustomerID,
number_of_orders )
ON ( Customers.ID = sales_order_counts.cust_id )
WHERE number_of_orders > 3

● The following example shows a query that illustrates a valid FROM clause where the two references to the
same table T are treated as two different instances of the same table T:

SELECT * FROM T, my_proc(TABLE(SELECT T.Z, T.X FROM T)


OVER(PARTITION BY T.Z));

● The following example uses a table parameterized function (TPF) and illustrates a valid FROM clause:

SELECT * FROM R, SELECT * FROM my_udf(1);


SELECT * FROM my_tpf(1, TABLE(SELECT c1, c2 FROM t))
(my_proc(R.X, TABLE T OVER PARTITION BY T.X)) AS XX;

● The following example 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;

● The following example shows query uses a comma-style join:

SELECT *
FROM Products pr, SalesOrders so, SalesOrderItems si
WHERE pr.ProductID = so.ProductID
AND pr.ProductID = si.ProductID;

SAP IQ SQL Reference


1490 INTERNAL SQL Statements
The same query can use the preferable keyword-style join:

SELECT *
FROM Products pr INNER JOIN SalesOrders so
ON (pr.ProductID = so.ProductID)
INNER JOIN SalesOrderItems si
ON (pr.ProductID = si.ProductID);

Related Information

DELETE Statement [page 1424]


SELECT Statement [page 1659]
REVOKE System Privilege Statement [page 1635]
FROM Clause for Full Text Searches

9.4.114 GET DESCRIPTOR Statement [ESQL]

Retrieves information about variables within a descriptor area, or retrieves actual data from a variable in a
descriptor area.

 Syntax

GET DESCRIPTOR <descriptor-name>


{ <...hostvar> = COUNT } | VALUE <n> <assignment> [,…] }

<assignment> ::=
<hostvar> = { TYPE
| LENGTH
| PRECISION
| SCALE
| DATA
| INDICATOR
| NAME
| NULLABLE
| RETURNED_LENGTH }

Remarks

The value <n> specifies the variable in the descriptor area about which information is retrieved.

Type checking is performed when doing GET DESCRIPTOR ... DATA to ensure that the host variable and the
descriptor variable have the same data type. LONG VARCHAR and LONG BINARY are not supported by GET
DESCRIPTOR ... DATA.

If an error occurs, it is returned in the SQLCA.

SAP IQ SQL Reference


SQL Statements INTERNAL 1491
Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

See ALLOCATE DESCRIPTOR Statement [ESQL].

Related Information

ALLOCATE DESCRIPTOR Statement [ESQL] [page 1131]


DEALLOCATE DESCRIPTOR Statement [ESQL] [page 1411]
SET DESCRIPTOR Statement [ESQL] [page 1676]
REVOKE System Privilege Statement [page 1635]

9.4.115 GOTO Statement [T-SQL]

Branches to a labeled statement.

 Syntax

<label> :
<sql-statement(s)>
GOTO <label_name>

Remarks

Statements in a procedure or batch can be labeled using a valid identifier followed by a colon (for example
mylabel:), provided that the label is at the beginning of a loop, conditional, or block. The label can then be
referenced in a GOTO statement, causing the execution point to move to the top of the loop/condition or the
first statement within the block.

SAP IQ SQL Reference


1492 INTERNAL SQL Statements
When referencing a label in a GOTO statement, do not specify the colon.

If you nest compound statements, then you can only go to 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.

The label use is not restricted to the beginning of loops, conditionals, or blocks; they can occur on any
statement. However, the same restrictions apply to using the GOTO statement within nested compound
statements.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

In the following example, if the GotoTest procedure is executed, then the GOTO lbl1 repositions execution to the
SET i2 = 200 statement. The returned values for column i2 in the result are 203 for all 5 rows in the result set:

CREATE OR REPLACE PROCEDURE GotoTest()


RESULT ( id INT, i INT, i2 INT )
BEGIN
DECLARE LOCAL TEMPORARY TABLE gotoTable( id INT DEFAULT AUTOINCREMENT, i
INT, i2 INT ) NOT TRANSACTIONAL;
DECLARE i INT;
DECLARE i2 INT;
SET i = 100;
lbl1: WHILE i < 105 LOOP
SET i2 = 200;
SET i2 = i2 + 1;
lbl2: BEGIN
SET i2 = i2 + 1;
lbl3: BEGIN
SET i2 = i2 + 1;
INSERT INTO gotoTable(i, i2) VALUES(i, i2);
SET i = i + 1;
IF( i < 110 ) THEN
GOTO lbl1
END IF;
END
END
END LOOP;
SELECT id, i, i2 FROM gotoTable ORDER BY id;
END;
CALL GotoTest();

SAP IQ SQL Reference


SQL Statements INTERNAL 1493
The results are:

id i i2

1 100 203

2 101 203

3 102 203

4 103 203

5 104 203

If the GotoTest procedure is changed to use GOTO lbl2 instead of GOTO lbl1, then the GOTO statement
repositions execution to the SET i2 = i2 + 1 statement immediately after the lbl2: BEGIN statement, and the
returned values in column i2 become 203, 205, 207, up to 221.

If the GotoTest procedure is changed to use GOTO lbl3, then the GOTO statement repositions execution to the
SET i2 = i2 +1 statement immediately after the lbl3: BEGIN statement, and the returned values in column i2
become 203, 204, 205, up to 212.

In the following example, the Transact-SQL batch prints the message “yes” on the server window four times:

declare @count smallint


select @count = 1
restart:
print 'yes'
select @count = @count + 1
while @count <=4
goto restart

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.116 GRANT CHANGE PASSWORD Privilege Statement

Allows users to manage passwords for other users and administer the CHANGE PASSWORD system privilege.

 Syntax

GRANT CHANGE PASSWORD ( <target_user_list> | ANY | ANY WITH ROLES


<target_role_list> )
TO <user_id>[, …]
[ WITH ADMIN [ONLY] OPTION | WITH NO ADMIN OPTION]

SAP IQ SQL Reference


1494 INTERNAL SQL Statements
Parameters

target_user_list

Users the grantee has the potential to impersonate. The list must consist of existing users or user-
extended roles with login passwords. Separate the user_IDs in the list with commas.
ANY

All database users with login passwords become potential target users to manage passwords for each
grantee.
ANY WITH ROLES target_role_list

List of target roles for each grantee. Any users who are granted any of the target roles become potential
target users for each grantee. The <target_role_list> must consist of existing roles and the users who
are granted said roles must consist of database users with login passwords. Use commas to separate
multiple user_IDs.
user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_ids with
commas.
WITH ADMIN OPTION

(Valid with the ANY clause only) The user can both manage passwords and grant the CHANGE PASSWORD
system privilege to another user.
WITH ADMIN ONLY OPTION

(Valid with the ANY clause only) The user can grant the CHANGE PASSWORD system privilege to another
user, but cannot manage passwords of other users.
WITH NO ADMIN OPTION

The user can manage passwords, but cannot grant the CHANGE PASSWORD system privilege to another
user.

Remarks

A user can be granted the ability to manage the password of any user in the database (ANY) or only specific
users (<target_users_list>) or members of specific roles (ANY WITH ROLES <target_roles_list>).
Administrative rights to the CHANGE PASSWORD system privilege can only be granted when using the ANY
clause.

If no clause is specified, ANY is used by default. If no administrative clause is specified in the grant statement,
the WITH NO ADMIN OPTION clause is used.

By default, the CHANGE PASSWORD system privilege is granted to the SYS_AUTH_SA_ROLE compatibility role
with the WITH NO ADMIN OPTION clause and to the SYS_AUTH_SSO_ROLE compatibility role with the ADMIN
ONLY OPTION clause, if they exist.

Each target user specified (target_users_list) must be an existing user or user-extended role with a login
password. Each target role specified (target_roles_list) must be an existing user-extended or user-defined role.

SAP IQ SQL Reference


SQL Statements INTERNAL 1495
Privileges

Requires the CHANGE PASSWORD system privilege granted with administrative rights. See GRANT System
Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example grants Sally and Laurel the ability to manage the password of Bob, Sam, and
Peter:

GRANT CHANGE PASSWORD (Bob, Sam, Peter) TO (Sally, Laurel)

● The following example grants Mary the right to grant the CHANGE PASSWORD system privilege to any
user in the database. However, since the system privilege is granted with the WITH ADMIN ONLY OPTION
clause, Mary cannot manage the password of any other user.

GRANT CHANGE PASSWORD (ANY) TO Mary WITH ADMIN ONLY OPTION

● The following example grants Steve and Joe the ability to manage the password of any member of Role1
or Role2:

GRANT CHANGE PASSWORD (ANY WITH ROLES Role1, Role2) TO Steve, Joe

Related Information

REVOKE CHANGE PASSWORD Privilege Statement [page 1621]

9.4.117 GRANT CONNECT Privilege Statement

Create a new user, and can also be used to change a password. However, it is recommended that you use the
CREATE USER statement to create users instead of the GRANT CONNECT statement.

 Syntax

GRANT CONNECT
TO <userID> [, …]
IDENTIFIED BY <password> [, …]

SAP IQ SQL Reference


1496 INTERNAL SQL Statements
Parameters

userID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Remarks

GRANT CONNECT can be used to create a new user or be used by any user to change their own password.

 Tip

Use the CREATE USER statement rather than the GRANT CONNECT statement to create users.

If you inadvertently enter the user ID of an existing user when you are trying to add a new user, you are
actually changing the password of the existing user. You do not receive a warning because this behavior is
considered normal.

The stored procedures sp_addlogin and sp_adduser can also be used to add users. These procedures
display an error if you try to add an existing user ID.

 Note

Use system procedures, not GRANT and REVOKE statements to add and remove user IDs.

A user without a password cannot connect to the database. This is useful when you are creating groups and
you do not want anyone to connect to the role user ID. To create a user without a password, do not include the
IDENTIFIED BY clause.

When specifying a password, it must be a valid identifier. Passwords have a maximum length of 255 bytes. If
the VERIFY_PASSWORD_FUNCTION database option is set to a value other than the empty string, the GRANT
CONNECT TO statement calls the function identified by the option value. The function returns NULL to indicate
that the password conforms to rules. If the VERIFY_PASSWORD_FUNCTION option is set, you can specify only
one <userid> and <password> with the GRANT CONNECT statement.

Invalid names for database user IDs and passwords include those that:

● Begin with white space or single or double quotes


● End with white space
● Contain semicolons

Privileges

To change your own password requires no additional privilege. To change another user's password requires the
CHANGE PASSWORD system privilege.

To create a new user requires the MANAGE ANY USER system privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1497
Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – the security model is different in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Examples

● The following example creates two new users for the database named Laurel and Hardy:

GRANT CONNECT TO Laurel, Hardy


IDENTIFIED BY Stan, Ollie

● The following example creates user Jane with no password:

GRANT CONNECT TO Jane

● The following example changes the password for Bob to newpassword:

GRANT CONNECT TO Bob IDENTIFIED BY <newpassword>

Related Information

CREATE USER Statement [page 1402]


REVOKE CONNECT Privilege Statement [page 1623]

9.4.118 GRANT CREATE Privilege Statement

Grants CREATE privilege on a specified dbspace to the specified users and roles.

 Syntax

GRANT CREATE
ON <dbspace_name>
TO <user_id> [, …]

Parameters

dbspace_name

The name of the dbspace.

SAP IQ SQL Reference


1498 INTERNAL SQL Statements
user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires the MANAGE ANY DBSPACE system privilege. See GRANT System Privilege Statement [page 1511].

Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – the security model is different in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Examples

The following example grants CREATE privilege on dbspace DspHist to users Fiona and Ciaran:

GRANT CREATE ON DspHist TO Fiona, Ciaran

Related Information

REVOKE CREATE Privilege Statement [page 1624]

9.4.119 GRANT EXECUTE Privilege Statement

Grants EXECUTE privilege on a procedure or user-defined function.

 Syntax

GRANT EXECUTE
ON [ <owner>.] {<procedure-name> | <user-defined-function-name> }
TO <user_id> [, …]

SAP IQ SQL Reference


SQL Statements INTERNAL 1499
Parameters

user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires one of:

● You own the procedure


● MANAGE ANY OBJECT PRIVILEGE system privilege

See GRANT System Privilege Statement [page 1511].

Standards

● SQL – syntax is a Persistent Stored Module feature.


● SAP database products – the security model is different in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Related Information

Granting the Ability to Run a Privileged System Procedure [page 575]


REVOKE EXECUTE Privilege Statement [page 1625]

9.4.120 GRANT INTEGRATED LOGIN Statement

Creates an explicit integrated login mapping between one or more Windows user profiles and an existing
database user ID. This allows a user who successfully logged in to their local machine to connect to a database
without having to provide a user ID or password.

 Syntax

GRANT INTEGRATED LOGIN


TO <user_profile_name> [, …]
AS USER <userID> [, …]

SAP IQ SQL Reference


1500 INTERNAL SQL Statements
Parameters

user_profile_name

Specifies the name of the user profile.


userID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511].

Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – the security model is different in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Related Information

REVOKE INTEGRATED LOGIN Statement [page 1626]

9.4.121 GRANT KERBEROS LOGIN Statement

Creates a Kerberos-authenticated login mapping from one or more Kerberos principals to an existing database
user ID. This allows a user who has successfully logged in to Kerberos (user who has a valid Kerberos ticket-
granting ticket) to connect to a database without having to provide a user ID or password.

 Syntax

GRANT KERBEROS LOGIN


TO <client-Kerberos-principal> [, …]
AS USER <userID> [, …]

SAP IQ SQL Reference


SQL Statements INTERNAL 1501
Parameters

userID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511].

Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – the security model differs in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Related Information

REVOKE KERBEROS LOGIN Statement [page 1627]

9.4.122 GRANT Object-Level Privilege Statement

Grants database object-level privileges on individual tables or views to a user or role.

 Syntax

GRANT <object-level-privilege> [, …]
ON [ <owner>.]<object-name>
TO <user_id> [, …]
[ WITH GRANT OPTION ]

<object-level-privilege> ::=
ALL [ PRIVILEGES ]
| ALTER
| DELETE
| INSERT
| LOAD
| REFERENCE [ ( <column-name> [, …] ) ]
| SELECT [ ( <column-name> [, …] ) ]
| TRUNCATE
| UPDATE [ ( <column-name>, …) ] }

SAP IQ SQL Reference


1502 INTERNAL SQL Statements
Parameters

user_id

Must be the name of an existing user or immutable role. The list must consist of existing users with login
passwords. Separate the user_ids in the list with commas.
object-level-privilege

ALL

Grants all privileges to users


ALTER

Users can alter this table with the ALTER TABLE statement. This privilege is not allowed for views.
DELETE

Users can delete rows from this table or view.


INSERT

Users can insert rows into the named table or view.


LOAD

Users can load data into the named table or view.


SELECT

Users can look at information in this view or table. If column names are specified, then the users can
look at only those columns. SELECT permissions on columns cannot be granted for views, only for
tables.
TRUNCATE

Users can truncate the named table or view.


UPDATE

Users can update rows in this view or table. If column names are specified, users can update only
those columns. UPDATE privileges on columns cannot be granted for views, only for tables. To update
a table, users must have both SELECT and UPDATE privilege on the table.
WITH GRANT OPTION

The named user ID is also given privileges to grant the same privileges to other user IDs.

Remarks

You can list the table privileges, or specify ALL to grant all privileges at once.

Privileges

If you own the object or have been granted the specific object privilege with the WITH GRANT OPTION clause
on the object, no additional privilege is required to grant an object-level privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1503
For objects owned by others, you need the MANAGE ANY OBJECT PRIVILEGE system privilege. See GRANT
System Privilege Statement [page 1511].

Standards

● SQL – syntax is an entry-level feature


● SAP database products – supported by SAP Adaptive Server Enterprise

Related Information

REVOKE Object-Level Privilege Statement [page 1628]

9.4.123 GRANT ROLE Statement

Grants roles to users or other roles, with or without administrative rights.

 Syntax

GRANT ROLE <role_name> [, …]


TO <grantee> [, …]
[ {WITH NO ADMIN | WITH ADMIN [ ONLY ] } OPTION ]
[ WITH NO SYSTEM PRIVILEGE INHERITANCE ]

<role_name>
dbo
| diagnostics
| PUBLIC
| rs_systabgroup
| SA_DEBUG
| SYS
| SYS_AUTH_SA_ROLE
| SYS_AUTH_SSO_ROLE
| SYS_AUTH_DBA_ROLE
| SYS_AUTH_RESOURCE_ROLE
| SYS_AUTH_BACKUP_ROLE
| SYS_AUTH_VALIDATE_ROLE
| SYS_AUTH_WRITEFILE_ROLE
| SYS_AUTH_WRITEFILECLIENT_ROLE
| SYS_AUTH_READFILE_ROLE
| SYS_AUTH_READFILECLIENT_ROLE
| SYS_AUTH_PROFILE_ROLE
| SYS_AUTH_USER_ADMIN_ROLE
| SYS_AUTH_SPACE_ADMIN_ROLE
| SYS_AUTH_MULTIPLEX_ADMIN_ROLE
| SYS_AUTH_OPERATOR_ROLE
| SYS_AUTH_PERMS_ADMIN_ROLE
| SYS_REPLICATE_ADMIN_ROLE
| SYS_RUN_REPLICATE_ROLE
| SYS_SPATIAL_ADMIN_ROLE
| <user-defined role name>

SAP IQ SQL Reference


1504 INTERNAL SQL Statements
Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

role_name

Must already exist in the database. Separate multiple role names with commas.
grantee

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.
WITH NO ADMIN OPTION

Each <grantee> is granted the underlying system privileges of each <role_name>, but cannot grant
<role_name> to another user.
WITH ADMIN ONLY OPTION

Each <userID> is granted administrative privileges over each <role_name>, but not the underlying
system privileges of <role_name>.
WITH ADMIN OPTION

Each userID is granted the underlying system privileges of each <role_name>, along with the ability to
grant <role_name> to another user.
WITH NO SYSTEM PRIVILEGE INHERITANCE

The underlying system privileges of the granting role are not inherited by the members of the receiving
role. However, if the receiving role is a user-extended role, the underlying system privileges are granted to
the extended user.

Remarks

(back to top)

● The WITH NO SYSTEM PRIVILEGE INHERITANCE clause can be used when granting select compatibility
roles to other roles. It prevents automatic inheritance of the compatibility role's underlying system
privileges by members of the role. When granted to user-extended roles, the WITH NO SYSTEM PRIVILEGE
INHERITANCE clause applies to members of the role only. The user acting as a role automatically inherits
the underlying system privileges regardless of the clause.
● The WITH NO ADMIN OPTION WITH NO SYSTEM PRIVILEGE INHERITANCE and WITH NO SYSTEM
PRIVILEGE INHERITANCE clauses are semantically equivalent.

SAP IQ SQL Reference


SQL Statements INTERNAL 1505
● The WITH ADMIN OPTION or WITH ADMIN ONLY clauses cannot be specified in combination with the
WITH NO SYSTEM PRIVILEGE INHERITANCE clause when granting the SYS_AUTH_BACKUP_ROLE,
SYS_AUTH_RESOURCE_ROLE, or SYS_AUTH_VALIDATE_ROLE roles.
● The WITH ADMIN OPTION clause can only be specified in combination with the WITH NO SYSTEM
PRIVILEGE INHERITANCE clause when granting the SYS_AUTH_DBA_ROLE or
SYS_RUN_REPLICATION_ROLE roles.
● The WITH ADMIN OPTION and WITH ADMIN ONLY OPTION clauses are not supported for system roles.

Use of the WITH ADMIN OPTION or WITH ADMIN ONLY OPTION clause allows the grantee to grant or revoke
the role, but does not allow the grantee to drop the role.

By default, if no administrative clause is specified in the grant statement, each compatibility role is granted
with these default administrative rights:

WITH ADMIN OPTION WITH ADMIN ONLY OPTION WITH NO ADMIN OPTION

SYS_AUTH_SA_ROLE SYS_AUTH_DBA_ROLE SYS_AUTH_RESOURCE_ROLE


SYS_AUTH_SSO_ROLE
SYS_AUTH_BACKUP_ROLE

SYS_AUTH_VALIDATE_ROLE

SYS_AUTH_WRITEFILE_ROLE

SYS_AUTH_WRITEFILECLIENT_ROLE

SYS_AUTH_READFILE_ROLE

SYS_AUTH_READFILECLIENT_ROLE

SYS_AUTH_PROFILE_ROLE

SYS_AUTH_USER_ADMIN_ROLE

SYS_AUTH_SPACE_ADMIN_ROLE

SYS_AUTH_MULTIPLEX_ADMIN_ROLE

SYS_AUTH_OPERATOR_ROLE

SA_DEBUG

SYS_RUN_REPLICATION_ROLE

The SYS_AUTH_PERMS_ADMIN_ROLE role grants these underlying roles with these default administrative
rights:

SAP IQ SQL Reference


1506 INTERNAL SQL Statements
WITH ADMIN OPTION WITH NO ADMIN OPTION

SYS_AUTH_BACKUP_ROLE MANAGE ROLES

SYS_AUTH_OPERATOR_ROLE MANAGE ANY OBJECT PRIVILEGE

SYS_AUTH_USER_ADMIN_ROLE CHANGE PASSWORD

SYS_AUTH_SPACE_ADMIN_ROLE

SYS_AUTH_MULTIPLEX_ADMIN_ROLE

SYS_AUTH_RESOURCE_ROLE

SYS_AUTH_VALIDATE_ROLE

SYS_AUTH_PROFILE_ROLE

SYS_AUTH_WRITEFILE_ROLE

SYS_AUTH_WRITEFILECLIENT_ROLE

SYS_AUTH_READFILE_ROLE

SYS_AUTH_READFILECLIENT_ROLE

Privileges

(back to top)

To grant the following system roles requires the MANAGE ROLES system privilege. See GRANT System
Privilege Statement [page 1511] for assistance with granting privileges..

● dbo
● diagnostics
● PUBLIC
● rs_systabgroup
● SA_DEBUG SYS
● SYS
● SYS_REPLICATION_ADMIN_ROLE
● SYS_RUN_REPLICATION_ROLE
● SYS_SPATIAL_ADMIN_ROLE

To grant the following compatibility roles requires you been granted the specific compatibility role with
administrative privilege. See Grant Compatibility Roles in the SAP IQ Installation and Update Guide for your
platform for assistance in granting compatibility roles.

● SYS_AUTH_SA_ROLE
● SYS_AUTH_SSO_ROLE
● SYS_AUTH_DBA_ROLE
● SYS_AUTH_RESOURCE_ROLE
● SYS_AUTH_BACKUP_ROLE
● SYS_AUTH_VALIDATE_ROLE

SAP IQ SQL Reference


SQL Statements INTERNAL 1507
● SYS_AUTH_WRITEFILE_ROLE
● SYS_AUTH_WRITEFILECLIENT_ROLE
● SYS_AUTH_READFILE_ROLE
● SYS_AUTH_READFILECLIENT_ROLE
● SYS_AUTH_PROFILE_ROLE
● SYS_AUTH_USER_ADMIN_ROLE
● SYS_AUTH_SPACE_ADMIN_ROLE
● SYS_AUTH_MULTIPLEX_ADMIN_ROLE
● SYS_AUTH_OPERATOR_ROLE
● SYS_AUTH_PERMS_ADMIN_ROLE
● <user-defined role name>

Standards

(back to top)

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example grants Sales_Role to Sally, with administrative privileges, which means she can
grant or revoke Sales_Role to other users as well as perform any authorized tasks granted by the role:

GRANT ROLE Sales_Role TO Sally WITH ADMIN OPTION

● The following example grants the compatibility role SYS_AUTH_PROFILE_ROLE to the role Sales_Admin
with no administrative rights:

GRANT ROLE SYS_AUTH_PROFILE_ROLE TO Sales_Role WITH NO ADMIN OPTION

Sales_Admin is a standalone role and Mary and Peter have been granted Sales_Admin. Since
SYS_AUTH_PROFILE_ROLE is an inheritable compatibility role, Mary and Peter are granted the
underlying system privileges of Sales_Role. Since the role is granted with no administrative rights, they
cannot grant or revoke the role.
● The following example grants the compatibility role SYS_AUTH_BACKUP_ROLE to Tom with no
administrative rights:

GRANT ROLE SYS_AUTH_BACKUP_ROLE TO Tom


WITH NO SYSTEM PRIVILEGE INHERITANCE

Tom is a user-extended role to which Betty and Laurel have been granted. Since
SYS_AUTH_BACKUP_ROLE is a non-inheritable compatibility role, the underlying system privileges of the
role are not granted to Betty and Laurel. However, since Tom is an extended user, the underlying system
privileges are granted directly to Tom.

SAP IQ SQL Reference


1508 INTERNAL SQL Statements
Related Information

REVOKE ROLE Statement [page 1630]


REVOKE System Privilege Statement [page 1635]

9.4.124 GRANT SET USER Privilege Statement

Grants the ability for one user to impersonate another user and to administer the SET USER system privilege.

 Syntax

GRANT SET USER ( <target_users_list>


| ANY
| ANY WITH ROLES <target_roles_list> )
TO <user_id> [, …]
[ WITH ADMIN [ ONLY ] OPTION | WITH NO ADMIN OPTION ]

Parameters

target_users_list

Must consist of existing users with login passwords and is the potential list of target users who can no
longer be impersonated by grantee users. Separate the user IDs in the list with commas.
ANY

The potential list of target users for each grantee consists of all database users with login passwords.
ANY WITH ROLES target_roles_list

The <target_role_list> must consist of existing roles, and the potential list of target users for each
grantee must consist of database users with login passwords that have a subset of roles in
<target_role_list>. Separate the list of roles with commas.
user_id

Each <user_id> must be the name of an existing user or immutable role. The list must consist of existing
users with login passwords. Separate the user_ids in the list with commas.
WITH ADMIN OPTION

(Valid in conjunction with the ANY clause only) The user can both issue the SETUSER command to
impersonate another user and grant the SET USER system privilege to another user.
WITH ADMIN ONLY OPTION

(Valid in conjunction with the ANY clause only) The user can grant the SET USER system privilege to
another user, but cannot issue the SETUSER command to impersonate another user.
WITH NO ADMIN OPTION

The user can issue the SETUSER command to impersonate another user, but cannot grant the SET USER
system privilege to another user.

SAP IQ SQL Reference


SQL Statements INTERNAL 1509
Remarks

A user can be granted the ability to impersonate any user in the database (ANY) or only specific users
(<target_users_list>) or members of specific roles (ANY WITH ROLES <target_roles_list>).
Administrative rights to the SET USER system privilege can only be granted when using the ANY clause.

If no clause is specified, ANY is used by default. If no administrative clause is specified in the grant statement,
the WITH NO ADMIN OPTION clause is used.

If regranting the SET USER system privilege to a user, the effect of the regrant is cumulative.

By default, the SET USER system privilege is granted to the SYS_AUTH_SSO_ROLE compatibility role with the
WITH NO ADMIN OPTION clause, if they exist.

The granting of the SET USER system privilege to a user only grants the potential to impersonate another user.
Validation of the at-least criteria required to successfully impersonate another user does no occur until the
SETUSER statement is issued.

Each target user specified (target_users_list) must be an existing user or user-extended role with a login
password. Each target role specified (target_roles_list) must be an existing user-extended or user-defined role.

Privileges

Requires the CHANGE PASSWORD system privilege granted with administrative rights. See GRANT System
Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example grants Sally and Laurel the ability to impersonate Bob, Sam, and Peter:

GRANT SET USER (Bob, Sam, Peter) TO Sally, Laurel

● The following example grants Mary the right to grant the SET USER system privilege to any user in the
database. However, since the system privilege is granted with the WITH ADMIN ONLY OPTION clause,
Mary cannot impersonate any other user.

GRANT SET USER (ANY) TO Mary WITH ADMIN ONLY OPTION

● The following example grants Steve and Joe the ability to impersonate any member of Role1 or Role2:

GRANT SET USER (ANY WITH ROLES Role1, Role2) TO Steve, Joe

SAP IQ SQL Reference


1510 INTERNAL SQL Statements
Related Information

REVOKE SET USER Privilege Statement [page 1633]


REVOKE System Privilege Statement [page 1635]
REVOKE System Privilege Statement [page 1635]

9.4.125 GRANT System Privilege Statement

Grants specific system privileges to users or roles, with or without administrative rights.

 Syntax

GRANT <system_privilege_name> [, …]
TO <user_id> [, …]
[ { WITH NO ADMIN
| WITH ADMIN [ ONLY ] } OPTION ]

Parameters

system_privilege_name

Must be the name of an existing system privilege.


TO user_id

Must be the name of an existing user or immutable role. The list must consist of existing users with login
passwords. Separate multiple user_ids with commas.
WITH NO ADMIN OPTION

The user can manage the system privilege, but cannot grant the system privilege to another user.
WITH ADMIN ONLY OPTION

If the WITH ADMIN ONLY OPTION clause is used, each <user_id> is granted administrative privileges
over each <system_privilege>, but not the <system_privilege> itself.
WITH ADMIN OPTION

Each <user_id> is granted administrative privileges over each <system_privilege> in addition to all
underlying system privileges of <system_privilege>.

Remarks

By default, if no administrative clause is specified in the grant statement, the WITH NO ADMIN OPTION clause
is used.

SAP IQ SQL Reference


SQL Statements INTERNAL 1511
Privileges

You must have been granted the specific system privilege with administrative privilege.

Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

● The following example grants the DROP CONNECTION system privilege to Joe with administrative
privileges:

GRANT DROP CONNECTION TO Joe WITH ADMIN OPTION

● This example grants the CHECKPOINT system privilege to Sally with no administrative privileges:

GRANT CHECKPOINT TO Sally WITH NO ADMIN OPTION

● This example grants the MONITOR system privilege to Jane with administrative privileges only:

GRANT MONITOR TO Jane WITH ADMIN ONLY OPTION

In this section:

Alphabetical List of System Privileges [page 1513]


A list of all system privileges.

System Privileges Listed by Functional Area [page 1520]


A list of system privileges organized by functional area.

Related Information

Granting the Ability to Run a Privileged System Procedure [page 575]


REVOKE System Privilege Statement [page 1635]
PREFETCH_FP_PERCENT Option [page 1953]
Set a Database Option [page 1727]
PREFETCH_HASH_PERCENT Option [page 1955]
Set a Database Option [page 1727]
PREFETCH_LOB_PERCENT Option [page 1956]
Set a Database Option [page 1727]
PREFETCH_TEXTPOST_PERCENT Option [page 1958]

SAP IQ SQL Reference


1512 INTERNAL SQL Statements
Set a Database Option [page 1727]

9.4.125.1 Alphabetical List of System Privileges

A list of all system privileges.

System privileges control the rights of users to perform authorized database tasks.

The following is a list of available system privileges:

System Privilege Description Functional Area

ACCESS SERVER LS Allows logical server connection using the SERVER logical server Multiplex
context.

ACCESS USER PASSWORD Allows a user to access views that contain password hashes, and User and Login Man­
perform operations that involve accessing passwords, such as un­ agement
loading, extracting, or comparing database

ALTER ANY INDEX Allows a user to alter and comment on indexes and text indexes Indexes
on tables and views owned by any user.

ALTER ANY MATERIALIZED Allows a user to alter and comment on materialized views owned Materialized Views
VIEW by any user.

ALTER ANY OBJECT Allows a user to alter and comment on the following types of ob­ Objects
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

ALTER ANY OBJECT OWNER Allows a user to alter the owner of any type of table object. This Objects
privilege does not allow changing of the owner of other objects,
such as procedures, materialized views, and so on.

ALTER ANY PROCEDURE Allows a user to alter and comment on procedures and functions Procedures
owned by any user.

ALTER ANY SEQUENCE Allows a user to alter sequence generators owned by any user. Sequence

SAP IQ SQL Reference


SQL Statements INTERNAL 1513
System Privilege Description Functional Area

ALTER ANY TABLE Allows a user to: Tables

● Alter and comment on tables (including proxy tables) owned


by any user.
● Truncate tables, table partitions, or views owned by any user
● Comment on tables (including proxy tables) and columns in
tables owned by any user.

ALTER ANY TEXT CONFIGURA­ Allows a user to alter and comment on text configuration objects Text Configuration
TION owned by any user.

ALTER ANY TRIGGER Allows a user to: Triggers

● Alter triggers on tables and views.


● Issue comments on tables (also requires the ALTER object-
level privilege on the table).

ALTER ANY VIEW Allows a user to alter and comment on views owned by any user. Views

ALTER DATABASE Allows a user to: Database

● Upgrade a database.
● Perform cost model calibration.
● Load database statistics.
● Alter transaction logs (also requires the SERVER OPERATOR
system privilege).
● Change ownership of the database (also requires the MAN­
AGE ANY MIRROR SERVER system privilege).

ALTER DATATYPE Allows a user to alter data types. Data Type

BACKUP DATABASE Allows a user to back up a database. Database

CHANGE PASSWORD Allows a user to manage user passwords for any user. User and Login Man­
agement
This system privilege can apply to all users, or it can be limited to
a set of specified users, or users who are granted one or more
specified roles.

This system privilege is not required to change a user's own pass­


word.

CHECKPOINT Allows a user to force the database server to execute a check­ Database
point.

COMMENT ANY OBJECT Allows a user to comment on any type of object owned by any Objects
user that can be created using the CREATE ANY OBJECT system
privilege.

CREATE ANY INDEX Allows a user to create and comment on indexes and text indexes Indexes
on tables and views owned by any user.

CREATE ANY MATERIALIZED Allows a user to create and comment on materialized views Materialized Views
VIEW owned by any user.

CREATE ANY MUTEX SEMA­ Allows a user to create a mutex or semaphore owned by any user. Mutex and Sema­
PHORE phores

SAP IQ SQL Reference


1514 INTERNAL SQL Statements
System Privilege Description Functional Area

CREATE ANY OBJECT Allows a user to create and comment on the following types of ob­ Objects
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

CREATE ANY PROCEDURE Allows a user to create and comment on procedures and func­ Procedure
tions owned by any user.

CREATE ANY SEQUENCE Allows a user to create sequence generators, regardless of owner. Sequence

CREATE ANY TABLE Allows a user to: Table

● Create and comment on tables (including proxy tables)


owned by any user.
● Comment on columns in tables (including proxy tables)
owned by any user.

CREATE ANY TEXT CONFIGU­ Allows a user to alter and comment on text configuration objects Text Configuration
RATION owned by any user.

CREATE ANY TRIGGER Allows a user to create and comment (also requires the ALTER Triggers
object level privilege on the table) on tables and views.

CREATE ANY VIEW Allows a user to create and comment on views owned by any user. Views

CREATE DATABASE VARIABLE Allows a user to create, select from, update, and drop self-owned Database Variables
database-scope variables.

CREATE DATATYPE Allows a user to create data types. Database

CREATE EXTERNAL REFER­ Allows a user to create external references in the database. External Environment
ENCE
You must have the system privileges required to create specific
database objects before you can create external references.

For example, creating a self-owned text configuration object that


uses an external term breaker requires both the CREATE TEXT
CONFIGURATION and CREATE EXTERNAL REFERENCE system
privileges.

CREATE MATERIALIZED VIEW Allows a user to create and comment on self-owned materialized Materialized Views
views.

SAP IQ SQL Reference


SQL Statements INTERNAL 1515
System Privilege Description Functional Area

CREATE MESSAGE Allows a user to create messages. Miscellaneous

CREATE PROCEDURE Allows a user to create and comment on self-owned procedures Procedure
and functions. create a self-owned stored procedure or function.

CREATE PROXY TABLE Allows a user to create self-owned proxy tables. Table

CREATE TABLE Allows a user to: Table

● Create self-owned tables.


● Comment on self-owned columns and tables.

CREATE TEXT CONFIGURA­ Allows a user to create and comment on self-owned text configu- Text Configuration
TION ration objects.

CREATE VIEW Allows a user to create and comment on self-owned views. Re­ Views
quired to create self-owned views.

DEBUG ANY PROCEDURE Allows a user to debug any database object. Miscellaneous

DELETE ANY TABLE Allows a user to delete rows in tables and views owned by any Table
user.

DROP ANY INDEX Allows a user to drop indexes and text indexes on tables and views Indexes
owned by any user.

DROP ANY MATERIALIZED Allows a user to drop materialized views owned by any user. Materialized View
VIEW

DROP ANY MUTEX SEMA­ Allows a user to drop a mutex or semaphore owned by any user. Mutex and Sema­
PHORE phores

DROP ANY OBJECT Allows a user to drop the following types of objects owned by any Objects
user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

DROP ANY PROCEDURE Allows a user to drop procedures and functions owned by any Procedure
user.

DROP ANY SEQUENCE Allows a user to drop sequence generators owned by any user. Sequence

SAP IQ SQL Reference


1516 INTERNAL SQL Statements
System Privilege Description Functional Area

DROP ANY TABLE Allows a user to drop tables (including proxy tables) owned by any Table
user.

DROP ANY TEXT CONFIGURA­ Allows a user to drop text configuration objects owned by any Text Configuration
TION user.

DROP ANY VIEW Allows a user to drop views owned by any user. Views

DROP CONNECTION Allows a user to drop any connections to the database. Database

DROP DATATYPE Allows a user to drop data types. Database

DROP MESSAGE Allows a user to drop messages. Miscellaneous

EXECUTE ANY PROCEDURE Allows a user to execute procedures and functions owned by any Procedure
user.

INSERT ANY TABLE Allows a user to insert rows into tables and views owned by any Table
user.

LOAD ANY TABLE Allows a user to load data into tables owned by any user. Table

MANAGE ANY DATABASE VARI­ Allows a user to create and drop database-scope variables owned Database Variables
ABLE by self or by PUBLIC.

MANAGE ANY DBSPACE Allows a user to: Dbspaces

● Create, alter, drop, and comment on dbspaces.


● Grant and revoke CREATE object-level privileges on dbspa­
ces.
● Move data to any dbspace.
● Issue a read-only selective restore statement on any
dbspace.
● Run the database delete file function.

MANAGE ANY EVENT Allows a user to create, alter, drop, trigger, and comment on Miscellaneous
events.

MANAGE ANY EXTERNAL EN­ Allows a user to alter, comment on, start, and stop external envi­ External Environment
VIRONMENT ronments.

MANAGE ANY EXTERNAL OB­ Allows a user to install, comment on, and remove external envi­ External Environment
JECT ronment objects.

MANAGE ANY LDAP SERVER Allows a user to create, alter, drop, validate, and comment on Miscellaneous
LDAP servers.

MANAGE ANY LOGIN POLICY Allows a user to create, alter, drop, and comment on login poli­ User and Login Man­
cies. agement

MANAGE ANY MIRROR Allows a user to: Miscellaneous


SERVER
● Create, alter, drop, and comment on mirror servers.
● Change mirror server parameters.
● Set mirror server options.
● Change ownership of a database.

SAP IQ SQL Reference


SQL Statements INTERNAL 1517
System Privilege Description Functional Area

MANAGE ANY OBJECT PRIVI­ Allows a user to: Objects


LEGES
● Grant and revoke SELECT, INSERT, DELETE, UPDATE, AL­
TER, REFERENCES, LOAD, and TRUNCATE object-level privi­
leges on tables owned by any user.
● Grant and revoke SELECT, INSERT, DELETE, and UPDATE ob­
ject-level privileges on views owned by any user.
● Grant and revoke EXECUTE privileges on procedures and
functions owned by any user.
● Grant and revoke USAGE object-level privileges on sequence
generators owned by any user.
● Grant and revoke CREATE object-level privileges on dbspa­
ces.

MANAGE ANY PROPERTY HIS­ Allows a user to turn on and configure the tracking of database Server Operator
TORY server property values.

MANAGE ANY SPATIAL OB­ Allows a user to create, alter, drop, and comment on spatial refer­ Miscellaneous
JECT ence systems and spatial unit of measures.

MANAGE ANY STATISTICS Allows a user to create, alter, drop, and update database statistics Miscellaneous
for any table.

MANAGE ANY USER Allows a user to: User and Login Man­
agement
● Create, alter, drop, and comment on database users (includ­
ing assigning an initial password).
● Force a password change on next login for any user.
● Assign and reset the login policy for any user.
● Create, drop, and comment on integrated logins and Ker­
beros logins.
● Create and drop external logins.

MANAGE ANY WEB SERVICE Allows a user to create, alter, drop, and comment on web serv­ Miscellaneous
ices.

MANAGE AUDITING Allows a user to run the sa_audit_string stored procedure. Procedure

MANAGE LISTENERS Allows a user to start and stop network listeners. Server Operator

MANAGE MULTIPLEX Allows users to: Multiplex

● Create, alter, drop, or comment on logical servers and logical


server policies.
● Assign a dbspace to logical servers.
● Release a populated dbspace from the exclusive use of a logi­
cal server.
● Manages failover configurations, and perform a manual fail­
over.

MANAGE PROFILING Allows a user to manage database server tracing. The DIAGNOS­ Database
TICS system role is also required to fully utilize diagnostics func­
tionality for user information.

SAP IQ SQL Reference


1518 INTERNAL SQL Statements
System Privilege Description Functional Area

MANAGE ROLES Allows a user to create new roles and act as a global administrator Roles
for new and existing roles. By default, MANAGE ROLES is granted
administrative rights on each newly created role. A user requires
administrative rights on the role to delete it.

Administration of a role can also be granted directly to users ei­


ther during or after the creation of the role. When granted directly
to a user, the user does not require the MANAGE ROLES system
privilege to administer the role.

If no role administrator is specified during role creation, the MAN­


AGE ROLES system privilege is automatically granted to the role
with the ADMIN ONLY OPTION clause, allowing the global role ad­
ministrator to administer the role. If at least one role administra­
tor is specified during creation, the MANAGE ROLES system privi­
lege is not granted to the role, and global role administrators can­
not manage the role.

MONITOR Allows a user to monitor a database, including accessing privi­ Database


leged statistics, connected users, and locks.

READ CLIENT FILE Allows a user to read files on the client computer. Files

READ FILE Allows a user to read files on the database server computer. Files

REORGANIZE ANY OBJECT Allows a user to reorganize tables and materialized views owned Objects
by any user.

SELECT ANY TABLE Allows a user to query tables and views owned by any user. Table

SELECT PUBLIC DATABASE Allows a user to select the value of a database-scope variable Database Variables
VARIABLE owned by PUBLIC.

SERVER OPERATOR Allows a user to: Server Operator

● Create, drop, change ownership of a database, and restore


the catalog (only).
● Create, alter, and drop a server.
● Manage a server cache.
● Start and stop database or database engine.
● Encrypt databases.
● Change a database transaction log.

SET ANY PUBLIC OPTION Allows a user to set PUBLIC database options that do not require Database Options
the SET ANY SECURITY OPTION or the SET ANY SYSTEM OP­
TION system privileges.

SET ANY SECURITY OPTION Allows a user to set any PUBLIC security database options. Database Options

SET ANY SYSTEM OPTION Allows a user to set PUBLIC system database options. Database Options

SET ANY USER DEFINED OP­ Allows a user to set user-defined database options. Database Options
TION

SAP IQ SQL Reference


SQL Statements INTERNAL 1519
System Privilege Description Functional Area

SET USER (granted with admin­ Allows a user to temporarily assume the roles and privileges of User and Login Man­
istrative rights only) another user. agement

This system privilege can apply to all users, or can be limited to a


set of specified users, or users who are granted one or more
specified roles.

TRUNCATE ANY TABLE Allows a user to truncate data for tables and materialized views Table
owned by any user.

UPDATE ANY MUTEX SEMA­ Allows a user to update a mutex or semaphore owned by any Mutex and Sema­
PHORE user. phores

UPDATE ANY TABLE Allows a user to update rows in tables and views owned by any Table
user.

UPDATE PUBLIC DATABASE Allows a user to update database-scope variables owned by PUB­ Database Variables
VARIABLE LIC.

UPGRADE ROLE Allows a user to be a default administrator of any system privilege Roles
that is introduced when upgrading an SAP IQ database from ver­
sion 16.0. By default, the UPGRADE ROLE system privilege is
granted to the SYS_AUTH_SA_ROLE role, if it exists.

USE ANY SEQUENCE Allows a user to use sequence generators owned by any user. Sequence

VALIDATE ANY OBJECT Allows a user to validate tables, materialized views, indexes, and Objects
text indexes owned by any user.

WRITE CLIENT FILE Allows a user to write files to the client computer. Files

WRITE FILE Allows a user to write files on the database server computer. Files

9.4.125.2 System Privileges Listed by Functional Area

A list of system privileges organized by functional area.

Functional Area System Privilege Description

Database Options SET ANY PUBLIC OPTION Allows a user to set PUBLIC database options that do not require
the SET ANY SECURITY OPTION or the SET ANY SYSTEM OP­
TION system privileges.

SET ANY SECURITY OPTION Allows a user to set any PUBLIC security database options.

SET ANY SYSTEM OPTION Allows a user to set PUBLIC system database options.

SET ANY USER DEFINED OP­ Allows a user to set user-defined database options.
TION

Database Variables CREATE DATABASE VARIABLE Allows a user to create, select from, update, and drop self-owned
database-scope variables.

MANAGE ANY DATABASE VARI­ Allows a user to create and drop database-scope variables owned
ABLE by self or by PUBLIC.

SAP IQ SQL Reference


1520 INTERNAL SQL Statements
Functional Area System Privilege Description

SELECT PUBLIC DATABASE Allows a user to select the value of a database-scope variable
VARIABLE owned by PUBLIC.

UPDATE PUBLIC DATABASE Allows a user to update database-scope variables owned by PUB­
VARIABLE LIC.

Database CHECKPOINT Allows a user to force the database server to execute a check­
point.

DROP DATATYPE Allows a user to drop data types.

MANAGE PROFILING Allows a user to manage database server tracing. The DIAGNOS­
TICS system role is also required to fully utilize diagnostics func­
tionality for user information.

MONITOR Allows a user to monitor a database, including accessing privi­


leged statistics, connected users, and locks.

ALTER DATABASE Allows a user to:

● Upgrade a database.
● Perform cost model calibration.
● Load database statistics.
● Alter transaction logs (also requires the SERVER OPERATOR
system privilege).
● Change ownership of the database (also requires the MAN­
AGE ANY MIRROR SERVER system privilege).

BACKUP DATABASE Allows a user to back up a database.

CREATE DATATYPE Allows a user to create data types.

DROP CONNECTION Allows a user to drop any connections to the database.

MANAGE ANY DBSPACE Allows a user to:

● Create, alter, drop, and comment on dbspaces.


● Grant and revoke CREATE object-level privileges on dbspa­
ces.
● Move data to any dbspace.
● Issue a read-only selective restore statement on any
dbspace.
● Run the database delete file function.

External Environment CREATE EXTERNAL REFER­ Allows a user to create external references in the database.
ENCE
You must have the system privileges required to create specific
database objects before you can create external references.

For example, creating a self-owned text configuration object that


uses an external term breaker requires both the CREATE TEXT
CONFIGURATION and CREATE EXTERNAL REFERENCE system
privileges.

MANAGE ANY EXTERNAL EN­ Allows a user to alter, comment on, start, and stop external envi­
VIRONMENT ronments.

MANAGE ANY EXTERNAL OB­ Allows a user to install, comment on, and remove external envi­
JECT ronment objects.

SAP IQ SQL Reference


SQL Statements INTERNAL 1521
Functional Area System Privilege Description

Files READ CLIENT FILE Allows a user to read files on the client computer.

READ FILE Allows a user to read files on the database server computer.

WRITE CLIENT FILE Allows a user to write files to the client computer.

WRITE FILE Allows a user to write files on the database server computer.

Indexes ALTER ANY INDEX Allows a user to alter and comment on indexes and text indexes
on tables and views owned by any user.

CREATE ANY INDEX Allows a user to create and comment on indexes and text indexes
on tables and views owned by any user.

DROP ANY INDEX Allows a user to drop indexes and text indexes on tables and views
owned by any user.

Materialized View DROP ANY MATERIALIZED Allows a user to drop materialized views owned by any user.
VIEW

ALTER ANY MATERIALIZED Allows a user to alter and comment on materialized views owned
VIEW by any user.

CREATE ANY MATERIALIZED Allows a user to create and comment on materialized views
VIEW owned by any user.

CREATE MATERIALIZED VIEW Allows a user to create and comment on self-owned materialized
views.

Miscellaneous ALTER DATATYPE Allows a user to alter data types.

CREATE MESSAGE Allows a user to create messages.

DEBUG ANY PROCEDURE Allows a user to debug any database object.

DROP MESSAGE Allows a user to drop messages.

MANAGE ANY EVENT Allows a user to create, alter, drop, trigger, and comment on
events.

MANAGE ANY LDAP SERVER Allows a user to create, alter, drop, validate, and comment on
LDAP servers.

MANAGE ANY MIRROR Allows a user to:


SERVER
● Create, alter, drop, and comment on mirror servers.
● Change mirror server parameters.
● Set mirror server options.
● Change ownership of a database.

MANAGE ANY SPATIAL OB­ Allows a user to create, alter, drop, and comment on spatial refer­
JECT ence systems and spatial unit of measures.

MANAGE ANY STATISTICS Allows a user to create, alter, drop, and update database statistics
for any table.

MANAGE ANY WEB SERVICE Allows a user to create, alter, drop, and comment on web serv­
ices.

Multiplex ACCESS SERVER LS Allows logical server connection using the SERVER logical server
context.

SAP IQ SQL Reference


1522 INTERNAL SQL Statements
Functional Area System Privilege Description

MANAGE MULTIPLEX Allows users to:

● Create, alter, drop, or comment on logical servers and logical


server policies.
● Assign a dbspace to logical servers.
● Release a populated dbspace from the exclusive use of a logi­
cal server.
● Manages failover configurations, and perform a manual fail­
over.

Mutex and Sema­ CREATE ANY MUTEX SEMA­ Allows a user to create a mutex or semaphore owned by any user.
phores PHORE

DROP ANY MUTEX SEMA­ Allows a user to drop a mutex or semaphore owned by any user.
PHORE

UPDATE ANY MUTEX SEMA­ Allows a user to update a mutex or semaphore owned by any
PHORE user.

Objects ALTER ANY OBJECT OWNER Allows a user to alter the owner of any type of table object. This
privilege does not allow changing of the owner of other objects,
such as procedures, materialized views, and so on.

ALTER ANY OBJECT Allows a user to alter and comment on the following types of ob­
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

COMMENT ANY OBJECT Allows a user to comment on any type of object owned by any
user that can be created using the CREATE ANY OBJECT system
privilege.

SAP IQ SQL Reference


SQL Statements INTERNAL 1523
Functional Area System Privilege Description

CREATE ANY OBJECT Allows a user to create and comment on the following types of ob­
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

DROP ANY OBJECT Allows a user to drop the following types of objects owned by any
user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

SAP IQ SQL Reference


1524 INTERNAL SQL Statements
Functional Area System Privilege Description

MANAGE ANY OBJECT PRIVI­ Allows a user to:


LEGES
● Grant and revoke SELECT, INSERT, DELETE, UPDATE, AL­
TER, REFERENCES, LOAD, and TRUNCATE object-level privi­
leges on tables owned by any user.
● Grant and revoke SELECT, INSERT, DELETE, and UPDATE ob­
ject-level privileges on views owned by any user.
● Grant and revoke EXECUTE privileges on procedures and
functions owned by any user.
● Grant and revoke USAGE object-level privileges on sequence
generators owned by any user.
● Grant and revoke CREATE object-level privileges on dbspa­
ces.

REORGANIZE ANY OBJECT Allows a user to reorganize tables and materialized views owned
by any user.

VALIDATE ANY OBJECT Allows a user to validate tables, materialized views, indexes, and
text indexes owned by any user.

Procedures ALTER ANY PROCEDURE Allows a user to alter and comment on procedures and functions
owned by any user.

CREATE ANY PROCEDURE Allows a user to create and comment on procedures and func­
tions owned by any user.

CREATE PROCEDURE Allows a user to create and comment on self-owned procedures


and functions. create a self-owned stored procedure or function.

DROP ANY PROCEDURE Allows a user to drop procedures and functions owned by any
user.

EXECUTE ANY PROCEDURE Allows a user to execute procedures and functions owned by any
user.

MANAGE AUDITING Allows a user to run the sa_audit_string stored procedure.

Roles MANAGE ROLES Allows a user to create new roles and act as a global administrator
for new and existing roles. By default, MANAGE ROLES is granted
administrative rights on each newly created role. A user requires
administrative rights on the role to delete it.

Administration of a role can also be granted directly to users ei­


ther during or after the creation of the role. When granted directly
to a user, the user does not require the MANAGE ROLES system
privilege to administer the role.

If no role administrator is specified during role creation, the MAN­


AGE ROLES system privilege is automatically granted to the role
with the ADMIN ONLY OPTION clause, allowing the global role ad­
ministrator to administer the role. If at least one role administra­
tor is specified during creation, the MANAGE ROLES system privi­
lege is not granted to the role, and global role administrators can­
not manage the role.

SAP IQ SQL Reference


SQL Statements INTERNAL 1525
Functional Area System Privilege Description

UPGRADE ROLE Allows a user to be a default administrator of any system privilege


that is introduced when upgrading an SAP IQ database from ver­
sion 16.0. By default, the UPGRADE ROLE system privilege is
granted to the SYS_AUTH_SA_ROLE role, if it exists.

Sequence ALTER ANY SEQUENCE Allows a user to alter sequence generators owned by any user.

CREATE ANY SEQUENCE Allows a user to create sequence generators, regardless of owner.

DROP ANY SEQUENCE Allows a user to drop sequence generators owned by any user.

USE ANY SEQUENCE Allows a user to use sequence generators owned by any user.

Server Operator MANAGE ANY PROPERTY HIS­ Allows a user to turn on and configure the tracking of database
TORY server property values.

MANAGE LISTENERS Allows a user to start and stop network listeners.

SERVER OPERATOR Allows a user to:

● Create, drop, change ownership of a database, and restore


the catalog (only).
● Create, alter, and drop a server.
● Manage a server cache.
● Start and stop database or database engine.
● Encrypt databases.
● Change a database transaction log.

Table CREATE PROXY TABLE Allows a user to create self-owned proxy tables.

CREATE TABLE Allows a user to:

● Create self-owned tables.


● Comment on self-owned columns and tables.

DELETE ANY TABLE Allows a user to delete rows in tables and views owned by any
user.

DROP ANY TABLE Allows a user to drop tables (including proxy tables) owned by any
user.

INSERT ANY TABLE Allows a user to insert rows into tables and views owned by any
user.

LOAD ANY TABLE Allows a user to load data into tables owned by any user.

SELECT ANY TABLE Allows a user to query tables and views owned by any user.

TRUNCATE ANY TABLE Allows a user to truncate data for tables and materialized views
owned by any user.

UPDATE ANY TABLE Allows a user to update rows in tables and views owned by any
user.

CREATE ANY TABLE Allows a user to:

● Create and comment on tables (including proxy tables)


owned by any user.
● Comment on columns in tables (including proxy tables)
owned by any user.

SAP IQ SQL Reference


1526 INTERNAL SQL Statements
Functional Area System Privilege Description

ALTER ANY TABLE Allows a user to:

● Alter and comment on tables (including proxy tables) owned


by any user.
● Truncate tables, table partitions, or views owned by any user
● Comment on tables (including proxy tables) and columns in
tables owned by any user.

Text Configuration ALTER ANY TEXT CONFIGURA­ Allows a user to alter and comment on text configuration objects
TION owned by any user.

CREATE TEXT CONFIGURA­ Allows a user to create and comment on self-owned text configu-
TION ration objects.

DROP ANY TEXT CONFIGURA­ Allows a user to drop text configuration objects owned by any
TION user.

CREATE ANY TEXT CONFIGU­ Allows a user to alter and comment on text configuration objects
RATION owned by any user.

Triggers ALTER ANY TRIGGER Allows a user to:

● Alter triggers on tables and views.


● Issue comments on tables (also requires the ALTER object-
level privilege on the table).

CREATE ANY TRIGGER Allows a user to create and comment (also requires the ALTER
object level privilege on the table) on tables and views.

ACCESS USER PASSWORD Allows a user to access views that contain password hashes, and
perform operations that involve accessing passwords, such as un­
loading, extracting, or comparing database

CHANGE PASSWORD Allows a user to manage user passwords for any user.

This system privilege can apply to all users, or it can be limited to


a set of specified users, or users who are granted one or more
specified roles.

This system privilege is not required to change a user's own pass­


word.

MANAGE ANY LOGIN POLICY Allows a user to create, alter, drop, and comment on login poli­
cies.

MANAGE ANY USER Allows a user to:

● Create, alter, drop, and comment on database users (includ­


ing assigning an initial password).
● Force a password change on next login for any user.
● Assign and reset the login policy for any user.
● Create, drop, and comment on integrated logins and Ker­
beros logins.
● Create and drop external logins.

SAP IQ SQL Reference


SQL Statements INTERNAL 1527
Functional Area System Privilege Description

SET USER (granted with admin­ Allows a user to temporarily assume the roles and privileges of
istrative rights only) another user.

This system privilege can apply to all users, or can be limited to a


set of specified users, or users who are granted one or more
specified roles.

Views ALTER ANY VIEW Allows a user to alter and comment on views owned by any user.

CREATE ANY VIEW Allows a user to create and comment on views owned by any user.

CREATE VIEW Allows a user to create and comment on self-owned views. Re­
quired to create self-owned views.

DROP ANY VIEW Allows a user to drop views owned by any user.

9.4.126 GRANT USAGE ON SEQUENCE Privilege Statement

Grants the USAGE system privilege on a specified sequence to a user or role.

 Syntax

GRANT USAGE ON SEQUENCE <sequence-name>


TO <user_id> [, …]

Parameters

user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires one of:

● You own the sequence


● MANAGE ANY OBJECT PRIVILEGE

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

SAP IQ SQL Reference


1528 INTERNAL SQL Statements
Standards

● SQL – syntax is a Persistent Stored Module feature.


● SAP database products – the security model is different in SAP ASE and SAP IQ, so other syntaxes differ.

Related Information

REVOKE USAGE ON SEQUENCE Privilege Statement [page 1653]


REVOKE System Privilege Statement [page 1635]
REVOKE USAGE ON SEQUENCE Privilege Statement [page 1653]

9.4.127 IF Statement

Lets you conditionally execute the first list of SQL statements whose <search-condition> evaluates to
TRUE.

 Syntax

IF <search-condition> THEN <statement-list>


... [ ELSEIF <search-condition> THEN <statement-list> ]...
... [ ELSE <statement-list> ]
... END IF

Remarks

If no <search-condition> evaluates to TRUE, and an ELSE clause exists, the <statement-list> in the
ELSE clause is executed. If no <search-condition> evaluates to TRUE, and there is no ELSE clause, the
expression returns a NULL value.

Execution resumes at the first statement after the END IF.

When comparing variables to the single value returned by a SELECT statement inside an IF statement, you
must first assign the result of the SELECT to another variable.

 Note

Do not confuse the syntax of the IF statement with that of the IF expression. You cannot nest the IF
statement.

SAP IQ SQL Reference


SQL Statements INTERNAL 1529
Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – the Transact-SQL IF statement has a slightly different syntax.

Examples

● The following example illustrates the use of the IF statement:

CREATE PROCEDURE TopCustomer (OUT TopCompany CHAR(35), OUT TopValue INT)


BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE '02000' ;
DECLARE curThisCust CURSOR FOR
SELECT CompanyName, CAST( sum(SalesOrderItems.Quantity *
Products.UnitPrice) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrsderItems
LEFT OUTER JOIN Product
GROUP BY CompanyName ;
DECLARE ThisValue INT ;
DECLARE ThisCompany CHAR(35) ;
SET TopValue = 0 ;
OPEN curThisCust ;
CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue ;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop ;
END IF ;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue ;
SET TopCompany = ThisCompany ;
END IF ;
END LOOP CustomerLoop ;
CLOSE curThisCust ;
END

● The following example illustrates the use of the ELSEIF statement:

BEGIN
DECLARE X INT;
SET X = 1;
IF X = 1 THEN
PRINT '1';
ELSEIF X = 2 THEN
PRINT '2';
ELSE
PRINT 'something else';

SAP IQ SQL Reference


1530 INTERNAL SQL Statements
ENDIF
END

Related Information

BEGIN … END Statement [page 1218]


REVOKE System Privilege Statement [page 1635]

9.4.128 IF Statement [T-SQL]

Provides conditional execution of a Transact-SQL statement, as an alternative to the SAP IQ IF statement.

 Syntax

IF <expression>
... <statement>
... [ ELSE [ IF <expression> ] <statement> ]...

Remarks

The Transact-SQL IF conditional and the ELSE conditional each control the performance of only a single SQL
statement or compound statement (between the keywords BEGIN and END).

In contrast to the SAP IQ IF statement, the Transact-SQL IF statement has no THEN. The Transact-SQL
version also has no ELSEIF or END IF keywords.

When comparing variables to the single value returned by a SELECT statement inside an IF statement, you
must first assign the result of the SELECT to another variable.

 Note

You cannot nest the IF statement.

Privileges

None

SAP IQ SQL Reference


SQL Statements INTERNAL 1531
Standards

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

● The following example uses 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 example uses of the Transact-SQL ELSEIF statement:

BEGIN
DECLARE @X INT
SET @X = 1
IF @X = 1
PRINT '1'
ELSEIF @X = 2
PRINT '2'
ELSE
PRINT 'something else'
END

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.129 INCLUDE Statement [ESQL]

Includes a file into a source program to be scanned by the SQL source language preprocessor.

 Syntax

INCLUDE <filename>

SAP IQ SQL Reference


1532 INTERNAL SQL Statements
Parameters

filename

Identifier

Remarks

The INCLUDE statement is very much like the C preprocessor #include directive.

However, the SQL preprocessor reads the given file, inserting its contents into the output C file. Thus, if an
include file contains information that the SQL preprocessor requires, it should be included with the Embedded
SQL INCLUDE statement.

Two file names are specially recognized: SQLCA and SQLDA. Any C program using Embedded SQL must
contain this statement before any Embedded SQL statements:

EXEC SQL INCLUDE SQLCA;

This statement must appear at a position in the C program where static variable declarations are allowed.
Many Embedded SQL statements require variables (invisible to the programmer) which are declared by the
SQL preprocessor at the position of the SQLCA include statement. The SQLDA file must be included if any
SQLDAs are used.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1533
9.4.130 INSERT Statement

Inserts a single row or a selection of rows, from elsewhere in the current database, into the table. This
command can also insert a selection of rows from another database into the table.

 Syntax

Syntax 1

INSERT [ INTO ] [ <owner>.]<table-name> [ ( <column-name> [, …] ) ]


... VALUES ( [ <expression> | DEFAULT,… ) ]
or
INSERT [ INTO ] [ <owner>.]<table-name> DEFAULT VALUES

Syntax 2

INSERT [ INTO ] [ <owner>.]<table-name> [ ( <column-name> [, …] ) ]


... <insert-load-options> <insert-select-load-options>
... <select-statement>

Syntax 3

INSERT [ INTO ] [ <owner>.]<table-name>[ ( <column-name> [, …] ) ]


... <insert-select-load-options> <insert-select-load-options>
LOCATION '<servername.dbname>'
[ <location-options> ]
... { { <select-statement> } | '<select statement>' }

<insert-load-options> ::=
[ LIMIT <number-of-rows> ]
[ NOTIFY <number-of-rows> ]
[ SKIP <number-of-rows> ]

<insert-select-load-options> ::=
[ WORD SKIP <number> ]
[ IGNORE CONSTRAINT <constraint-type> [, …] ]
[ MESSAGE LOG '<string>' ROW LOG '<string>' [ ONLY LOG <logwhat> [, …] ] ]
[ LOG DELIMITED BY '<string>' ]

<constraint-type> ::=
{ CHECK <integer>
| UNIQUE <integer>
| NULL <integer>
| FOREIGN KEY <integer>
| DATA VALUE <integer>
} ALL <integer> }

<logwhat> ::=
{ CHECK
| ALL
| NULL
| UNIQUE
| DATA VALUE
| FOREIGN KEY
| WORD }

Go to:

● Remarks

SAP IQ SQL Reference


1534 INTERNAL SQL Statements
● Privileges
● Standards
● Examples

Parameters

(back to top)

insert-load-options

Options that constrain the load:

● LIMIT – specifies the maximum number of rows to insert into the table from a query. The default is 0
for no limit. The maximum is 2 GB -1.
● NOTIFY – specifies that you be notified with a message each time the number of rows are successfully
inserted into the table. The default is every 100,000 rows.
● SKIP – defines the number of rows to skip at the beginning of the input tables for this insert. The
default is 0.
WORD SKIP

Allows the load to continue when it encounters data longer than the limit specified when the word index
was created. The <number> parameter specifies the number of times to ignore the error. Setting this
option to 0 means there is no limit.

If a row is not loaded because a word exceeds the maximum permitted size, a warning is written to
the .iqmsg file. WORD size violations can be optionally logged to the MESSAGE LOG file. If the option is
not specified, the operation rolls back on the first occurrence of a word that is longer than the specified
limit.
IGNORE CONSTRAINT

Determines whether the load engine ignores CHECK, UNIQUE, NULL, DATA VALUE, and FOREIGN KEY
integrity constraint violations that occur during a load and the maximum number of violations to ignore
before initiating a rollback.

If <limit> is zero, the number of CHECK constraint violations to ignore is infinite. If CHECK is not
specified, the first occurrence of any CHECK constraint violation causes the load to roll back. If <limit> is
nonzero, then the <limit> +1 occurrence of a CHECK constraint violation causes the load to roll back
MESSAGE LOG

Specifies the file names where the load engine logs integrity constraint violations. Timestamps indicating
the start and completion of the load are logged in both the MESSAGE LOG and the ROW LOG files. Both
MESSAGE LOG and ROW LOG must be specified, or no information about integrity violations is logged.

Information is logged on all integrity constraint-type violations specified in the ONLY LOG clause or for all
word index-length violations if the keyword WORD is specified. If the ONLY LOG clause is not specified, no
information on integrity constraint violations is logged. Only the timestamps indicating the start and
completion of the load are logged.
LOG DELIMITED BY

Specifies the separator between data values in the ROW LOG file. The default separator is a comma.
ENCRYPTED PASSWORD

SAP IQ SQL Reference


SQL Statements INTERNAL 1535
Specifies the use of Open Client Library default password encryption when connecting to a remote server.
If you specify this parameter and the remote server does not support Open Client Library default password
encryption, an error is reported indicating that an invalid user ID or password was used.

To enable the SAP IQ server to accept a jConnect connection with an encrypted password, set the jConnect
ENCRYPT_PASSWORD connection property to true.
PACKETSIZE

Specifies the TDS packet-size in bytes. The default TDS packet-size on most platforms is 512 bytes. If the
packet size is not specified or is specified as zero, then the default packet size value for the platform is
used.

The packet-size value must be a multiple of 512, either equal to the default network packet size or between
the default network packet size and the maximum network packet size. The maximum network packet size
and the default network packet size are multiples of 512 in the range 512 – 524288 bytes. The maximum
network packet size is always greater than or equal to the default network packet size.
QUOTED_IDENTIFIER

Sets the QUOTED_IDENTIFIER option on the remote server. The default setting is OFF. You set
QUOTED_IDENTIFIER to ON only if any of the identifiers in the SELECT statement are enclosed in double
quotes, as in this example using "c1":

INSERT INTO foo


LOCATION 'ase.database'
QUOTED_IDENTIFIER ON {select "c1" from xxx};

ISOLATION LEVEL

Specifies an isolation level for the connection to a remote server. The levels and their characteristics are:

● READ UNCOMMITTED
○ Isolation level 0
○ Read permitted on row with or without write lock
○ No read locks are applied
○ No guarantee that concurrent transaction will not modify row or roll back changes to row
● READ COMMITTED
○ Isolation level 1
○ Read only permitted on row with no write lock
○ Read lock acquired and held for read on current row only, but released when cursor moves off the
row
○ No guarantee that data will not change during transaction
● SERIALIZABLE
○ Isolation level 3
○ Read only permitted on rows in result without write lock
○ Read locks acquired when cursor is opened and held until transaction ends

 Note

For additional information on the insert-select-load-options and location-options as well as the constraint-
type and logwhat parameters, see LOAD TABLE Statement.

SAP IQ SQL Reference


1536 INTERNAL SQL Statements
Remarks

(back to top)

Syntax 1 allows the insertion of a single row with the specified expression values. 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 allows the user to perform a mass insertion into a table using the results of a fully general SELECT
statement. Insertions are done in an arbitrary order unless the SELECT statement contains an ORDER BY
clause. The columns from the select list are matched ordinally with the columns specified in the column list, or
sequentially in the order in which the columns were created.

 Note

The NUMBER(*) function is useful for generating primary keys with Syntax 2 of the INSERT statement.

Syntax 3 INSERT...LOCATION is a variation of Syntax 2 that allows you to insert data from an SAP Adaptive
Server Enterprise or SAP IQ database. The <servername.dbname> specified in the LOCATION clause
identifies the remote server and database for the table in the FROM clause. To use Syntax 3, the SAP ASE or
SAP IQ remote server to which you are connecting must exist in the SAP Open Client interfaces or sql.ini
file on the local machine.

In queries using Syntax 3, you can insert a maximum of 2147483647 rows.

The SELECT statement can be delimited by either curly braces or straight single quotation marks.

 Note

Curly braces represent the start and end of an escape sequence in the ODBC standard, and might generate
errors in the context of ODBC or SAP IQ Cockpit. The workaround is to use single quotes to escape the
SELECT statement.

The local SAP IQ server connects to the server and database you specify in the LOCATION clause. The results
from the queries on the remote tables are returned and the local server inserts the results in the current
database. If you do not specify a server name in the LOCATION clause, SAP IQ ignores any database name you
specify, since the only choice is the current database on the local server.

When SAP IQ connects to the remote server, INSERT...LOCATION uses the remote login for the user ID of the
current connection, if a remote login has been created with CREATE EXTERNLOGIN and the remote server has
been defined with a CREATE SERVER statement. If the remote server is not defined, or if a remote login has not
been created for the user ID of the current connection, SAP IQ connects using the user ID and password of the
current connection.

 Note

If you rely on the user ID and password of the current connection, and a user changes the password, you
must stop and restart the server before the new password takes effect on the remote server. Remote logins
created with CREATE EXTERNLOGIN are unaffected by changes to the password for the default user ID.

Creating a remote login with the CREATE EXTERNLOGIN statement and defining a remote server with a
CREATE SERVER statement sets up an external login and password for INSERT...LOCATION such that any

SAP IQ SQL Reference


SQL Statements INTERNAL 1537
user can use the login and password in any context. This avoids possible errors due to inaccessibility of the
login or password, and is the recommended way to connect to a remote server.

For example, user russid connects to the SAP IQ database and executes this statement:

INSERT local_SQL_Types LOCATION 'ase1.ase1db'


{SELECT int_col FROM SQL_Types};

On server ase1, there exists user ID ase1user with password mydatabase. The owner of the table
SQL_Types is ase1user. The remote server is defined on the IQ server as:

CREATE SERVER ase1 CLASS 'ASEODBC'


USING 'system1:4100';

The external login is defined on the IQ server as:

CREATE EXTERNLOGIN russid TO ase1 REMOTE LOGIN ase1user IDENTIFIED BY mydatabase;

INSERT...LOCATION connects to the remote server ase1 using the user ID ase1user and the password
mydatabase for user russid.

Use the ENCRYPTED PASSWORD parameter to specify the use of Open Client Library default password
encryption when connecting to a remote server. If ENCRYPTED PASSWORD is specified and the remote server
does not support Open Client Library default password encryption, an error is reported indicating that an
invalid user ID or password was used.

When used as a remote server, SAP IQ supports TDS password encryption. The SAP IQ server accepts a
connection with an encrypted password sent by the client. For information on connection properties to set for
password encryption, see Security Handshaking: Encrypted Password in the Client-Library/C Reference
Manual.

 Note

Password encryption requires Open Client 15.0. TDS password encryption requires Open Client 15.0 ESD
#7 or later.

When INSERT...LOCATION is transferring data between an SAP IQ server and a remote SAP IQ or SAP ASE
server, the value of the INSERT...LOCATION TDS PACKETSIZE parameter is always 512 bytes, even if you
specify a different value for PACKETSIZE.

 Note

If you specify an incorrect packet size (for example 933, which is not a multiple of 512), the connection
attempt fails with an Open Client ct_connect “Connection failed” error. Any unsuccessful connection
attempt returns a generic “Connection failed” message. The SAP ASE error log might contain more specific
information about the cause of the connection failure.

SAP IQ does not support the SAP ASE data type TEXT, but you can execute INSERT...LOCATION (Syntax 3)
from both an IQ CHAR or VARCHAR column whose length is greater than 255 bytes, and from an ASE database
column of data type TEXT. ASE TEXT and IMAGE columns can be inserted into columns of other SAP IQ data
types, if SAP IQ supports the internal conversion. By default, if a remote data column contains over 2 GB, SAP
IQ silently truncates the column value to 2 GB.

SAP IQ SQL Reference


1538 INTERNAL SQL Statements
 Caution

SAP IQ does not support the SAP ASE data types UNICHAR, UNIVARCHAR, or UNITEXT. An
INSERT...LOCATION command from UNICHAR or UNITEXT to CHAR or CLOB columns in the ISO_BINENG
collation may execute without error; if this happens, the data in the columns may be inconsistent. An error
is reported in this situation, only if the conversion fails.

Users must be specifically licensed to use the large object functionality of the Unstructured Data Analytics
Option.

 Note

If you use INSERT...LOCATION to insert data selected from a VARBINARY column, set
ASE_BINARY_DISPLAY to OFF on the remote database.

INSERT...LOCATION (Syntax 3) does not support the use of variables in the SELECT statement.

Inserts can be done into views, provided the SELECT statement defining the view has only one table in the
FROM clause and does not contain a GROUP BY clause, an aggregate function, or involve a UNION operation.

Character strings inserted into tables are always stored in the case they are entered, regardless of whether the
database is case-sensitive or not. Thus, a string “Value” inserted into a table is always held in the database with
an 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.

Whenever you execute an INSERT...LOCATION statement, SAP IQ loads the localization information needed
to determine language, collation sequence, character set, and date/time format. If your database uses a
nondefault locale for your platform, you must set an environment variable on your local client to ensure that
SAP IQ loads the correct information.

If you set the LC_ALL environment variable, SAP IQ uses its value as the locale name. If LC_ALL is not set, SAP
IQ uses the value of the LANG environment variable. If neither variable is set, SAP IQ uses the default entry in
the locales file.

Use the (DEFAULT), DEFAULT VALUES or VALUES() clauses to insert rows with all default values. Assuming
that there are 3 columns in table t2, these examples are semantically equivalent:

INSERT INTO t2 values (DEFAULT, DEFAULT, DEFAULT);

INSERT INTO t2 DEFAULT VALUES;

INSERT INTO t2() VALUES();

INSERT...VALUES also supports multiple rows. The following example inserts 3 rows into table t1:

CREATE TABLE t1(c1 varchar(30));


INSERT INTO t1 VALUES ('morning'),('afternoon'),
('evening');

SAP IQ treats all load/inserts as full-width inserts. Columns not explicitly specified on the load/insert
statement, the value loaded will either be the column’s DEFAULT value (if one is defined) or NULL (if no
DEFAULT value is defined for the column).

SAP IQ SQL Reference


SQL Statements INTERNAL 1539
SAP IQ supports column DEFAULT values for INSERT...VALUES, INSERT...SELECT, and
INSERT...LOCATION. If a DEFAULT value is specified for a column, this DEFAULT value is used as the value of
the column in any INSERT (or LOAD) statement that does not specify a value for the column.

An INSERT from a stored procedure or function is not permitted, if the procedure or function uses COMMIT,
ROLLBACK, or some ROLLBACK TO SAVEPOINT statements.

The result of a SELECT…FROM may be slightly different from the result of an INSERT…SELECT…FROM due to an
internal data conversion of an imprecise data type, such as DOUBLE or NUMERIC, for optimization during the
insert. If a more precise result is required, a possible workaround is to declare the column as a DOUBLE or
NUMERIC data type with a higher precision.

Privileges

(back to top)

Requires the INSERT object-level privilege on the table. See GRANT Object-Level Privilege Statement [page
1502] for assistance with granting privileges

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise (excluding the <insert-load-
options>).

Examples

(back to top)

● The following example adds an Eastern Sales department to the database:

INSERT INTO Departments


(DepartmentID, DepartmentName, DepartmentHeadID)
VALUES (600, 'Eastern Sales', 501)

● The following example fills the table dept_head with the names of department heads and their
departments:

INSERT INTO dept_head (name, dept)


NOTIFY 20
SELECT Surname || ' ' || GivenName
AS name,
dept_name
FROM Employees JOIN Departments
ON EmployeeID= DepartmentHeadID

SAP IQ SQL Reference


1540 INTERNAL SQL Statements
● The following example inserts data from the l_shipdate and l_orderkey columns of the lineitem
table from the SAP IQ database iqdet on the remote server detroit into the corresponding columns of
the lineitem table in the current database:

INSERT INTO lineitem


(l_shipdate, l_orderkey)
LOCATION 'detroit.iqdet'
PACKETSIZE 512
' SELECT l_shipdate, l_orderkey
FROM lineitem '

● The INSERT statement permits a list of values allowing several rows to be inserted at once:

INSERT into t1 values( 10, 20, 30 ), ( 11, 21, 31 ), ( 12, 22, 32 )

Related Information

CREATE EXTERNLOGIN Statement [page 1271]


DELETE Statement [page 1424]
LOAD TABLE Statement [page 1549]
REVOKE System Privilege Statement [page 1635]

9.4.131 INSTALL JAVA Statement

Makes Java classes available for use within a database.

 Syntax

INSTALL JAVA [ <install-mode> ] [ JAR <jar-name> ]


FROM <source>

<install-mode> ::= { NEW | UPDATE }

<source> ::=
{ FILE <file-name> | URL <url-value> }

Go to:

● Remarks
● Privileges
● Standards
● Examples

SAP IQ SQL Reference


SQL Statements INTERNAL 1541
Parameters

(back to top)

NEW

(Default) requires that the referenced Java classes 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 clause is used.
UPDATE

An install mode of specifies that the referenced Java classes may include replacements for Java classes
already installed in the given database.
JAR

A character string value of up to 255 bytes that is used to identify the retained JAR in subsequent
INSTALL, UPDATE, and REMOVE statements. <jar-name> or text-pointer must designate a JAR file or a
column containing a JAR. JAR files typically have extensions of .jar or .zip.

Installed JAR and zip files can be compressed or uncompressed. However, JAR files produced by the Sun
JDK jar utility are not supported. Files produced by other zip utilities are supported.

If the JAR option is specified, then 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 set of JARs installed in a database
with the JAR clause are called the retained JARs of the database.

Retained JARs are referenced in INSTALL and REMOVE statements. Retained JARs have no effect on other
uses of Java-SQL classes. Retained JARs are used by the SQL system for requests by other systems for the
class associated with given data. If a requested class has an associated JAR, the SQL system can supply
that JAR, rather than the individual class.
source

Specifies the location of the Java classes to be installed and must identify either a class file or a JAR file.

The formats supported for <file-name> include fully qualified file names, such as 'c:\libs
\jarname.jar' and '/usr/u/libs/jarname.jar', and relative file names, which are relative to the
current working directory of the database server.

The class definition for each class is loaded by the VM of each connection 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 uses an install-mode clause of NEW or UPDATE.

For other connections, the new class is loaded the next time a VM accesses the class for the first time. If
the class is already loaded by a VM, that connection does not see the new class until the VM is restarted for
that connection (for example, with a STOP JAVA and START JAVA).

Remarks

(back to top)
Only new connections established after installing the class, or that use the class for the first time after installing
the class, use the new definition. Once the Java VM loads a class definition, it stays in memory until the
connection closes.

SAP IQ SQL Reference


1542 INTERNAL SQL Statements
If you have been using a Java class or objects based on a class in the current connection, you need to
disconnect and reconnect to use the new class definition.

All installed classes can be referenced in any way by any user.

Privileges

(back to top)

Requires the MANAGE ANY EXTERNAL OBJECT system privilege. See GRANT System Privilege Statement
[page 1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

● The following example 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'

After installation, the class is referenced using its name. Its original file path location is no longer used. For
example, this statement uses the class installed in the previous statement:

CREATE VARIABLE d Demo

If the Demo class was a member of the package SAP.work, the fully qualified name of the class must be
used:

CREATE VARIABLE d SAP.work.Demo

● The following example installs all the classes contained in a zip file and associate them within the database
with a JAR file name:

INSTALL JAVA
JAR 'Widgets'
FROM FILE 'C:\Jars\Widget.zip'

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

SAP IQ SQL Reference


SQL Statements INTERNAL 1543
Related Information

REMOVE Statement [page 1605]


REVOKE System Privilege Statement [page 1635]

9.4.132 IQ UTILITIES Statement

Starts a cache monitor that collects buffer cache statistics.

 Syntax

IQ UTILITIES { MAIN | PRIVATE }


[ INTO ] <table-name>
{ START MONITOR ['<monitor-options>']
| STOP MONITOR }

<monitor-options>
{ -summary
| {-append | -truncate } -bufalloc
| -cache
| -cache_by_type
| -contention
| -debug
| -file_suffix <suffix>
| -io
| -interval <seconds>
| -threads }...

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

START MONITOR

Starts the IQ buffer cache monitor.


MAIN

Monitors all tables in the main buffer cache of the IQ Store.


PRIVATE

Monitors all tables in the temp buffer cache of the temporary Store.
dummy_table_name

SAP IQ SQL Reference


1544 INTERNAL SQL Statements
Can be any SAP IQ base or temporary table. The table name is required for syntactic compatibility with
other IQ UTILITIES commands. It is best to have a table that you use only for monitoring.
monitor_options options

Controls buffer cache monitor output. You can specify more than one, and they must be enclosed with
quotation marks. Valid <options> are:

Option Name Description Usage

-summary Displays summary information for both the main and temp buffer monitor_options -
caches. If you do not specify any monitor options, you receive a summary
summary report.

-cache Displays main or temp buffer cache activity in detail. Critical fields monitor_options -
are Finds, HR%, and BWaits. cache

- Breaks -cache results down by IQ page type. (An exception is the monitor_options -
cache_by_t Bwaits column, which shows a total only.) This format is most cache_by_type
ype useful when you need to supply information to Technical Support.

- Creates a monitor output file named <dbname>.<connid>- monitor_options -


file_suffi <main_or_temp>-<suffix>. If you do not specify an op­ file_suffix
x tional file extension, the file extension defaults to .iqmon. {extension}

-io Displays main or temp (private) buffer cache I/O rates and com­ monitor_options -io
pression ratios during the specified interval. These counters repre­
sent all activity for the server; the information is not broken out by
device.

-bufalloc Displays information on the main or temp buffer allocator, which monitor_options -
reserves space in the buffer cache for objects like sorts, hashes, bufalloc
and bitmaps.

- Displays many key buffer cache and memory manager locks. monitor_options -
contention These lock and mutex counters show the activity within the buffer contention
cache and heap memory and how quickly these locks were re­
solved. Timeout numbers that exceed 20 percent indicate a prob­
lem.

-threads Displays the processing thread manager counts. Values are server- monitor_options -
wide (it does not matter whether you select this option for main or threads
private).

-interval Specifies the reporting interval in seconds. The default is every 60 monitor_options -
seconds. The minimum is every 2 seconds. You can usually get interval
useful results by running the monitor at the default interval during
a query or time of day with performance problems. Short intervals
may not give meaningful results. Intervals should be proportional
to the job time; one minute is generally more than enough.

-append | Appends or truncates output to existing output file. Truncate is the monitor_options -
-truncate default. append and
monitor_options -
truncate

SAP IQ SQL Reference


SQL Statements INTERNAL 1545
Option Name Description Usage

-debug Displays all information available to the performance monitor, monitor_options -


whether or not there is a standard display mode that covers the debug
same information. -debug is used mainly to supply information to
Technical Support.

STOP MONITOR

Similar to START MONITOR, except that you do not need to specify any options:

● To simplify monitor use, create a stored procedure to declare the dummy table, specify its output
location, and start the monitor.
● The interval, with two exceptions, applies to each line of output, not to each page. The exceptions are
the -cache_by_type and -debug clauses, where a new page begins for each display.

Remarks

(back to top)
Issue separate commands to monitor each buffer cache. Keep each session open while the monitor collects
results; a monitor run stops when you close its connection. A connection can run up to a maximum of two
monitor runs, one for the main and one for the temp buffer cache.

To control the directory placement of monitor output files, set the MONITOR_OUTPUT_DIRECTORY option. If
this option is not set, the monitor sends output to the same directory as the database. All monitor output files
are used for the duration of the monitor runs. They remain after a monitor run has stopped.

Either declare a temporary table for use in monitoring, or create a permanent dummy table when you create a
new database, before creating any multiplex query servers. These solutions avoid DDL changes, so that data
stays up on query servers during production runs.

On UNIX-like operating systems, you can watch monitor output as queries are running.

For example, starting the monitor with this command sends the output to an ASCII file with the name
dbname.conn#-[main|temp]-iqmon:

iq utilities main into monitor_tab


start monitor "-cache -interval 2 -file_suffix iqmon"

So, for the iqdemo database, the buffer monitor would send the results to iqdemo.2-main-iqmon.

The buffer cache monitor writes the results of each run to these logs:

● dbname.connection#-main-iqmon //for main buffer cache results


● dbname.connection#-temp-iqmon //for temp buffer cache results

The prefix <dbname.connection#> represents your database name and connection number. If you see more
than one connection number and are uncertain which is yours, you can run the catalog stored procedure
sa_conn_info. This procedure displays the connection number, user ID, and other information for each active
connection to the database. The -file_suffix clause to change the suffix iqmon to a suffix of your choice.
Use a text editor to display or print a file. Running the monitor again from the same database and connection
number, overwrites the previous results. To save the results of a monitor run, copy the file to another location
or use the -append option.

SAP IQ SQL Reference


1546 INTERNAL SQL Statements
Privileges

(back to top)

None

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

(back to top)

The following example starts the buffer cache monitor and record activity for the IQ temp buffer cache:

IQ UTILITIES PRIVATE INTO monitor START MONITOR '-cache -interval 20'

Related Information

MONITOR_OUTPUT_DIRECTORY Option [page 1926]


REVOKE System Privilege Statement [page 1635]

9.4.133 LEAVE Statement

Continues execution by leaving a compound statement or LOOP.

 Syntax

LEAVE <statement-label>

Remarks

LEAVE is a control statement that lets you leave a labeled compound statement or a labeled loop. Execution
resumes at the first statement after the compound statement or loop.

SAP IQ SQL Reference


SQL Statements INTERNAL 1547
The compound statement that is the body of a procedure has an implicit label that is the same as the name of
the procedure.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant.


● SAP database products – not supported by SAP Adaptive Server Enterprise. The break statement provides
a similar feature for Transact-SQL compatible procedures.

Examples

● The following example shows how to use the LEAVE statement to leave a loop:

SET i = 1;
lbl:
LOOP
INSERT
INTO Counters ( number )
VALUES ( i ) ;
IF i >= 10 THEN
LEAVE lbl ;
END IF ;
SET i = i + 1
END LOOP lbl

● The following example uses LEAVE in a nested loop:

outer_loop:
LOOP
SET i = 1;
inner_loop:
LOOP
...
SET i = i + 1;
IF i >= 10 THEN
LEAVE outer_loop
END IF
END LOOP inner_loop
END LOOP outer_loop

Related Information

BEGIN … END Statement [page 1218]

SAP IQ SQL Reference


1548 INTERNAL SQL Statements
FOR Statement [page 1479]
LOOP Statement [page 1576]
REVOKE System Privilege Statement [page 1635]

9.4.134 LOAD TABLE Statement

Imports data into a database table from an external file.

 Note

Sections in this topic are minimized. To expand or recollapse a section, click the title next to the greater-
than symbol (>).

 Syntax

LOAD [ INTO ] TABLE [ <owner>.]<table-name>


( <load-specification> [, …] )
{ FROM | USING [ CLIENT ] FILE }
{ '<filename>-<string>' | <filename>-<variable> } [, …]
[ CHECK CONSTRAINTS { ON | OFF } ]
[ DEFAULTS { ON | OFF } ]
[ QUOTES { ON | OFF } ]
[ QUOTE <enclosure_character> ]
[ QUOTE ESCAPE '<escape_character>' ]
ESCAPES OFF
[ FORMAT { ascii | binary | bcp | csv | parquet } ]
[ DELIMITED BY '<string>' ]
[ STRIP { OFF | RTRIM } ]
[ WITH CHECKPOINT { ON | OFF } ]
[ BYTE ORDER { NATIVE | HIGH | LOW } ]
[ LIMIT <number-of-rows> ]
[ NOTIFY <number-of-rows> ]
[ ON FILE ERROR { ROLLBACK | FINISH | CONTINUE } ]
[ PREVIEW { ON | OFF } ]
[ ROW DELIMITED BY '<delimiter-string>' ]
[ SKIP <number-of-rows> ]
[ HEADER SKIP [ ALL ] <number>
[ HEADER DELIMITED BY '<string>' ] ]
[ WORD SKIP <number> ]
[ ON PARTIAL INPUT ROW { ROLLBACK | CONTINUE } ]
[ IGNORE CONSTRAINT <constraint-type> <string> ]
[ MESSAGE LOG '<string>' ]
[ ROW LOG '<string>' ]
[ ONLY LOG <log-what> [, …] ]
[ LOG DELIMITED BY [, …] ]

<load-specification> ::=
{ <column-name> [ <filler-type> <column-spec> ]
| FILLER ( <filler-type> ) }

<column-spec> ::=
{ ASCII ( <input-width> )
| PREFIX { 1 | 2 | 4 }
| BINARY [ WITH NULL BYTE ]
| PREFIX { 1 | 2 | 4 } BINARY [ WITH NULL BYTE ] [ VARYING ]
| '<delimiter-string>'
| DATE ( <input-date-format> )
| DATETIME ( <input-datetime-format> )

SAP IQ SQL Reference


SQL Statements INTERNAL 1549
| FILE NAME
| ENCRYPTED ( <data-type> '<key-string>' [, '<algorithm-string>' ] )
| DEFAULT <default-value> }
[ NULL ( { BLANKS | ZEROS | '<literal>' , …} )

<filler-type> ::=
{ <input-width>
| PREFIX { 1 | 2 | 4 }
| '<delimiter-string>' }

<constraint-type> <string> ::=


{ CHECK <limit>
| UNIQUE <limit>
| NULL <limit>
| FOREIGN KEY <limit> [, …
| DATA VALUE <limit>
| ALL <limit> }

<log-what> ::=
{ CHECK
| ALL
| NULL
| UNIQUE
| DATA VALUE
| FOREIGN KEY
| WORD }

Parameters

FROM

Identifies one or more files from which to load data. To specify more than one file, use a comma to separate
each filename-string. The <filename-string> is passed to the server as a string. The string is
therefore subject to the same formatting requirements as other SQL strings.

To indicate directory paths on Windows, represent the backslash character (\) with two backslashes.
Therefore, the statement to load data from the file c:\temp\input.dat into the Employees table is:

LOAD TABLE Employees


FROM 'c:\\temp\\input.dat' ...

The path name is relative to the database server, not to the client application. If you are running the
statement on a database server on some other computer, the directory names refer to directories on the
server machine, not on the client machine. When loading a multiplex database, use absolute (fully
qualified) paths in all file names. Do not use relative path names.

Because of resource constraints, SAP IQ does not guarantee that all the data can be loaded. If resource
allocation fails, the entire load transaction is rolled back. Any SKIP or LIMIT clause only applies in the
beginning of the load, not to each file. Multiple files are processed in parallel, except when using the SKIP
or LIMIT clauses. The rows being skipped are processed single threaded from the files in the order
specified in the LOAD statement. Once the SKIP completes, the rest of the files are processed in parallel if
there is no LIMIT clause. If a LIMIT clause is specified, the entire load process is single threaded, and the
number of rows are loaded from the files in the order specified in the LOAD statement.

SAP IQ SQL Reference


1550 INTERNAL SQL Statements
The LOAD TABLE FROM clause is deprecated, but may be used to specify a file that exists on the server.
This example loads data from the file a.inp on a client computer:

LOAD TABLE t1(c1,c2,FILLER(30))


USING CLIENT FILE 'c:\\client-data\\a.inp'
QUOTES OFF ESCAPES OFF
IGNORE CONSTRAINT UNIQUE 0, NULL 0
MESSAGE LOG 'c:\\client-data\\m.log'
ROW LOG 'c:\\client-data\\r.log'
ONLY LOG UNIQUE

USING [ CLIENT ] FILE

USING FILE loads one or more files from the server. This clause is synonymous with specifying the FROM
<filename> clause.

USING CLIENT FILE bulk loads one or more files from a client. The character set of the file on the client
side must be the same as the server collation. Client-side bulk loading incurs no administrative overhead,
such as extra disk space, memory, or network-monitoring daemon requirements, but does forces single
threaded processing for each file.

When bulk loading large objects, the USING CLIENT FILE clause applies to both primary and secondary
files.

The LOAD TABLE statement can load compressed client and server files only in gzip format. Any file with
an extension ".gz" or ".gzip" is assumed to be a compressed file. Named pipes or secondary files are not
supported during a compressed file load. Compressed files and uncompressed files can be specified in the
same LOAD TABLE statement. Each compressed file in a load is processed by one thread.

During client-side loads, the IGNORE CONSTRAINT log files are created on the client host and any error
while creating the log files causes the operation to roll back.

Client-side bulk loading is supported by Interactive SQL and ODBC/JDBC clients using the Command
Sequence protocol. It is not supported by clients using the TDS protocol. For data security over a network,
use Transport Layer Security. To control who can use client-side bulk loads, use the secure feature (-sf)
server startup switch, enable the ALLOW_READ_CLIENT_FILE database option, and the READ CLIENT
FILE access control.

The FORMAT parquet clause does not support the use of client files. You may use USING FILE with
FORMAT parquet, but SAP IQ returns an error and rolls back the LOAD TABLE statement if you specify
USING CLIENT FILE with FORMAT parquet.
CHECK CONSTRAINTS { ON | OFF }

Evaluates check constraints, which you can ignore or log. CHECK CONSTRAINTS defaults to ON.

Setting CHECK CONSTRAINTS OFF causes SAP IQ to ignore all check constraint violations. This can be
useful, for example, during database rebuilding. If a table has check constraints that call user-defined
functions that are not yet created, the rebuild fails unless this option is set to OFF.

This option is mutually exclusive to the following options. If any of these options are specified in the same
load, an error results:

● IGNORE CONSTRAINT ALL


● IGNORE CONSTRAINT CHECK
● LOG ALL
● LOG CHECK

SAP IQ SQL Reference


SQL Statements INTERNAL 1551
DEFAULTS { ON | OFF }

Uses a column's default value. This option is ON by default. If the DEFAULTS option is OFF, any column not
present in the column list is assigned NULL.

The setting for the DEFAULT option applies to all column DEFAULT values, including AUTOINCREMENT.
QUOTES { ON | OFF }

Indicates that input strings are enclosed in quote characters. QUOTES is an optional parameter and is ON by
default. The first such character encountered in a string is treated as the quote character for the string.
String data must be terminated with a matching quote.

With QUOTES ON, column or row delimiter characters can be included in the column value. Leading and
ending quote characters are assumed not to be part of the value and are excluded from the loaded data
value.

To include a quote character in a value with QUOTES ON, use two quotes. For example, this line includes a
value in the third column that is a single quote character:

'123 High Street, Anytown', '(715)398-2354',''''

With STRIP turned on (the default), trailing blanks are stripped from values before they are inserted.
Trailing blanks are stripped only for non-quoted strings. Quoted strings retain their trailing blanks. Leading
blank or TAB characters are trimmed only when the setting is ON.

The data extraction facility provides options for handling quotes (TEMP_EXTRACT_QUOTES,
TEMP_EXTRACT_QUOTES_ALL, and TEMP_EXTRACT_QUOTE). If you plan to extract data to be loaded into
an IQ main store table and the string fields contain column or row delimiter under default ASCII extraction,
use the TEMP_EXTRACT_BINARY option for the extract and the FORMAT binary and QUOTES OFF options
for LOAD TABLE.

Limits:

● QUOTES ON applies only to column-delimited ASCII fields.


● With QUOTES ON, the first character of a column delimiter or row terminator cannot be a single or
double quote mark.
● QUOTES ON forces single threaded processing for a given file.
● The QUOTES option does not apply to loading binary large object (BLOB) or character large object
(CLOB) data from the secondary file, regardless of its setting. A leading or trailing quote is loaded as
part of CLOB data. Two consecutive quotes between enclosing quotes are loaded as two consecutive
quotes with the QUOTES ON option.
● SAP Adaptive Server Enterprise BCP does not support the QUOTES option. All field data is copied in or
out equivalent to the QUOTES OFF setting. As QUOTES ON is the default setting for the SAP IQ LOAD
TABLE statement, you must specify QUOTES OFF when importing SAP ASE data from BCP output to an
SAP IQ table.
● When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the QUOTES { ON
| OFF } clause and issues a message with this information.

Exceptions:

● If LOAD TABLE encounters any nonwhite characters after the ending quote character for an enclosed
field, this error is reported and the load operation is rolled back:

SAP IQ SQL Reference


1552 INTERNAL SQL Statements
Non-SPACE text found after ending quote character for
an enclosed field.
SQLSTATE: QTA14 SQLCODE: -1005014L
● With QUOTES ON, if a single or double quote is specified as the first character of the column delimiter,
an error is reported and the load operation fails:
Single or double quote mark cannot be the 1st character
of column delimiter or row terminator with QUOTES option
ON.
SQLSTATE: QCA90 SQLCODE: -1013090L
QUOTE enclosure_character

For TEXT data only; identifies the enclosure character to be placed around string values. If not specified,
the default QUOTE character is either a single (') or double (") quotation mark, depending on what is used in
the field. If QUOTES OFF is defined, QUOTE is ignored.

If the specified <enclosure_character> is multibyte, only the first byte is used; the remaining bytes are
ignored.

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the QUOTE
<enclosure_character> clause and issues a message with this information.
QUOTE ESCAPE 'escape_character'

Specifies the escape character used in the data. If not specified, the default QUOTE ESCAPE character is
the value of QUOTE. For example, if QUOTE is defined as percent (%), but QUOTE ESCAPE is not defined, the
default value for QUOTE ESCAPE becomes %. If neither QUOTE ESCAPE nor QUOTE are defined, QUOTE
defaults to either a single (') or double (") quotation mark, depending on what is used in the field, and
QUOTE ESCAPE defaults to match QUOTE.

If the specified ESCAPE character is multibyte, only the first byte is used; the remaining bytes are ignored.

If QUOTES ON and QUOTE ESCAPE is not defined, single quote becomes the ESCAPE character and must
be escaped by another quote.

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the QUOTE ESCAPE
clause and issues a message with this information.
ESCAPES

If you omit a <column-spec> definition for an input field and ESCAPES is ON (the default), characters
following the backslash character are recognized and interpreted as special characters by the database
server. You can include newline characters as the combination \n, and other characters as hexadecimal
ASCII codes, such as \x09 for the Tab character. A sequence of two backslash characters ( \\ ) is
interpreted as a single backslash.

 Note

For SAP IQ, you must set ESCAPES OFF.

FORMAT { ascii | binary | bcp | csv | parquet }

SAP IQ supports ASCII and binary input fields. The format is usually defined by the <column-spec>
described above. If you omit that definition for a column, by default SAP IQ uses the format defined by this
option. Input lines are assumed to have ASCII (the default) or binary fields, one row per line, with values
separated by the column delimiter character.

bcp

SAP IQ SQL Reference


SQL Statements INTERNAL 1553
SAP IQ also accepts data from BCP character files as input to the LOAD TABLE command.

● The BCP data file loaded into SAP IQ tables using the LOAD TABLE FORMAT BCP statement must
be exported (BCP OUT) in cross-platform file format using the -c option.
● For FORMAT bcp, the default column delimiter for the LOAD TABLE statement is <tab> and the
default row terminator is <newline>.
● For FORMAT bcp, the last column in a row must be terminated by the row terminator, not by the
column delimiter. If the column delimiter is present before the row terminator, then the column
delimiter is treated as a part of the data.
● Data for columns that are not the last column in the load specification must be delimited by the
column delimiter only. If a row terminator is encountered before a column delimiter for a column
that is not the last column, then the row terminator is treated as a part of the column data.
● Column delimiter can be specified via the DELIMITED BY clause. For FORMAT bcp, the delimiter
must be less than or equal to 10 characters in length. An error is returned, if the delimiter length is
more than 10.
● For FORMAT bcp, the load specification may contain only column names, NULL, and ENCRYPTED.
An error is returned if any other option is specified in the load specification.
For example, these LOAD TABLE load specifications are valid:

LOAD TABLE x( c1, c2 null(blanks), c3 )


FROM 'bcp_file.bcp'
FORMAT BCP
...

LOAD TABLE x( c1 encrypted(bigint,'KEY-ONE','aes'), c2, c3 )


FROM 'bcp_file.bcp'
FORMAT BCP
...

csv

A row in a CSV file must be terminated either by a row deliminator (default newline) or a column
deliminator (default coma) followed by a row delimiter. The maximum size of a delimiter is 4 bytes. An
error message appears if the deliminator exceeds 4 bytes.

A CSV file may contain partial rows, defined as any row with the number of fields less than the number
of columns specified (either explicitly or implicitly) in the LOAD TABLE statement. All fields missing
from a partial row are assigned a NULL value. If the column is not nullable, an error message appears,
and no data is imported.

If a table has K columns, a CSV file has M fields, and the LOAD TABLE statement indicates N columns
(either explicitly or implicitly), when N <= K and N < M, columns missing from the column list in the
load statement are assigned default values.

parquet

To load a Parquet format file into a table, use the FORMAT parquet clause and specify .parquet
or .parq as the file name extension in the LOAD TABLE statement.

Not all LOAD TABLE clauses work with FORMAT parquet; some are ignored, while others can cause
the LOAD TABLE statement to roll back. See Loading Parquet Files in SAP IQ Administration: Load
Management for details.
DELIMITED BY 'string'

SAP IQ SQL Reference


1554 INTERNAL SQL Statements
If you omit a column delimiter in the <column-spec> definition, the default column delimiter character is
a comma. You can specify an alternative column delimiter by providing a single ASCII character or the
hexadecimal character representation. The DELIMITED BY clause is:

... DELIMITED BY '\x09' ...

To use the newline character as a delimiter, you can specify either the special combination '\n' or its ASCII
value '\x0a'. Although you can specify up to four characters in the <column-spec> <delimiter-
string>, you can specify only a single character in the DELIMITED BY clause.

When specifying the DATE column with the NULL clause, the date column is treated as a variable-width
date field if DELIMITED BY clause is included. Otherwise, date column is treated as fixed-width date field.

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the DELIMITED BY
clause and issues a message with this information.
STRIP { OFF | RTRIM }

Determines whether unquoted values should have trailing blanks stripped off before they are inserted. The
LOAD TABLE command accepts these STRIP keywords:

● STRIP OFF – does not strip off trailing blanks


● STRIP RTRIM – strips trailing blanks.
● STRIP ON – is deprecated. Use STRIP RTRIM.

With STRIP turned on (the default), SAP IQ strips trailing blanks from values before inserting them. This is
effective only for VARCHAR data. STRIP OFF preserves trailing blanks.

Trailing blanks are stripped only for unquoted strings. Quoted strings retain their trailing blanks. If you do
not require blank sensitivity, you can use the FILLER option as an alternative to be more specific in the
number of bytes to strip, instead of all the trailing spaces. STRIP OFF is more efficient for SAP IQ, and it
adheres to the ANSI standard when dealing with trailing blanks. (CHAR data is always padded, so the STRIP
option only affects VARCHAR data.)

The STRIP option applies only to variable-length non-binary data and does not apply to ASCII fixed-width
inserts. For example, assume this schema:

CREATE TABLE t( c1 VARCHAR(3) );


LOAD TABLE t( c1 ',' ) ........ STRIP RTRIM // trailing blanks trimmed
LOAD TABLE t( c1 ',' ) ........ STRIP OFF // trailing blanks not trimmed
LOAD TABLE t( c1 ASCII(3) ) ... STRIP RTRIM // trailing blanks not trimmed
LOAD TABLE t( c1 ASCII(3) ) ... STRIP OFF // trailing blanks trimmed
LOAD TABLE t( c1 BINARY ) ..... STRIP RTRIM // trailing blanks trimmed
LOAD TABLE t( c1 BINARY ) ..... STRIP OFF // trailing blanks trimmed

Trailing blanks are always trimmed from binary data.


WITH CHECKPOINT { ON | OFF }

Determines whether SAP IQ performs a checkpoint. This option is useful only when loading SAP SQL
Anywhere tables in an SAP IQ database.

The default setting is OFF. If this clause is set to ON, a checkpoint is issued after successfully completing
and logging the statement. If the server fails after a connection commits and before the next checkpoint,
the data file used to load the table must be present for the recovery to complete successfully. However, if
WITH CHECKPOINT ON is specified, and recovery is subsequently required, the data file doesn't need to be
present at the time of recovery.

SAP IQ SQL Reference


SQL Statements INTERNAL 1555
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.

 Caution

If you set the CONVERSION_ERROR database option to OFF, you may load bad data into your table
without any error being reported. If you do not specify WITH CHECKPOINT ON, and the database
needs to be recovered, the recovery may fail as CONVERSION_ERROR is ON (the default value) during
recovery. It is recommended that you do not load tables when CONVERSION_ERROR is set to OFF and
WITH CHECKPOINT ON is not specified.

See also CONVERSION_ERROR Option [TSQL].

BYTE ORDER { NATIVE | HIGH | LOW }

Specifies the byte order during reads. This option applies to all binary input fields. If none are defined, this
option is ignored. You can specify:

● NATIVE – (default)SAP IQ always reads binary data in the format native to the machine it is running
on.
● HIGH – when multibyte quantities have the high-order byte first (for big-endian platforms like Sun, IBM
AIX, and HP).
● LOW – when multibyte quantities have the low-order byte first (for little-endian platforms like
Windows).

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the BYTE ORDER
clause and issues a message with this information.
LIMIT number-of-rows

Specifies the maximum number of rows to insert into the table. The default is 0 for no limit. The maximum
is 231 - 1 (2147483647) rows.
NOTIFY number-of-rows

Specifies that you be notified with a message each time the specified number of rows is successfully
inserted into the table. The default is 0, meaning no notifications are printed. The value of this option
overrides the value of the NOTIFY_MODULUS database option.
ON FILE ERROR { ROLLBACK | FINISH | CONTINUE }

Specifies the action SAP IQ takes when an input file cannot be opened because it does not exist or you
have incorrect privileges to read the file. You can specify one of the following:

● ROLLBACK – aborts the entire transaction (the default).


● FINISH – finishes the insertions already completed and ends the load operation.
● CONTINUE – returns an error but only skips the file to continue the load operation.

Only one ON FILE ERROR clause is permitted.


PREVIEW { ON | OFF }

Displays the layout of input into the destination table including starting position, name, and data type of
each column. SAP IQ displays this information at the start of the load process. If you are writing to a log file,
this information is also included in the log.
ROW DELIMITED BY 'delimiter-string'

Specifies a string up to 4 bytes in length that indicates the end of an input record. You can use this option
only if all fields within the row are any of the following:

SAP IQ SQL Reference


1556 INTERNAL SQL Statements
● Delimited with column terminators
● Data defined by the DATE or DATETIME <column-spec> options
● ASCII fixed-length fields

Always include ROW DELIMITED BY to ensure parallel loads. Omitting this clause from the LOAD
specification may cause SAP IQ to load serially rather than in parallel.

You cannot use this option if any input fields contain binary data. With this option, a row terminator causes
any missing fields to be set to NULL. All rows must have the same row delimiters, and it must be distinct
from all column delimiters. The row and field delimiter strings cannot be an initial subset of each other. For
example, you cannot specify "*" as a field delimiter and "*#" as the row delimiter, but you could specify "#"
as the field delimiter with that row delimiter.

If a row is missing its delimiters, SAP IQ returns an error and rolls back the entire load transaction. The only
exception is the final record of a file where it rolls back that row and returns a warning message.

On Windows, a row delimiter is usually indicated by the newline character followed by the carriage return
character. You might need to specify this as the <delimiter-string> (see above for description) for
either this option or FILLER.

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the ROW DELIMITED
BY clause and issues a message with this information.
SKIP number-of-rows

Defines the number of rows to skip at the beginning of the input tables for this load. The maximum number
of rows to skip is 231 - 1 (2147483647). The default is 0. SKIP runs in single-threaded mode as it reads the
rows to skip.

The FORMAT parquet clause does not support SKIP <number-of-rows>. If you specify FORMAT
parquet with SKIP <number-of-rows>, SAP IQ returns an error and rolls back the LOAD TABLE
statement.
HEADER SKIP [ALL] number … HEADER DELIMITED BY 'string'

When you include ALL in your load statement for a multiple-file load, LOAD TABLE skips the number of
header rows (that you specify with <number>) from the start of each file, while omitting ALL just skips the
number of header rows from just the first file. ALL does not change the results for a single-file load.

HEADER SKIP <number>, without ALL, specifies a number of lines at the beginning of the data file,
including header rows, for LOAD TABLE to skip. All LOAD TABLE column specifications and other load
options are ignored, until the specified number of rows is skipped.

● The number of lines to skip is greater than or equal to zero.


● Lines are determined by a 1-to-4-character delimiter string specified in the HEADER DELIMITED BY
clause. The default HEADER DELIMITED BY string is the \n character.
● The HEADER DELIMITED BY string has a maximum length of four characters. An error is returned, if
the string length is greater than four or less than one.
● When a non-zero HEADER SKIP value is specified, all data inclusive of the HEADER DELIMITED BY
delimiter is ignored, until the delimiter is encountered the number of times specified in the HEADER
SKIP clause.
● All LOAD TABLE column specifications and other load options are ignored, until the specified number
of rows has been skipped. After the specified number of rows has been skipped, the LOAD TABLE
column specifications and other load options are applied to the remaining data.

SAP IQ SQL Reference


SQL Statements INTERNAL 1557
● The "header" bytes are ignored only at the beginning of the data. When multiple files are specified in
the USING clause, HEADER SKIP only ignores data starting from the first row of the first file, until it
skips the specified number of header rows, even if those rows exist in subsequent files. LOAD TABLE
does not look for headers once it starts parsing actual data.
● No error is reported, if LOAD TABLE processes all input data before skipping the number of rows
specified by HEADER SKIP.
● When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the HEADER SKIP
[ALL] clause and issues a message with this information.

HEADER SKIP ALL has the following behaviors:

● You cannot specify HEADER SKIP and HEADER SKIP ALL in the same LOAD TABLE statement; doing
so results in an error.
● You can specify HEADER SKIP ALL <number> and SKIP <number-of-rows> together. When you
do, the number of header rows (specified in <number>) is skipped first, then SKIP <number-of-
rows> is performed until the statement reaches the number of rows you specified.
● You can specify HEADER SKIP ALL <number> and LIMIT <number-of-rows>. When you do, the
number of header rows (specified in <number>) is skipped first, then rows are loaded for the number
of rows you specify.
WORD SKIP number

Allows the load to continue when it encounters data longer than the limit specified when the word index
was created.

If a row is not loaded because a word exceeds the maximum permitted size, a warning is written to
the .iqmsg file. WORD size violations can be optionally logged to the MESSAGE LOG file and rejected rows
logged to the ROW LOG file specified in the LOAD TABLE statement.

● If the option is not specified, LOAD TABLE reports an error and rolls back on the first occurrence of a
word that is longer than the specified limit.
● <number> specifies the number of times the “Words exceeding the maximum permitted word
length not supported” error is ignored.
● 0 (zero) means there is no limit.
ON PARTIAL INPUT ROW { ROLLBACK | CONTINUE }

Specifies the action to take when a partial input row is encountered during a load. You can specify one of
the following:

● CONTINUE – (default) issues a warning and continues the load operation.


● ROLLBACK – aborts the entire load operation and reports the error:
Partial input record skipped at EOF.
SQLSTATE: QDC32 SQLSTATE: -1000232L

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the ON PARTIAL
INPUT ROW clause and issues a message with this information.
IGNORE CONSTRAINT constraint-type string

Specifies whether to ignore CHECK, UNIQUE, NULL, DATA VALUE, and FOREIGN KEY integrity constraint
violations that occur during a load. <string> is an integer that indicates the maximum number of
violations to ignore before initiating a rollback. Specifying each <constraint-type> has the following
result:

SAP IQ SQL Reference


1558 INTERNAL SQL Statements
● CHECK <limit> – if <limit> specifies zero, the number of CHECK constraint violations to ignore is
infinite. If CHECK is not specified, the first occurrence of any CHECK constraint violation causes the
LOAD TABLE statement to roll back. If <limit> is nonzero, then the <limit> +1 occurrence of a
CHECK constraint violation causes the load to roll back.
● UNIQUE <limit> – if <limit> specifies zero, then the number of UNIQUE constraint violations to
ignore is infinite. If <limit> is nonzero, then the <limit> +1 occurrence of a UNIQUE constraint
violation causes the load to roll back.
● NULL <limit> – if <limit> specifies zero, then the number of NULL constraint violations to ignore is
infinite. If <limit> is nonzero, then the <limit> +1 occurrence of a NULL constraint violation causes
the load to roll back.
● FOREIGN KEY <limit> – if <limit> specifies zero, the number of FOREIGN KEY constraint
violations to ignore is infinite. If <limit> is nonzero, then the <limit> +1 occurrence of a FOREIGN
KEY constraint violation causes the load to roll back.
● DATA VALUE <limit> – if the database option CONVERSION_ERROR = ON, an error is reported and
the statement rolls back. If <limit> specifies zero, then the number of DATA VALUE constraint
violations (data type conversion errors) to ignore is infinite. If <limit> is nonzero, then the <limit>
+1 occurrence of a DATA VALUE constraint violation causes the load to roll back.
● ALL <limit> – if the CONVERSION_ERROR database option is ON, an error is reported and the
statement rolls back. If <limit> specifies zero, then the cumulative total of all integrity constraint
violations to ignore is infinite. If <limit> is nonzero, then load rolls back when the cumulative total of
all ignored UNIQUE, NULL, DATA VALUE, and FOREIGN KEY integrity constraint violations exceeds the
value of <limit>. For example, if you specify this IGNORE CONSTRAINT option, the total number of
integrity constraint violations cannot exceed 200, whereas the total number of NULL and UNIQUE
constraint violations cannot exceed 50 and 100, respectively:

IGNORE CONSTRAINT NULL 50, UNIQUE 100, ALL 200

Whenever any of these limits is exceeded, the LOAD TABLE statement rolls back.

 Note

A single row can have more than one integrity constraint violation. Every occurrence of an integrity
constraint violation counts towards the limit of that type of violation.

Set the IGNORE CONSTRAINT option limit to a nonzero value if you are logging the ignored
integrity constraint violations. Logging an excessive number of violations affects the performance
of the load

If CHECK, UNIQUE, NULL, or FOREIGN KEY is not specified in the IGNORE CONSTRAINT clause, then the
load rolls back on the first occurrence of each of these types of integrity constraint violation.

If DATA VALUE is not specified in the IGNORE CONSTRAINT clause, then the load rolls back on the first
occurrence of this type of integrity constraint violation, unless the CONVERSION_ERROR database option is
OFF. If so, a warning is reported for any DATA VALUE constraint violation and the load continues.

When the load completes, an informational message regarding integrity constraint violations is logged in
the .iqmsg file. This message contains the number of integrity constraint violations that occurred during
the load and the number of rows that were skipped.
[MESSAGE LOG 'string'] [ROW LOG 'string' ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1559
Specifies the names of files in which to log information about integrity constraint violations and the types
of violations to log. Timestamps indicating the start and completion of the load are logged in both the
MESSAGE LOG and the ROW LOG files. Both MESSAGE LOG and ROW LOG must be specified, or no
information about integrity violations is logged.

● If the ONLY LOG clause is not specified, no information on integrity constraint violations is logged. Only
the timestamps indicating the start and completion of the load are logged.
● Information is logged on all integrity constraint-type violations specified in the ONLY LOG clause or for
all word index-length violations if the keyword WORD is specified.
● If constraint violations are being logged, every occurrence of an integrity constraint violation generates
exactly one row of information in the MESSAGE LOG file.
The number of rows (errors reported) in the MESSAGE LOG file can exceed the IGNORE CONSTRAINT
option limit, because the load is performed by multiple threads running in parallel. More than one
thread might report that the number of constraint violations has exceeded the specified limit.
● If constraint violations are being logged, exactly one row of information is logged in the ROW LOG file
for a given row, regardless of the number of integrity constraint violations that occur on that row.
The number of distinct errors in the MESSAGE LOG file might not exactly match the number of rows in
the ROW LOG file. The difference in the number of rows is due to the parallel processing of the load
described above for the MESSAGE LOG.
● The MESSAGE LOG and ROW LOG files cannot be raw partitions or named pipes.
● If the MESSAGE LOG or ROW LOG file already exists, new information is appended to the file.
● Specifying an invalid file name for the MESSAGE LOG or ROW LOG file generates an error.
● Specifying the same file name for the MESSAGE LOG and ROW LOG files generates an error.

Various combinations of the IGNORE CONSTRAINT and MESSAGE LOG options result in different logging
actions:

IGNORE CONSTRAINT MESSAGE LOG Speci­


Specified? fied? Action

Yes Yes All ignored integrity constraint violations are logged, in­
cluding the user specified limit, before the rollback.

No Yes The first integrity constraint violation is logged before the


rollback.

Yes No Nothing is logged.

No No Nothing is logged. The first integrity constraint violation


causes a rollback.

 Tip

Set the IGNORE CONSTRAINT option limit to a nonzero value, if you are logging the ignored integrity
constraint violations. If a single row has more than one integrity constraint violation, a row for each
violation is written to the MESSAGE LOG file. Logging an excessive number of violations affects the
performance of the load.

LOG DELIMITED BY

Specifies the separator between data values in the ROW LOG file. The default separator is a comma.

SAP IQ SQL Reference


1560 INTERNAL SQL Statements
SAP IQ no longer returns an error message when FORMAT bcp is specified as a LOAD TABLE clause. In
addition, these conditions are verified and proper error messages are returned:

● If the specified load format is not ascii, binary, or bcp, SAP IQ returns the message “Only ASCII,
BCP and BINARY are supported LOAD formats.”
● If the LOAD TABLE column specification contains anything other than column name, NULL, or
ENCRYPTED, then SAP IQ returns the error message “Invalid load specification for
LOAD ... FORMAT BCP.”
● If the column delimiter or row terminator size for the FORMAT bcp load is greater than 10 characters,
then SAP IQ returns the message “Delimiter '%2' must be 1 to %3 characters in
length.” (where %3 equals 10).
Messages corresponding to error or warning conditions, which can occur for FORMAT bcp as well as
FORMAT ascii, are the same for both formats.
● If the load default value specified is AUTOINCREMENT, IDENTITY, or GLOBAL AUTOINCREMENT, SAP IQ
returns the error “Default value %2 cannot be used as a LOAD default value. %1”
● If the LOAD TABLE specification does not contain any columns that need to be loaded from the file
specified, SAP IQ returns the error “The LOAD statement must contain at least one
column to be loaded from input file.” and the LOAD TABLE statement rolls back.
● If a load exceeds the limit on the maximum number of terms for a text document with TEXT indexes,
SAP IQ returns the error “Text document exceeds maximum number of terms. Support up
to 4294967295 terms per document.”

Remarks

The LOAD TABLE statement allows efficient mass insertion into a database table from a file with ASCII or
binary data.

The LOAD TABLE options also let you control load behavior when integrity constraints are violated and to log
information about the violations.

You can use LOAD TABLE on a temporary table, but the temporary table must have been declared with ON
COMMIT PRESERVE ROWS, or the next COMMIT removes the rows you have loaded.

LOAD TABLE supports loading of large object (LOB) data.

Column Options
SAP IQ supports loading from both ASCII and binary data, and it supports both fixed- and variable-length
formats. To handle all of these formats, you supply a <load-specification> to tell SAP IQ what kind of data
to expect from each “column” or field in the source file. The <column-spec> lets you define these formats:

● ASCII with a fixed length of bytes. The <input-width> value is an integer indicating the fixed width in
bytes of the input field in every record.
● Binary or non-binary fields that use a PREFIX clause, which comprises two parts:

Part Description

Prefix portion Always a binary value.

SAP IQ SQL Reference


SQL Statements INTERNAL 1561
Part Description

Associated data portion If you use:


○ The PREFIX clause without BINARY – a character format (ASCII data)
○ The PREFIX clause with BINARY – a binary format and which can only be
specified for a VARCHAR or VARBINARY column.

When you perform a load of binary data, the length of the associated data portion differs based on whether
you specify the VARYING option with the PREFIX clause:
○ PREFIX <n> BINARY with VARYING – the length of the associated data portion is variable, and is the
same as the actual data length.
○ PREFIX <n> BINARY without VARYING – the length of the associated data portion is fixed, and is the
declared length for the varchar/varbinary column. For example, if the column is varchar(10), the
associated data portion is 10 bytes long. The prefix portion indicates the actual length of data in the
field, even if that length is shorter than the field in the file — in which case, the remaining data after the
actual data is ignored, and is not inserted in the column in the table.
If you plan to use PREFIX <n> BINARY for a varchar or varbinary column for a file that was generated by
the binary mode option for extraction, use the TEMP_EXTRACT_LENGTH_PREFIX option for extraction to
specify the length of the prefix portion, and TEMP_EXTRACT_VARYING to extract the associated data
portion with a variable length of actual data (instead of the declared length of varchar/varbinary).
Specifying TEMP_EXTRACT_VARYING allows you to extract the varchar or varbinary column without trailing
padding in the extracted file. With PREFIX <n> BINARY, trailing blanks for the varchar column (and
trailing zeros for the varbinary column) are not stripped from values when inserted into the column.
If the data is unloaded using the extraction facility with the TEMP_EXTRACT_BINARY option set ON, you
must use the BINARY WITH NULL BYTE parameter for each column when you load the binary data.

● Variable-length characters delimited by a separator. You can specify the terminator as hexadecimal ASCII
characters and the bytes (1, 2, or 4) to specify the length of the input. This <delimiter-string>
variable-length characters, delimited by a separator, can be any string of up to 4 characters, including any
combination of printable characters, and any 8-bit hexadecimal ASCII code that represents a nonprinting
character. For example, specify:
○ "\x09" to represent a tab as the terminator.
○ "\x00" for a null terminator (no visible terminator as in “C” strings).
○ "\x0a" for a newline character as the terminator. You can also use the special character combination
of '\n' for newline.

 Note

The delimiter string can be from 1 to 4 characters long, but you can specify only a single character in
the DELIMITED BY clause. For BCP, the delimiter can be up to 10 characters.

● DATE or DATETIME string as ASCII characters. You must define the <input-date-format> or <input-
datetime-format> of the string using one of the corresponding formats for the date and datetime data
types supported by SAP IQ. Use DATE for DATE values and DATETIME for DATETIME and TIME values.
Formatting dates and times are:

SAP IQ SQL Reference


1562 INTERNAL SQL Statements
Option Meaning

yyyy or YYYY Represents number of year. Default is current year.

yy or YY

mm or MM Represents number of month. Always use leading zero or blank for number of the month
where appropriate, for example, '05' for May. DATE value must include a month. For example,
if the DATE value you enter is 1998, you receive an error. If you enter '03', SAP IQ applies the
default year and day and converts it to '1998-03-01'.

dd or DD Represents number of day. Default day is 01. Always use leading zeros for number of day
where appropriate, for example, '01' for first day. J or j indicates a Julian day (1 to 366) of the
jjj or JJJ year.

hh or HH Represents hour. Hour is based on 24-hour clock. Always use leading zeros or blanks for hour
where appropriate, for example, '01' for 1 am. '00' is also valid value for hour of 12 a.m.

nn Represents minute. Always use leading zeros for minute where appropriate, for example, '08'
for 8 minutes.

ss[.ssssss] Represents seconds and fraction of a second.

aa Represents the a.m. or p.m. designation.

pp Represents the p.m. designation only if needed. (This is an incompatibility with SAP IQ ver­
sions earlier than 12.0; previously, “pp” was synonymous with “aa”.)

hh SAP IQ assumes zero for minutes and seconds. For example, if the SAP IQ value you enter is
'03', SAP IQ converts it to '03:00:00.0000'.

hh:nn or hh:mm SAP IQ assumes zero for seconds. For example, if the time value you enter is '03:25', SAP IQ
converts it to '03:25:00.0000'.

Sample DATE and DATETIME format options are:

Input data Format specification

12/31/98 DATE ('MM/DD/YY')

19981231 DATE ('YYYYMMDD')

123198140150 DATETIME ('MMDDYYhhnnss')

14:01:50 12-31-98 DATETIME ('hh:nn:ss MM-DD-YY')

18:27:53 DATETIME ('hh:nn:ss')

12/31/98 02:01:50AM DATETIME ('MM/DD/YY hh:nn:ssaa')

● The FILE NAME option allows you to insert the name of a file into a column when you perform a LOAD
INTO TABLE statement. When you do, the name of the file (but not its contents) is loaded into the column
for each of the rows in the table.
○ You can only specify this option for VARCHAR and CHAR columns.
○ The length of the file name cannot be longer than the maximum length of the column you are
specifying.
○ You can only specify one column for use with FILE NAME.
○ After the load inserts the file name into a column, the system does not add any information to mark
the column as a FILE NAME column.

SAP IQ SQL Reference


SQL Statements INTERNAL 1563
○ The column you specify for FILE NAME cannot contain any data.

SAP IQ has built-in load optimizations for common date, time, and datetime formats. If your data to be loaded
matches one of these formats, you can significantly decrease load time by using the appropriate format.

You can also specify the date/time field as an ASCII fixed-width field (as described above) and use the
FILLER(1) option to skip the column delimiter.

The NULL portion of the <column-spec> indicates how to treat certain input values as NULL values when
loading into the table column. These characters can include BLANKS, ZEROS, or any other list of literals you
define. When specifying a NULL value or reading a NULL value from the source file, the destination column
must be able to contain NULLs.

ZEROS are interpreted as follows: the cell is set to NULL if (and only if) the input data (before conversion, if
ASCII) is all binary zeros (and not character zeros).

● If the input data is character zero, then:


1. NULL (ZEROS) never causes the cell to be NULL.
2. NULL ('0') causes the cell to be NULL.
● If the input data is binary zero (all bits clear), then:
1. NULL (ZEROS) causes the cell to be NULL.
2. NULL ('0') never causes the cell to be NULL.

For example, if your LOAD TABLE statement includes col1 date('yymmdd') null(zeros) and the date is
000000, you receive an error indicating that 000000 cannot be converted to a DATE(4). To get LOAD TABLE
to insert a NULL value in col1 when the data is 000000, either write the NULL clause as null('000000'), or
modify the data to equal binary zeros and use NULL (ZEROS).

If the length of a VARCHAR cell is zero and the cell is not NULL, you get a zero-length cell. For all other data
types, if the length of the cell is zero, SAP IQ inserts a NULL. This is ANSI behavior. For non-ANSI treatment of
zero-length character data, set the NON_ANSI_NULL_VARCHAR database option.

Use the DEFAULT option to specify a load default column value. You can load a default value into a column, even
if the column does not have a default value defined in the table schema. This feature provides more flexibility at
load time.

● The LOAD TABLE DEFAULTS option must be ON in order to use the default value specified in the LOAD
TABLE statement. If the DEFAULTS option is OFF, the specified load default value is not used and a NULL
value is inserted into the column instead.
● The LOAD TABLE statement must contain at least one column that needs to be loaded from the file
specified in the LOAD TABLE statement. Otherwise, an error is reported and the load is not performed.
● The specified load default value must conform to the supported default values for columns and default
value restrictions. The LOAD TABLE DEFAULT option does not support AUTOINCREMENT, IDENTITY, or
GLOBAL AUTOINCREMENT as a load default value.
● The LOAD TABLE DEFAULT <default-value> must be of the same character set as that of the
database.
● Encryption of the default value is not supported for the load default values specified in the LOAD TABLE
DEFAULT clause.
● A constraint violation caused by evaluation of the specified load default value is counted for each row that
is inserted in the table.

Another important part of the <load-specification> is the FILLER option. This option indicates you want
to skip over a specified field in the source input file. For example, there may be characters at the end of rows or

SAP IQ SQL Reference


1564 INTERNAL SQL Statements
even entire fields in the input files that you do not want to add to the table. As with the <column-spec>
definition, FILLER specifies ASCII fixed length of bytes, variable length characters delimited by a separator, and
binary fields using PREFIX bytes.

Parquet Files

When you specify FORMAT parquet in the LOAD TABLE statement, SAP IQ ignores the following <column-
spec> options and issues a message with this information:

ASCII ( <input-width> )

PREFIX { 1 | 2 | 4 }

BINARY [ WITH NULL BYTE ]

PREFIX { 1 | 2 | 4 } BINARY [ WITH NULL BYTE ] [ VARYING ]

'<delimiter-string>'

The FORMAT parquet clause does not support the following <load-specification> options. If you specify
both, SAP IQ returns an error and rolls back the LOAD TABLE statement:

FILLER <filler-type>

<filler-type> ::=
{ <input-width>
| PREFIX { 1 | 2 | 4 }
| '<delimiter-string>'
}

Privileges

The privileges required depends on the database server -gl command line option, as follows. See GRANT
System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502] for assistance
with granting privileges.

Option Privilege Required

-gl ALL – (default) Requires one of:

● You are the owner of the table


● ALTER object-level privilege on the table
● LOAD object-level privilege on the table
● ALTER ANY TABLE system privilege
● LOAD ANY TABLE system privilege
● ALTER ANY OBJECT system privilege

SAP IQ SQL Reference


SQL Statements INTERNAL 1565
Option Privilege Required

-gl DBA Requires one of:

● ALTER ANY TABLE system privilege


● LOAD ANY TABLE system privilege
● ALTER ANY OBJECT system privilege

-gl NONE Execution of the LOAD TABLE statement is not permitted regardless of privi­
lege.

For more information on the -gl command line option, see SAP IQ Utility Reference > start_iq Database Server
Startup Utility > start_iq Server Options.

LOAD TABLE also requires a write lock on the table. When using the USING CLIENT FILE clause, you require:

● READ CLIENT FILE system privilege


● Read privileges on the directory being read from.
● The ALLOW_READ_CLIENT_FILE database option be enabled.
● The ALLOW_READ_CLIENT_FILE secure feature be enabled.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

● This example loads data from one file into the Products table on a Windows system. A tab is used as the
column delimiter following the Description and Color columns:

LOAD TABLE Products


( ID ASCII(6),
FILLER(1),
Name ASCII(15),
FILLER(1),
Description '\x09',
Size ASCII(2),
FILLER(1),
Color '\x09',
Quantity PREFIX 2,
UnitPrice PREFIX 2,
FILLER(2) )
FROM 'C:\\mydata\\source1.dmp'
QUOTES OFF ESCAPES OFF
BYTE ORDER LOW
NOTIFY 1000

● This example loads data from a file a.inp on a client computer:

LOAD TABLE t1(c1,c2,FILLER(30))

SAP IQ SQL Reference


1566 INTERNAL SQL Statements
USING CLIENT FILE 'c:\\client-data\\a.inp'
QUOTES OFF ESCAPES OFF
IGNORE CONSTRAINT UNIQUE 0, NULL 0
MESSAGE LOG 'c:\\client-data\\m.log'
ROW LOG 'c:\\client-data\\r.log'ONLY LOG UNIQUE

● This example loads data from two files into the product_new table (which allows NULL values) on a UNIX
system. The tab character is the default column delimiter, and the newline character is the row delimiter:

LOAD TABLE product_new


( id,
name,
description,
size,
color '\x09' NULL( 'null', 'none', 'na' ),
quantity PREFIX 2,
unit_price PREFIX 2 )
FROM '/s1/mydata/source2.dump',
'/s1/mydata/source3.dump'
QUOTES OFF ESCAPES OFF
FORMAT ascii
DELIMITED BY '\x09'
ON FILE ERROR CONTINUE
ROW DELIMITED BY '\n'

● This example ignores 10 word-length violations; on the 11th, deploy the new error and roll back the load:

load table PTAB1(


ck1 ',' null ('NULL') ,
ck3fk2c2 ',' null ('NULL') ,
ck4 ',' null ('NULL') ,
ck5 ',' null ('NULL') ,
ck6c1 ',' null ('NULL') ,
ck6c2 ',' null ('NULL') ,
rid ',' null ('NULL') )
FROM 'ri_index_selfRI.inp'
row delimited by '\n'
LIMIT 14 SKIP 10
IGNORE CONSTRAINT UNIQUE 2, FOREIGN KEY 8
word skip 10 quotes off escapes off strip
off
...

● This example loads data into table t1 from the BCP character file bcp_file.bcp using the FORMAT BCP
load option:

LOAD TABLE t1 (c1, c2, c3)


FROM 'bcp_file.bcp'
FORMAT BCP
...

● This example loads default values 12345 into c1 using the DEFAULT load option, and load c2 and c3 with
data from the LoadConst04.dat file:

LOAD TABLE t1 (c1 DEFAULT '12345 ', c2, c3, FILLER(1))


FROM 'LoadConst04.dat'
STRIP OFF
QUOTES OFF ESCAPES OFF
DELIMITED BY ',';

● This example loads c1 and c2 with data from the file bcp_file.bcp using the FORMAT BCP load option
and set c3 to the value 10:

LOAD TABLE t1 (c1, c2, c3 DEFAULT '10')


FROM 'bcp_file.bcp'

SAP IQ SQL Reference


SQL Statements INTERNAL 1567
FORMAT BCP
QUOTES OFF ESCAPES OFF;

● This code fragment ignores one header row at the beginning of the data file, where the header row is
delimited by '&&':

LOAD TABLE
...HEADER SKIP 1 HEADER DELIMITED by '&&'
...

● This code fragment ignores 2 header rows at the beginning of the data file, where each header row is
delimited by '\n':

LOAD TABLE
...HEADER SKIP 2
...

● This example loads a file into an RLV-enabled table.


Load data into RLV-enabled table rvt1 from the BCP character file bcp_file.bcp using the FORMAT bcp
load option:

LOAD TABLE rvt1 (c1, c2, c3)


FROM 'bcp_file.bcp'
FORMAT BCP
...

● This example loads a table from a CSV file, using a double quotation mark for the QUOTE enclosure
character and the backslash (\) for the QUOTE ESCAPE character.

LOAD TABLE tab1(c1, c2, c3)


FROM 'foo.csv'
DELIMITED BY ','
ROW DELIMITED BY '\n'
QUOTES ON ESCAPES OFF
QUOTE '"'
QUOTE ESCAPE '\'
FORMAT CSV;

● If QUOTE ESCAPE is not specified and foo.csv file contains:


○ """',"\\","\abc"
○ "\a\b\c","\\\\","""\dog"""
● Executing the following LOAD TABLE statement:

LOAD TABLE tab1(c1,c2,c3)


FROM 'foo.csv'
DELIMITED BY ','
ROW DELIMITED BY '\n'
QUOTES ON ESCAPES OFF
QUOTE '"'
FORMAT CSV;

Loads the data as:


c1 c2 c3
" \\ \abc
\a\b\c \\\\ "dog"
● This example loads a table, inserting the names of the files (datafile1.csv and datafile2.csv) into
the c2 column as specified by FILE NAME:

LOAD INTO TABLE test2 (c1, c2 FILE NAME, c3)


USING FILE 'datafile1.csv', 'datafile2.csv'

SAP IQ SQL Reference


1568 INTERNAL SQL Statements
QUOTES OFF ESCAPES OFF FORMAT CSV
DELIMITED BY ',' ROW DELIMITED BY '\n' ;

● In this example, the contents of datefile1.csv are:

c1_val1, c3_value1,
c1_val2, c3_value2,

The contents of datefile2.csv are:

c1_val21, c3_value21,
c1_val22, c3_value22,

After the load, the test2 table contains the following:

c1 c2 c3
========= ======== =========
c1_val1 datefile1.csv c3_value1
c1_val2 datefile1.csv c3_value2
c1_val21 datefile2.csv c3_value21
c1_val22 datefile2.csv c3_value22

● This example loads a table named test2 (which contains columns c1 and c2, both of which are
VARCHAR(20)), using files datafile1.csv and datafile2.csv, skipping the first header row from the
start of each file:

LOAD INTO TABLE test2 (c1, c2 )


USING FILE 'datafile1.csv', 'datafile2.csv'
QUOTES OFF ESCAPES OFF FORMAT CSV
HEADER SKIP ALL 1 DELIMITED BY ',' ROW DELIMITED BY '\n' ;

In this example, the contents of datefile1.csv are:

c1_val1, c3_value1,
c1_val2, c3_value2,

The contents of datefile2.csv are:

c1_val1, c3_value1,
c1_val2, c3_value2,

After the load, the contents of the test2 table are:

c1 c2
========= ======
c1_val2 c3_value2
c1_val22 c3_value22

● To execute a VARCHAR or VARBINARY load from a file generated by the data extraction facility, without
specifying the TEMP_EXTRACT_LENGTH_PREFIX option:

LOAD TABLE t1 (c1 BINARY WITH NULL BYTE) FROM 'yyy' FORMAT BINARY

You can specify this LOAD <column-spec>, binary, for any column data type — the column in this
example is c1.

SAP IQ SQL Reference


SQL Statements INTERNAL 1569
● This example uses the prefix <n> binary option to specify a VARCHAR or VARBINARY load from a file
generated by the data extraction facility using the TEMP_EXTRACT_LENGTH_PREFIX option set to 2, where
c1 is a VARCHAR column:

LOAD TABLE t1 (c1 PREFIX 2 BINARY WITH NULL BYTE) FROM 'xxx' FORMAT BINARY

You can only specify prefix <n> binary for VARCHAR and VARBINARY columns; which in this example is
c1.

Related Information

Loading Parquet Files


INSERT Statement [page 1534]
LOAD_ZEROLENGTH_ASNULL Option [page 1895]
NON_ANSI_NULL_VARCHAR Option [page 1940]
NOTIFY_MODULUS Option [page 1942]
TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]
TEMP_EXTRACT_VARYING Option [page 2053]
TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]
REVOKE System Privilege Statement [page 1635]

9.4.135 LOCK MUTEX statement

Locks a resource such as a file or system procedure using a predefined mutex.

 Syntax

LOCK MUTEX [ <owner>.]<mutex-name>


[ IN { SHARE | EXCLUSIVE } MODE ]
[ TIMEOUT <num-milliseconds> ]

Parameters

owner

The owner of the mutex. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
mutex-name

The name of the mutex. <mutex-name> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
IN { SHARE | EXCLUSIVE } MODE clause

SAP IQ SQL Reference


1570 INTERNAL SQL Statements
Use this clause to specify whether the lock provides exclusive access to the resource (EXCLUSIVE), or
whether other connections can use the resource as well (SHARE). If the IN...MODE clause is not specified,
then EXCLUSIVE is the default behavior.
TIMEOUT clause

The amount of time, in milliseconds (greater than 0), to wait to acquire the lock. If the TIMEOUT clause is
not specified, then the connection waits indefinitely until the lock can be acquired.

<number-milliseconds> can be specified using a variable (for example, TIMEOUT @timeout-value).


If <number-milliseconds> is set to a variable and the variable is NULL, the behavior is equivalent to not
specifying the clause.

Remarks

Recursive LOCK MUTEX statements are allowed; however, an equal number of releases (RELEASE MUTEX) are
required to release the mutex for connection-scope mutexes.

If a connection executes the LOCK MUTEX statement in SHARE MODE, and then again in EXCLUSIVE MODE, it
may be blocked if other connections have the mutex locked in SHARE MODE. If not, then then the lock mode
changes to an exclusive lock and remains that way until the lock is completely released by the connection.

For transaction-scope mutexes (that is, the SCOPE TRANSACTION clause was specified at creation time), the
mutex is held until the end of the transaction. For connection-scope mutexes (that is, the SCOPE
CONNECTION clause was specified at creation time), the mutex is held until a RELEASE MUTEX statement is
execute, or the connection is terminated.

LOCK MUTEX statements benefit from the same deadlock detection used for table and row locks.

Privileges

Requires one of:

● You own the semaphore


● UPDATE ANY MUTEX SEMAPHORE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None.

Standards

ANSI/ISO SQL Standard

SAP IQ SQL Reference


SQL Statements INTERNAL 1571
Not in the standard.

 Example

The following statement locks the protect_my_cr_section mutex in exclusive mode:

LOCK MUTEX protect_my_cr_section IN EXCLUSIVE MODE;

Related Information

CREATE MUTEX statement [page 1319]


DROP MUTEX statement [page 1449]
CREATE MUTEX statement [page 1319]
DROP MUTEX statement [page 1449]
RELEASE MUTEX statement [page 1603]
RELEASE MUTEX statement [page 1603]
REVOKE System Privilege Statement [page 1635]

9.4.136 LOCK TABLE Statement

Prevents other concurrent transactions from accessing or modifying a table within the specified time or lock
released by earlier transaction.

 Syntax

LOCK TABLE <table-list> [ WITH HOLD ]


IN { SHARE | WRITE | EXCLUSIVE } MODE [ WAIT <time> ]

<table-list> ::=
[ <owner>. ] <table-name> [ , [ <owner.> ] <table-name>, ...]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

table-name

SAP IQ SQL Reference


1572 INTERNAL SQL Statements
Must be a base table, not a view. WRITE mode is only valid for IQ base tables. LOCK TABLE either locks all
tables in the table list, or none. The table must not be enabled for row-level versioning (RLV). If obtaining a
lock for an SAP SQL Anywhere table, a multiplex write server, or when obtaining SHARE or EXCLUSIVE
locks, you may only specify a single table. Standard SAP IQ object qualification rules are used to parse
<table-name>.
table-name

LOCK TABLE either locks all tables in the table list, or none. The table must not be enabled for row-level
versioning (RLV). If obtaining a lock for a SAP SQL Anywhere table or when obtaining SHARE or
EXCLUSIVE locks, you may only specify a single table. Standard SAP IQ object qualification rules are used
to parse <>.
WITH HOLD

The lock is held 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. Using the WITH HOLD clause in the same statement with
WRITE MODE is unsupported and returns the error Must be a base table, not a view. WRITE mode is only
valid for IQ base tables. SQLCODE=-131, ODBC 3 State="42000".
SHARE

Must be a base table, not a view. WRITE mode is only valid for IQ basePrevents other transactions from
modifying the table, but allows them read access. In this mode, you can change data in the table as long as
no other transaction has locked the row being modified, either indirectly, or explicitly by using LOCK
TABLE.
WRITE

Prevents other transactions from modifying a list of tables. Unconditionally commits the connections
outermost transaction. The transaction’s snapshot version is established not by the LOCK TABLE IN
WRITE MODE statement, but by the execution of the next command processed by SAP IQ.

WRITE mode locks are released when the transaction commits or rolls back, or when the connection
disconnects.
EXCLUSIVE

Prevents other transactions from accessing the table. In this mode, no other transaction can execute
queries, updates of any kind, or any other action against the table.
WAIT time

Specifies maximum blocking time for all lock types. This clause is mandatory when lock mode is WRITE.
When a time argument is given, the server locks the specified tables only if available within the specified
time. The time argument can be specified in the format hh:nn:ss:sss. If a date part is specified, the server
ignores it and converts the argument into a timestamp. When no time argument is given, the server waits
indefinitely until a WRITE lock is available or an interrupt occurs.

Remarks

(back to top)

On a multiplex, only the coordinator supports LOCK TABLE.

SAP IQ SQL Reference


SQL Statements INTERNAL 1573
LOCK TABLE statements run on tables in the IQ main store on the coordinator do not affect access to those
tables from connections on secondary servers. For example:

On a coordinator connection, issue the command:

LOCK TABLE coord1 WITH HOLD IN EXCLUSIVE MODE

sp_iqlocks on the coordinator confirms that the table coord1 has an exclusive (E) lock.

The result of sp_iqlocks run on a connection on a secondary server does not show the exclusive lock on table
coord1. The user on this connection can see updates to table coord1 on the coordinator.

Other connections on the coordinator can see the exclusive lock on table coord1 and attempting to select
from table coord1 from another connection on the coordinator returns User DBA has the row in
coord1 locked.

LOCK TABLE on views is unsupported. Attempting to lock a view acquires a shared schema lock regardless of
the mode specified in the command. A shared schema lock prevents other transactions from modifying the
table schema.

The Transact-SQL (T-SQL) stored procedure dialect does not support LOCK TABLE. For example, this
statement returns Syntax error near LOCK:

CREATE PROCEDURE tproc()


AS
BEGIN
COMMIT;
LOCK TABLE t1 IN SHARE MODE
INSERT INTO t1 VALUES(30)
END

The Watcom-SQL stored procedure dialect supports LOCK TABLE. The default command delimiter is a
semicolon (;). For example:

CREATE PROCEDURE tproc()


AS
BEGIN
COMMIT;
LOCK TABLE t1 IN SHARE MODE
INSERT INTO t1 VALUES(30)
END

Privileges

(back to top)

The privilege varies by lock mode. See GRANT System Privilege Statement [page 1511] or GRANT Object-Level
Privilege Statement [page 1502] for assistance with granting privileges.

SAP IQ SQL Reference


1574 INTERNAL SQL Statements
Mode Privilege Required

Share mode Requires one of:

● You own the table


● SELECT ANY TABLE system privilege
● SELECT object-level privilege on the table

Exclusive mode Requires one of:

● You own the table


● ALTER ANY OBJECT system privilege
● ALTER ANY TABLE system privilege
● ALTER object-level privilege on the table

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise. The WITH HOLD clause is not
supported in SAP ASE. SAP ASE provides a WAIT clause that is not supported in SAP SQL Anywhere.

Examples

(back to top)

● This example obtains a WRITE lock on the Customers and Employees tables, if available within 5 minutes
and 3 seconds:

LOCK TABLE Customers, Employees IN WRITE MODE WAIT


'00:05:03'

● This example waits indefinitely until the WRITE lock on the Customers and Employees tables is available,
or an interrupt occurs:

LOCK TABLE Customers, Employees IN WRITE MODE WAIT

Related Information

SELECT Statement [page 1659]


REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1575
9.4.137 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 let you repeatedly execute a list of SQL
statements while a <search-condition> evaluates to TRUE. The LEAVE statement can be used to resume
execution at the first statement after the END LOOP.

If the ending <statement-label> is specified, it must match the beginning <statement-label>.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise. The WHILE statement
provides looping in Transact-SQL stored procedures.

Examples

● The following example shows 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 ;
...

SAP IQ SQL Reference


1576 INTERNAL SQL Statements
● The following example shows a labeled loop in a procedure:

SET i = 1;
lbl:
LOOP
INSERT
INTO Counters( number )
VALUES ( i ) ;
IF i >= 10 THEN
LEAVE lbl ;
END IF ;
SET i = i + 1 ;
END LOOP lbl

Related Information

FOR Statement [page 1479]


LEAVE Statement [page 1547]
WHILE Statement [T-SQL] [page 1718]
REVOKE System Privilege Statement [page 1635]

9.4.138 MESSAGE Statement

Displays a message, which can be any expression. Clauses can specify where the message is displayed.

 Syntax

MESSAGE <expression>, …
[ TYPE { INFO | ACTION | WARNING | STATUS } ]
[ TO { CONSOLE
| CLIENT [ FOR { CONNECTION <conn_id> [ IMMEDIATE ] | ALL } ]
| [ EVENT | SYSTEM ] LOG }
[ DEBUG ONLY ] ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

FOR

Specifies which connections receive notification about the message:

SAP IQ SQL Reference


SQL Statements INTERNAL 1577
● CONNECTION <conn_id> – the recipient's connection ID for the message.
● IMMEDIATE – the connection receives the message within a few seconds regardless of when the SQL
statement is executed.
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.
● ALL – all open connections receive the message.

The FOR clause can be used to notify another application of an event detected on the 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 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, you can use a second connection. This connection can
execute one or more WAITFOR DELAY statements. These statements do not consume significant
resources on the server or network (as would happen with a polling approach), but permit applications to
receive notification of the message shortly after it is sent.
TYPE

Has an effect only if the message is sent to the client. The client application must decide how to handle the
message. Interactive SQL displays messages in these locations:

● INFO – (default) the Message window.


● ACTION – a Message box with an OK button.
● WARNING – a Message box with an OK button.
● STATUS – the Messages pane.
TO

Specifies the destination of a message:

● CONSOLE – (default) send messages to the database server window.


● CLIENT – send messages to the client application. Your application must decide how to handle the
message, and you can use the TYPE clause as information on which to base that decision.
● LOG – send messages to the server log file specified by the -o option.
DEBUG ONLY

Controls whether debugging messages added to stored procedures are enabled or disabled by changing
the setting of the DEBUG_MESSAGES database 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 might result in a
small performance penalty.

SAP IQ SQL Reference


1578 INTERNAL SQL Statements
Remarks

(back to top)

The procedure issuing a MESSAGE … TO CLIENT statement must be associated with a connection.

For example, the message box is not displayed because the event occurs outside of a connection:

CREATE EVENT CheckIdleTime TYPE ServerIdle


WHERE event_condition( 'IdleTime' ) > 100
HANDLER
BEGIN
MESSAGE 'Idle engine' type warning to client;
END;

However, in this example, the message is written to the server console:

CREATE EVENT CheckIdleTime TYPE ServerIdle


WHERE event_condition( 'IdleTime' ) > 100
HANDLER
BEGIN
MESSAGE 'Idle engine' type warning to console;
END;

Valid expressions can include a quoted string or other constant, variable, or function. However, queries are not
permitted in the output of a MESSAGE statement, even though the definition of an expression includes queries.

ESQL and ODBC clients receive messages via message callback functions. In each case, these functions must
be registered. To register ESQL message handlers, use the db_register_callback function.

ODBC clients can register callback functions using the SQLSetConnectAttr function.

Privileges

(back to top)

The privilege varies by clause. See GRANT System Privilege Statement [page 1511] for assistance with granting
privileges.

Clause Privilege Required

FOR Requires one of:

● SERVER OPERATOR system privilege


● DROP CONNECTION system privilege

TO EVENT LOG or TO SYSTEM LOG Requires the SERVER OPERATOR system privilege

Standards

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1579
● SQL – vendor extension to ISO/ANSI SQL grammar
● SAP database products – not supported by SAP Adaptive Server Enterprise. The Transact-SQL PRINT
statement provides a similar feature, and is available in SAP SQL Anywhere.

Examples

(back to top)

● The following example displays the string The current date and time, and the current date and time,
on the database server message window:

CREATE PROCEDURE message_test ()


BEGIN
MESSAGE 'The current date and time: ', Now();
END;
CALL message_test();

● The following example registers a callback in ODBC by first declaring the message handler:

void SQL_CALLBACK my_msgproc(


void * sqlca,
unsigned char msg_type,
long code,
unsigned short len,
char* msg )
{ … }

Install the declared message handler by calling the SQLSetConnectAttr function:

rc = SQLSetConnectAttr(
dbc,
ASA_REGISTER_MESSAGE_CALLBACK,
(SQLPOINTER) &my_msgproc, SQL_IS_POINTER );

Related Information

CREATE PROCEDURE Statement [page 1321]


WAITFOR Statement [page 1713]
DEBUG_MESSAGES Option [page 1809]
REVOKE System Privilege Statement [page 1635]

9.4.139 NOTIFY SEMAPHORE statement

Increments the counter associated with a semaphore.

 Syntax

NOTIFY SEMAPHORE [ <owner>.]<semaphore-name>

SAP IQ SQL Reference


1580 INTERNAL SQL Statements
[ INCREMENT BY <number> ]

Parameters

owner

The owner of the semaphore. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
semaphore-name

The name of the semaphore. <semaphore-name> can also be specified using an indirect identifier (for
example, `[@<variable-name>]`).
INCREMENT BY clause

Specify a positive integer to indicate how much to increment the counter associated with the semaphore. If
this clause is not specified, then the counter is incremented by 1.

<number> can be specified using a variable (for example, INCREMENT BY @inc-number).

If you set <number> to NULL, or if it is set to a variable and the variable value is NULL, the behavior is
equivalent to not specifying the clause.

Remarks

If the counter is 0, and a connection is blocked on a WAITFOR SEMAPHORE statement on this semaphore, the
NOTIFY SEMAPHORE statement notifies the connection.

If a connection that notified a semaphore is dropped or canceled, the counter increment persists, so your
application needs to be able to address this case.

Privileges

Requires one of:

● You own the semaphore


● UPDATE ANY MUTEX SEMAPHORE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None.

SAP IQ SQL Reference


SQL Statements INTERNAL 1581
Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement increments the counter for the license_counter semaphore by 1:

NOTIFY SEMAPHORE license_counter INCREMENT BY 1;

Related Information

CREATE SEMAPHORE statement [page 1358]


DROP SEMAPHORE statement [page 1452]
CREATE SEMAPHORE statement [page 1358]
DROP SEMAPHORE statement [page 1452]
WAITFOR SEMAPHORE statement [page 1715]
WAITFOR SEMAPHORE statement [page 1715]
REVOKE System Privilege Statement [page 1635]

9.4.140 OPEN Statement [ESQL] [SP]

Opens a previously declared cursor to access information from the database.

 Syntax

OPEN <cursor-name>
... [ USING [ DESCRIPTOR { <sqlda-name> | <host-variable> [, …] } ] ]
... [ WITH HOLD ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

SAP IQ SQL Reference


1582 INTERNAL SQL Statements
cursor-name

Identifier or host-variable.

If the cursor name is specified by an identifier or string, then the corresponding DECLARE CURSOR
statement must appear prior to the OPEN in the C program; if the cursor name is specified by a host
variable, then the DECLARE CURSOR statement must execute before the OPEN statement.
USING

Specifies the host variables that are bound to the placeholder bind variables in the SELECT statement for
which the cursor has been declared.
sqlda-name

Identifier
WITH HOLD

Keeps the cursor open for subsequent transactions. The cursor 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.

Remarks

(back to top)

By default, all cursors are automatically closed at the end of the current transaction (COMMIT or ROLLBACK).

The cursor is positioned before the first row.

A cursor declared using the FOR READ ONLY clause sees the version of table(s) on which the cursor is declared
when the cursor is opened, not the version of table(s) at the time of the first FETCH statement.

The USING DESCRIPTOR sqlda-name, host-variable, and BLOCK n clauses are for Embedded SQL only.

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 in 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). The sqlerrd[2] field is the actual number of rows, if the database server can compute this value
without counting the rows.

Privileges

(back to top)

● Must have SELECT object-level permission on all tables in a SELECT statement or EXECUTE object-level
permission on the procedure in a CALL 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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1583
See GRANT Object-Level Privilege Statement [page 1502] for assistance with granting privileges

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products—The simple OPEN <cursor-name> syntax is supported by SAP Adaptive Server
Enterprise. None of the other clauses are supported in SAP ASE stored procedures. Open Client/Open
Server supports the USING descriptor or host name variable syntax.

Examples

(back to top)

● The following example uses OPEN in Embedded SQL:

EXEC SQL OPEN employee_cursor;

and

EXEC SQL PREPARE emp_stat FROM


'SELECT EmployeeID, Surname FROM Employees WHERE name like ?';
EXEC SQL DECLARE employee_cursor CURSOR FOR emp_stat;
EXEC SQL OPEN employee_cursor USING :pattern;

● The following example is from a procedure:

BEGIN
DECLARE cur_employee CURSOR FOR
SELECT Surname
FROM Employees ;
DECLARE name CHAR(40) ;
OPEN cur_employee;
LOOP
FETCH NEXT cur_employee into name ;
...
END LOOP
CLOSE cur_employee;
END

Related Information

CLOSE Statement [ESQL] [SP] [page 1231]


DECLARE CURSOR Statement [ESQL] [SP] [page 1415]
FETCH Statement [ESQL] [SP] [page 1475]
PREPARE Statement [ESQL] [page 1590]
RESUME Statement [page 1618]

SAP IQ SQL Reference


1584 INTERNAL SQL Statements
REVOKE System Privilege Statement [page 1635]

9.4.141 OUTPUT Statement [Interactive SQL]

Writes the information retrieved by the current query to a file.

 Syntax

OUTPUT TO <filename>
[ APPEND ] [ VERBOSE ]
[ FORMAT <output-format> ]
[ ESCAPE CHARACTER <character> ]
[ DELIMITED BY <string> ]
[ QUOTE <string> [ ALL ] ]
[ COLUMN WIDTHS ( <integer>, … ) ]
[ HEXADECIMAL { ON | OFF | ASIS } ]
[ ENCODING <encoding> ]
[ WITH COLUMN NAMES ]

<output-format> ::=
TEXT | FIXED | HTML | SQL | XML

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

FORMAT

The output format. If no FORMAT clause is specified, the Interactive SQL OUTPUT_FORMAT database option
setting is used.
TEXT

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 the ALL clause is specified in the QUOTE clause, all values (not
just strings) are quoted. TEXT is the default output format.

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 are exporting Java methods that have string return values, you must use the HEXADECIMAL OFF
clause.

SAP IQ SQL Reference


SQL Statements INTERNAL 1585
FIXED

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 you omit the COLUMN WIDTHS clause, the width for each column is computed from the data type for the
column, and is large enough to hold any value of that data type. The exception is that LONG VARCHAR and
LONG BINARY data defaults to 32 KB.
HTML

Output is in the Hyper Text Markup Language format.


SQL

Output is an Interactive SQL INPUT statement required to re-create the information in the table.

 Note

SAP IQ does not support the INPUT statement. Change this statement to a valid LOAD TABLE (or
INSERT) statement to use it to load data back in.

XML

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. The LOAD TABLE statement does not
accept XML as a file format.
APPEND

Appends the results of the query to the end of an existing output file without overwriting the previous
contents of the file. By default, if you do not use APPEND clause, the OUTPUT statement overwrites the
contents of the output file.

The APPEND clause is valid if the output format is TEXT, FIXED, or SQL.
VERBOSE

Error messages about the query, the SQL statement used to select the data, and the data itself are written
to the output file. By default, if you omit the VERBOSE clause, only the data is written to the file. The
VERBOSE clause is valid if the output format is TEXT, FIXED, or SQL.
ESCAPE CHARACTER

The default escape character for characters stored as hexadecimal codes and symbols is a backslash (\),
so \x0A is the line feed character, for example.

To change this default, use the ESCAPE CHARACTER clause. For example, to use the exclamation mark as
the escape character, enter:

... ESCAPE CHARACTER '!'

DELIMITED BY

For the TEXT output format only. The delimiter string, by default a comma, is placed between columns.
QUOTE

For the TEXT output format only. The quote string, by default a single quote character, is placed around
string values. If ALL is specified in the QUOTE clause, the quote string is placed around all values, not just
around strings.
COLUMN WIDTHS

SAP IQ SQL Reference


1586 INTERNAL SQL Statements
Specifies column widths for the FIXED format output.
HEXADECIMAL

Specifies how binary data is to be unloaded for the TEXT format only. When set to ON, binary data is
unloaded in the format 0xabcd. When set to OFF, binary data is escaped when unloaded (\xab\xcd). When
set to ASIS, values are written without any escaping even if the value contains control characters. ASIS is
useful for text that contains formatting characters such as tabs or carriage returns.
ENCODING

Specifies the encoding that is used to write the file. You can use the ENCODING clause only with the TEXT
format. Can be a string or identifier.

If you do not specify the ENCODING clause, Interactive SQL determines the code page that is used to write
the file as follows, where code page values occurring earlier in the list take precedence over those
occurring later:

● The code page specified with the DEFAULT_ISQL_ENCODING option (if this option is set)
● The default code page for the computer Interactive SQL is running on

Remarks

(back to top)

The current query is the SELECT or LOAD TABLE statement that generated the information that appears on
the Results tab in the Results pane. The OUTPUT statement reports an error if there is no current query.

 Note

OUTPUT is especially useful in making the results of a query or report available to another application, but is
not recommended for bulk operations. For high-volume data movement, use the ASCII and BINARY data
extraction functionality with the SELECT statement. The extraction functionality provides much better
performance for large-scale data movement, and creates an output file you can use for loads.

Privileges

(back to top)

None

Side Effects

(back to top)

In Interactive SQL, the Results tab displays only the results of the current query. All previous query results are
replaced with the current query results.

SAP IQ SQL Reference


SQL Statements INTERNAL 1587
Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

(back to top)

● The following example places the contents of the Employees table in a text file:

SELECT * FROM Employees;


OUTPUT TO employees.txt FORMAT TEXT

● The following example places the contents of the Employees table at the end of an existing file, and
includes any messages about the query in this file as well:

SELECT * FROM Employees;


OUTPUT TO employees.txt APPEND VERBOSE

● The following example exports 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.
Execute this statement with HEXADECIMAL ON:

SELECT 'line1\x0aline2'; OUTPUT TO file.txt HEXADECIMAL ON

The result is a file with one line in it, containing this text:

line10x0aline2

Execute the same statement with HEXADECIMAL OFF:

line1\x0aline2

If you set HEXADECIMAL to ASIS, the result is a file with two lines:

'line1
line2'

Using ASIS generates two lines, because the embedded line feed character has been exported without
being converted to a two-digit hex representation, and without a prefix.

Related Information

SELECT Statement [page 1659]


DEFAULT_ISQL_ENCODING Option [Interactive SQL] [page 1816]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1588 INTERNAL SQL Statements
9.4.142 PARAMETERS Statement [Interactive SQL]

Specifies parameters to an Interactive SQL (dbisql) command file.

 Syntax

PARAMETERS <parameter1>, <parameter2>, …

Remarks

PARAMETERS specifies how many parameters there are to a command file and also names those parameters so
that they can be referenced later in the command file.

Parameters are referenced by putting the named parameter into the command file where you want the
parameter to be substituted:

{parameter1}

There can be no spaces between the braces and the parameter name.

If a command file is invoked with fewer than the required number of parameters, dbisql prompts for values of
the missing parameters.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

This dbisql command file takes two parameters:

PARAMETERS department_id, file ;


SELECT Surname
FROM Employees
WHERE DepartmentID = {department_id}
>#{file}.dat;

SAP IQ SQL Reference


SQL Statements INTERNAL 1589
Related Information

READ Statement [Interactive SQL] [page 1598]


REVOKE System Privilege Statement [page 1635]

9.4.143 PREPARE Statement [ESQL]

Prepares a statement to be executed later or used for a cursor.

 Syntax

PREPARE <statement-name>
FROM <statement> [ FOR { READ ONLY | UPDATE [ OF <column-name-list> ] } ]
... [ 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 }

Go to:

● Remarks
● Privileges
● Side Effects
● Standards
● Examples

Parameters

(back to top)

statement-name

Referenced to execute the statement, or to open a cursor if the statement is a SELECT statement.
<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>.
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, SAP IQ provides either a value-sensitive
cursor or a sensitive cursor. Insensitive and asensitive cursors are not updatable.

SAP IQ SQL Reference


1590 INTERNAL SQL Statements
DESCRIBE INTO DESCRIPTOR

The prepared statement is described into the specified descriptor. The describe type may be any of the
describe types allowed in the DESCRIBE statement.

The DESCRIBE INTO DESCRIPTOR clause might improve performance, as it decrease the required client/
server communication.
WITH EXECUTE

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 PREPARE and 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 WITH EXECUTE clause might improve performance, as it decrease the required client/server
communication.
WITH VARIABLE RESULT

Describes procedures that may have more than one result set, with different numbers or types of columns.
If the WITH VARIABLE RESULT clause is used, the database server sets the SQLCOUNT value after the
describe to one of these values:

● 0 – the result set may change: the procedure call should be described again following each OPEN
statement.
● 1 – the result set is fixed. No reßdescribing is required.

Remarks

(back to top)

The PREPARE statement prepares a SQL statement from the <statement> and associates the prepared
statement with <statement-name>.

If a host variable is used for <statement-name>, it must have the type short int. There is a typedef for this
type in sqlca.h called a_sql_statement_number. This type is recognized by the SQL preprocessor and can
be used in a DECLARE section. The host variable is filled in by the database during the PREPARE statement and
need not be initialized by the programmer.

These statements can be prepared:

● ALTER
● CALL
● COMMENT ON
● CREATE
● DELETE
● DROP
● GRANT
● INSERT
● REVOKE
● SELECT

SAP IQ SQL Reference


SQL Statements INTERNAL 1591
● SET OPTION

Preparing COMMIT, PREPARE TO COMMIT, and ROLLBACK statements is still supported for compatibility.
However, perform 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.

 Note

Make sure that you DROP the statement after use. If you do not, then the memory associated with the
statement is not reclaimed.

Privileges

(back to top)

None

Side Effects

(back to top)

Any statement previously prepared with the same name is lost.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

(back to top)

The following example prepares a simple query:

EXEC SQL PREPARE employee_statement FROM


'SELECT Surname FROM Employees';

SAP IQ SQL Reference


1592 INTERNAL SQL Statements
Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


DESCRIBE Statement [ESQL] [page 1429]
DROP Statement [page 1433]
EXECUTE Statement [ESQL] [page 1467]
OPEN Statement [ESQL] [SP] [page 1582]
REVOKE System Privilege Statement [page 1635]

9.4.144 PRINT Statement [T-SQL]

Displays a message on the message window of the database server.

 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 JDBC application. If you are connected from an Embedded SQL or ODBC application, the
message displays on the database server window.

The format string can contain placeholders for the arguments in the optional argument list. These placeholders
are of the form <%nn!>, where <nn> is an integer between 1 and 20.

Privileges

None

Standards

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

SAP IQ SQL Reference


SQL Statements INTERNAL 1593
Examples

● The following example displays a message on the server message window:

CREATE PROCEDURE print_test


AS
PRINT 'Procedure called successfully'

● This statement returns the string Procedure called successfully to the client:

EXECUTE print_test

● The following example uses placeholders in the PRINT statement; execute these statements inside a
procedure:

DECLARE @var1 INT, @var2 INT


SELECT @var1 = 3, @var2 = 5
PRINT 'Variable 1 = %1!, Variable 2 = %2!', @var1, @var2

● The following example uses RAISERROR to disallow connections:

CREATE procedure DBA.login_check()


begin
// Allow a maximum of 3 concurrent connections
IF( db_property('ConnCount') > 3 ) then
raiserror 28000
'User %1! is not allowed to connect -- there are
already %2! users logged on',
current user,
cast(db_property('ConnCount') as int)-1;
ELSE
call sp_login_environment;
end if;
end
go
grant execute on DBA.login_check to PUBLIC
go
set option PUBLIC.Login_procedure='DBA.login_check'
go

For an alternate way to disallow connections, use the LOGIN_PROCEDURE option or the
sp_iqmodifylogin system stored procedure.

Related Information

MESSAGE Statement [page 1577]


LOGIN_PROCEDURE Option [page 1901]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1594 INTERNAL SQL Statements
9.4.145 PUT Statement [ESQL]

Inserts a row into the specified cursor.

 Syntax

PUT <cursor-name> [ USING DESCRIPTOR <sqlda-name>


| FROM <hostvar-list> ] [ INTO { DESCRIPTOR <into-sqlda>-<name>
| <into-hostvar-list> } ] [ ARRAY :<nnn> ]

Parameters

cursor-name

Identifier or hostvar
sqlda-name

Identifier
sqlda-name

May contain indicator variables


ARRAY

Can be used to carry out wide puts, which insert more than one row at a time and which might improve
performance. The value <nnn> is the number of rows to be inserted. The SQLDA must contain <nnn> *
(columns per row) variables. The first row is placed in SQLDA variables 0 to (columns per row) - 1, and so
on.

 Note

For scroll (values-sensitive) cursors, the inserted row appears 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 might appear. Insensitive cursors cannot be updated.

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.

SAP IQ SQL Reference


SQL Statements INTERNAL 1595
For information on putting LONG VARCHAR or LONG BINARY values into the database, see SET statement
[ESQL].

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.

Privileges

Requires the INSERT object-level privilege. See GRANT Object-Level Privilege Statement [page 1502] for
assistance with granting privileges

Side Effects

Automatic commit

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

The following example uses PUT in Embedded SQL:

EXEC SQL PUT cur_employee FROM :EmployeeID, :Surname;

Related Information

DELETE (Positioned) Statement [ESQL] [SP] [page 1427]


INSERT Statement [page 1534]
SET Statement [ESQL] [page 1670]
UPDATE Statement [page 1700]
UPDATE (Positioned) Statement [ESQL] [SP] [page 1705]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1596 INTERNAL SQL Statements
9.4.146 RAISERROR Statement [T-SQL]

Allows user-defined errors to be signaled, and sends a message on the client.

 Syntax

RAISERROR <error-number> [ <format-string> ] [, <arg-list >]

Parameters

error-number

A 5-digit integer greater than 17000. The error number is stored in the global variable <@@error>.
format-string

If not supplied or is empty, the error number is used to locate an error message in the system tables. SAP
Adaptive Server Enterprise obtains messages 17000-19999 from the SYSMESSAGES table. In SAP IQ, this
table is an empty view, so errors in this range should provide a format string. Messages for error numbers
of 20000 or greater are obtained from the SYS.SYSUSERMESSAGES table.

The <format-string> can be up to 255 bytes long. This is the same as in SAP ASE.

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.

Remarks

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.

The extended values supported by the SQL Server or SAP ASE RAISERROR statement are not supported in
SAP IQ.

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 the @@error
global variable at different execution points.

Privileges

None

SAP IQ SQL Reference


SQL Statements INTERNAL 1597
Standards

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

The following example raises error 99999, which is in the range for user-defined errors, and send a message to
the client:

RAISERROR 99999 'Invalid entry for this


column: %1!', @val

Related Information

CONTINUE_AFTER_RAISERROR Option [TSQL] [page 1786]


ON_TSQL_ERROR Option [TSQL] [page 1946]
REVOKE System Privilege Statement [page 1635]

9.4.147 READ Statement [Interactive SQL]

Reads Interactive SQL (dbisql) statements from a file.

 Syntax

READ [ ENCODING <encoding> ] <filename> [ <parameter> ] …

Go to:

● Privileges
● Standards
● Examples

Parameters

(back to top)

ENCODING

An identifier or string that specifies encoding that is used to read the file.

SAP IQ SQL Reference


1598 INTERNAL SQL Statements
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 used.


2. The encoding specified by the byte order mark (BOM) in the file, if used.
3. The encoding specified with the default_isql_encoding option, if used.
4. The default encoding for the platform you are running on.
filename

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 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, 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, then the directories specified in the environment variable PATH.
parameter

Can be listed after the name of the SQL script file, and 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> }.

The parameters passed to a script file can be identifiers, numbers, quoted identifiers, or strings. Any
quotes around a parameter are placed 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.

Privileges

(back to top)

None

SAP IQ SQL Reference


SQL Statements INTERNAL 1599
Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

(back to top)

● The following example reads from the file status.rpt and birthday.sql and passes the parameter
values to the variables within the file:

READ status.rpt '160'

READ birthday.sql [>= '1988-1-1'] [<= '1988-1-30']

● The following example uses the PARAMETERS clause to pass parameters to a script file:

[test1.sql]
PARAMETERS par1, par2;
BEGIN
DECLARE v_par1 int;
DECLARE v_par2 varchar(200)
SET v_par1 = {par1};
SET v_par2 = {par2};
MESSAGE STRING('PAR1 Value: ', v_par1 ) TO CLIENT;
MESSAGE STRING('PAR2 Value: ', v_par2 ) TO CLIENT;
END;

(USR1)> READ test1.sql 123 '041028'


PAR1 Value: 123
PAR2 Value: 041028

 Note

You must enclose the second parameter value 041028 in quotes, as <v_par2> is declared as a
character data type.

Related Information

DEFAULT_ISQL_ENCODING Option [Interactive SQL] [page 1816]


PARAMETERS Statement [Interactive SQL] [page 1589]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1600 INTERNAL SQL Statements
9.4.148 REFRESH TEXT INDEX Statement

Refreshes a text index.

 Syntax

REFRESH TEXT INDEX <text-index-name> ON [ <owner>.]<table-name>


[ WITH {
ISOLATION LEVEL <isolation-level>
| EXCLUSIVE MODE
| SHARE MODE } ]
[ FORCE { BUILD | INCREMENTAL } ]

Parameters

WITH

Use the WITH clause to specify what kind of locks to obtain on the underlying base tables during the
refresh. The types of locks obtained determine how the text index is populated and how concurrency for
transactions is affected. If you do not specify the WITH clause, the default is WITH ISOLATION LEVEL
READ UNCOMMITTED, regardless of any isolation level set for the connection.

You can specify the following WITH clause options:

● ISOLATION LEVEL <isolation-level> – changes 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 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 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 { BUILD | INCREMENTAL }

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 – refreshes the text index by re-creating it. Use this clause to force a complete rebuild of
the text index.
● FORCE INCREMENTAL – 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

SAP IQ SQL Reference


SQL Statements INTERNAL 1601
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.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use either
statement or transaction snapshots.

Privileges

Requires one of:

● You own the table


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● REFERENCES object-level privilege on the table

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

The following example refreshes a fictitious text index called MarketingTextIndex, forcing it to be rebuilt:

REFRESH TEXT INDEX MarketingTextIndex ON GROUPO.MarketingInformation

SAP IQ SQL Reference


1602 INTERNAL SQL Statements
FORCE BUILD;

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.149 RELEASE MUTEX statement

Releases the specified connection-scope mutex, if it is locked by the current connection.

 Syntax

RELEASE MUTEX [ <owner>.]<mutex-name>

Parameters

owner

The owner of the mutex. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
mutex-name

The name of the mutex. <mutex-name> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).

Remarks

The RELEASE MUTEX statement releases one instance of lock on the mutex. So, if a connection has locked the
mutex multiple times, then only one lock on the mutex is released per RELEASE MUTEX statement.

An error is returned if the mutex was not locked by the current connection or if the release is being requested
for a transaction-scope mutex.

The RELEASE MUTEX statement will succeed on a dropped mutex that is locked by the current connection.

Privileges

Requires one of:

SAP IQ SQL Reference


SQL Statements INTERNAL 1603
● You own the mutex
● UPDATE ANY MUTEX SEMAPHORE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement releases the protect_my_cr_section mutex:

RELEASE MUTEX protect_my_cr_section;

Related Information

CREATE MUTEX statement [page 1319]


DROP MUTEX statement [page 1449]
LOCK MUTEX statement [page 1570]
CREATE MUTEX statement [page 1319]
DROP MUTEX statement [page 1449]
LOCK MUTEX statement [page 1570]
REVOKE System Privilege Statement [page 1635]

9.4.150 RELEASE SAVEPOINT Statement

Releases a savepoint within the current transaction.

 Syntax

RELEASE SAVEPOINT [ <savepoint-name> ]

SAP IQ SQL Reference


1604 INTERNAL SQL Statements
Parameters

savepoint-name

An identifier specified on a SAVEPOINT statement within the current transaction. If <savepoint-name> is


omitted, the most recent savepoint is released.

Remarks

Releasing a savepoint does not perform any type of COMMIT; it simply removes the savepoint from the list of
currently active savepoints.

There must have been a corresponding SAVEPOINT within the current transaction.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. A similar feature is available in
an SAP ASE-compatible manner using nested transactions.

Related Information

ROLLBACK TO SAVEPOINT Statement [page 1655]


SAVEPOINT Statement [page 1658]
REVOKE System Privilege Statement [page 1635]

9.4.151 REMOVE Statement

Removes a class, a package, or a JAR file from a database. Removed classes are no longer available for use as a
variable type. Any class, package, or JAR to be removed must already be installed.

 Syntax

REMOVE JAVA <classes_to_remove>

SAP IQ SQL Reference


SQL Statements INTERNAL 1605
<classes_to_remove>
{ CLASS <java_class_name> [, <java_class_name> ]…
| PACKAGE <java_package_name> [, <java_package_name> ]…
| JAR <jar_name> [, <jar_name> ]… [ RETAIN CLASSES ] }

Parameters

CLASS java_class_name

Specifies the name of one or more Java classes to be removed. Those classes must be installed classes in
the current database.
PACKAGE java_package_name

Specifies the name of one or more Java packages to be removed. Those packages must be the name of
packages in the current database.
JAR jar_name

Specifies a character string value of maximum length 255. Each <jar_name> must be equal to the
<jar_name> of a retained JAR in the current database. Equality of <jar_name> is determined by the
character string comparison rules of the SQL system.
RETAIN CLASSES

The specified JARs are no longer retained in the database, and the retained classes have no associated
JAR. If RETAIN CLASSES is specified, this is the only action of the REMOVE statement.

Privileges

Requires one of:

● You own the object


● MANAGE ANY EXTERNAL OBJECT system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. A similar feature is available in
an SAP ASE-compatible manner using nested transactions.

SAP IQ SQL Reference


1606 INTERNAL SQL Statements
Examples

The following example removes a Java class named "Demo" from the current database:

REMOVE JAVA CLASS Demo

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.152 RESIGNAL Statement

Resignals an exception condition.

 Syntax

RESIGNAL [ <exception-name> ]

Remarks

Within an exception handler, RESIGNAL lets you quit the compound statement with the exception still active, or
quit reporting another named exception. The exception is handled by another exception handler or returned to
the application. Any actions by the exception handler before the RESIGNAL are undone.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant.


● SAP database products – not supported by SAP Adaptive Server Enterprise. Error handling in Transact-
SQL procedures is carried out using the RAISERROR statement.

SAP IQ SQL Reference


SQL Statements INTERNAL 1607
Examples

This code fragment returns all exceptions except for “Column Not Found” to the application:

...
DECLARE COLUMN_NOT_FOUND EXCEPTION
FOR SQLSTATE '52003';
...
EXCEPTION
WHEN COLUMN_NOT_FOUND THEN
SET message='Column not found' ;
WHEN OTHERS THEN
RESIGNAL ;

Related Information

BEGIN … END Statement [page 1218]


SIGNAL Statement [page 1684]
REVOKE System Privilege Statement [page 1635]

9.4.153 RESTORE DATABASE Statement

Restores an SAP IQ database backup from one or more archive devices.

 Syntax

Syntax 1

RESTORE DATABASE '<db_file>'


[ FROM '<archive_device>' ]…
… [ CATALOG ONLY ]
… [ KEY <key_spec> ]
… [ [ RENAME <logical-dbfile-name> TO '<new-dbspace-path>']…
| VERIFY [ COMPATIBLE ] ]

Syntax 2

RESTORE DATABASE '<database-name>'


[ <restore-option> …]
FROM '<archive_device>' <…>

<restore-option> ::=
[MULTIPLEX]
READONLY <dbspace-or-file> [, … ]
KEY <key_spec>
RENAME <file-name> TO <new-file-path> …

Syntax 3

RESTORE DATABASE '<db_file>'

SAP IQ SQL Reference


1608 INTERNAL SQL Statements
FROM '<file-name>' <…>
USING LOG PATH '<directory>', […]
RECOVER UNTIL [ <TIMESTAMP> <timestamptz> | <OFFSET> <log-offset> ]
ON TIMELINE '<GUID>'
[ OVERWRITE EXISTING CLEAR LOG ]
KEY <key_spec>
[ VERIFY COMPATIBLE ]

Parameters

db_file

Relative or absolute path of the database to be restored. Can be the original location, or a new location for
the catalog store file.
FROM archive_device

Specifies the name of the <archive_device> from which you are restoring, delimited with single
quotation marks. If you are using multiple archive devices, specify them using separate FROM clauses. A
comma-separated list is not allowed. Archive devices must be distinct. The number of FROM clauses
determines the amount of parallelism Quoted string including mixed cases, numbers, letters, and special
characters. It might be necessary to protect the key from interpretation or alteration by the command
shell.SAP IQ attempts with regard to input devices.

The backup and restore API DLL implementation lets you specify arguments to pass to the DLL when
opening an archive device. For third-party implementations, the <archive_device> string has this
format:

'<dll_name>::<vendor_specific_information>'

For example:

'spsc::workorder=12;volname=ASD002'

The <archive_device> string can be up to 1023 bytes long. The <dll_name> portion is 1 to 30 bytes
long and can only contain alphanumeric and underscore characters. The
<vendor_specific_information> portion of the string is passed to the third-party implementation
without checking its contents.

Only certain third-party products are certified with SAP IQ using this syntax. Before using any third-party
product to back up your SAP IQ database, make sure it is certified.

For the SAP IQ implementation of the backup and restore API, you need not specify information other than
the tape device name or file name. However, if you use disk devices, you must specify the same number of
archive devices on the restore as given on the backup; otherwise, you may have a different number of
restoration devices than the number used to perform the backup. A specific example of an archive device
for the SAP IQ API DLL that specifies a non-rewinding tape device on a UNIX-like operating system is:

'/dev/rmt/0n'

CATALOG ONLY

Restores only the backup header record from the archive media. Cannot be used with the MULTIPLEX
keyword.

SAP IQ SQL Reference


SQL Statements INTERNAL 1609
USING LOG PATH directory

Instructs server to search along multiple paths for point-in-time recovery logs:

USING LOG PATH '<directory 1>, <directory 2>, ...'

Use a comma as a delimiter between directory names. The log name does not need to be specified. If any
required files are missing, the server reports an error.

On multiplex servers, use the current transaction log from the coordinator node. Do not include transaction
logs from secondary nodes. Including transaction logs from secondary nodes causes point-in-time
recovery to fail, and return a Files are missing for Point-in-time-Recovery error.
RECOVER UNTIL . . .

Recovers data from the recovery logs up to the date and time specified by the timestamp, or transaction
log-offset:

RECOVER UNTIL [ TIMESTAMP <timestamptz> | OFFSET <log-offset> ]

<timestamptz> is a TIMESTAMP WITH TIMEZONE data type. <logoffset> is an UNSIGNED BIGINT that
represents a transaction log offset.

Always specify a timestamp that is greater than the backup time of the data backup specified in the FROM
clause of the restore command. This ensures that the database includes all committed transactions in the
recovery logs. If the specified point in time is earlier than the last checkpoint in the backup database, the
server returns an error.

 Restriction

● A dbspace that you create after enabling point-in-time recovery may only be recorded in the point-
in-time recovery log. If this is the case, you cannot rename the dbspace during a RESTORE
DATABASE RECOVER UNTIL operation.
● If RESTORE DATABASE cannot locate the transaction log, RLV log, and point-in-time recovery logs
during a point-in-time recovery, the recovery operation fails. This can happen in cases when the
database is restored to a new location and there are no logs available in the new environment. In
cases like this, use the CLEAR LOG clause to ignore the current log area of the database you want
to restore and cancel the automatic log backups that normally occur during a recovery operation.

ON TIMELINE

Restores the database to an alternate timeline:

ON TIMELINE '<GUID>'

The ON TIMELINE clause requires a timeline GUID that identifies the alternate timeline. Point-in-time
recovery operations without this clause restore to the current timeline.
OVERWRITE EXISTING

Overwrites existing dbfiles and transaction logs during a point-in-time recovery operation:

OVERWRITE EXISTING

Point-in-time recovery operations generally restore dbfiles to a different location than the current dbspace.
Use the OVERWRITE EXISTING clause to restore a database to a location that already has a database, and
overwrite any existing dbfiles with the same name.

SAP IQ SQL Reference


1610 INTERNAL SQL Statements
The OVERWRITE EXISTING clause can appear as a restore option at any position in a RESTORE DATABASE
statement.
CLEAR LOG

Ignores the current log area of the database during a restore: cancels automatic log backups during a
point-in-time recovery operation:

CLEAR LOG

If RESTORE DATABASE cannot locate the transaction log, RLV log, and point-in-time recovery logs during a
point-in-time recovery, the recovery operation fails. This can happen in cases when the database is
restored to a new location and there are no logs available in the new environment. In cases like this, use the
CLEAR LOG clause to ignore the current log area of the database you want to restore and cancel the
automatic log backups that normally occur during a recovery operation.

During point-in-time recovery, the restore automatically backs up the existing transaction log and RLV log.
Every point-in-time restore looks for the existing transaction log, RLV log, and point in time logs in the
existing database directories. The restore operation returns an error if it fails to locate these logs. If you
want to restore to a new environment, however, and have no existing logs to back up, supply a RESTORE
command with the CLEAR LOG clause to stop SAP IQ from seeking existing log files in the database
directories.
RENAME

Restores one or more SAP IQ database files to a new location. Specify each <dbspace-name> you are
moving as it appears in the table. Specify <new-dbspace-path> as the new raw partition, or the new full
or relative path name, for that dbspace.

If relative paths were used to create the database files, the files are restored by default relative to the
catalog store file (the SYSTEM dbspace), and a rename clause is not required. If absolute paths were used
to create the database files and a rename clause is not specified for a file, it is restored to its original
location.

Relative path names in the RENAME clause work as they do when you create a database or dbspace: the
main IQ store dbspace, temporary store dbspaces, and Message Log are restored relative to the location of
db_file (the catalog store); user-created IQ store dbspaces are restored relative to the directory that
holds the main IQ dbspace.

Do not use the RENAME clause to move the SYSTEM dbspace, which holds the catalog store. To move the
catalog store, and any files created relative to it and not specified in a RENAME clause, specify a new
location in the <db_file> parameter.

If the dbspace name contains a file extension such as .iq or .iqtmp, enclose the dbspace name in double
quotation marks when specifying the name in a RESTORE DATABASEQuoted string including mixed cases,
numbers, letters, and special command RENAME clause, such as the following two examples:

RENAME temp1 TO '/work/temp1_res.iqtmp.iqtmp'


DBSPACENAME "temp1_res.iqtmp"

RENAME "test_prod2.iq" TO '/test/test_prod2.iq'

VERIFY [ COMPATIBLE ]

Directs the server to validate the specified SAP IQ database backup archives for a full, incremental,
incremental since full, or virtual backup. The backup must be SAP IQ version 12.6 or later. The verification

SAP IQ SQL Reference


SQL Statements INTERNAL 1611
process checks the specified archives for the same errors a restore process checks, but performs no write
operations. All status messages and detected errors are written to the server log file.

You cannot use the RENAME clause with the VERIFY clause; an error is reported.

The backup verification process can run on a different host than the database host. You must have the
BACKUP DATABASE system privilege to run RESTORE DATABASE VERIFY.

If the COMPATIBLE clause is specified with VERIFY, the compatibility of an incremental archive is checked
with the existing database files. If the database files do not exist on the system on which RESTORE
DATABASE…VERIFY COMPATIBLE is invoked, an error is returned. If COMPATIBLE is specified while
verifying a full backup, the keyword is ignored; no compatibility checks need to be made while restoring a
full backup.

You must have the database and log files (.db and .log) to validate the backup of a read-only dbspace
within a full backup. If you do not have these files, validate the entire backup by running RESTORE
DATABASE…VERIFY without the READONLY <dbspace> clause.

 Note

The verification of a backup archive is different than the database consistency checker (DBCC) verify
mode (sp_iqcheckdb 'verify...'). RESTORE DATABASE VERIFY validates the consistency of
the backup archive to be sure it can be restored, whereas DBCC validates the consistency of the
database data.

Run sp_iqcheckdb 'verify...' before taking a backup. If an inconsistent database is backed up,
then restored from the same backup archive, the data continues to be in an inconsistent state, even if
RESTORE DATABASE VERIFY reports a successful validation.

Remarks

The RESTORE DATABASE command requires exclusive access on an Oracle Solaris platform. On Solaris, user
with the SERVER OPERATOR system privilege to the database. This exclusive access is achieved by setting the
-gd switch to DBA, which is the default when you start the server engine.

Issue the RESTORE DATABASE command before you start the database (you must be connected to the
utility_db database). Once you finish specifying RESTORE DATABASE CHECKPOINT of the last backup you
restored. You can now specify a START DATABASE to allow other users to access the restored database.

The maximum size for a complete RESTORE DATABASE command, including all clauses, is 32KB.

When restoring to a raw device, make sure the device is large enough to hold the dbspace you are restoring.
SAP IQ RESTORE DATABASE checks the raw device size and returns an error, if the raw device is not large
enough to restore the dbspace.

BACKUP DATABASE allows you to specify full or incremental backups. There are two kinds of incremental
backups. INCREMENTAL backs up only those blocks that have changed and committed since the last backup
of any type (incremental or full). INCREMENTAL SINCE FULL backs up all the blocks that have changed since
the last full backup. If a restore of a full backup is followed by one or more incremental backups (of either type),
no modifications to the database are allowed between successive RESTORE DATABASE commands. This rule
prevents a restore from incremental backups on a database in need of crash recovery, or one that has been

SAP IQ SQL Reference


1612 INTERNAL SQL Statements
modified. You can still overwrite such a database with a restore from a full backup. Avoid starting the database
until after the entire sequence of incremental backups has completed.

Before starting a full restore, you must delete two files: the catalog store file (default name dbname.db) and the
transaction log file (default name dbname.log).

If you restore an incremental backup, RESTORE DATABASE ensures that backup media sets are accessed in the
proper order. This order restores the last full backup tape set first, then the first incremental backup tape set,
then the next most recent set, and so forth, until the most recent incremental backup tape set. If a user with
the SERVER OPERATOR system privilege produced an INCREMENTAL SINCE FULL backup, only the full
backup tape set and the most recent INCREMENTAL SINCE FULL backup tape set is required; however, if there
is an INCREMENTAL backup made since the INCREMENTAL SINCE FULL backup, it also must be applied.

SAP IQ ensures that the restoration order is appropriate, or it displays an error. Any other errors that occur
during the restore results in the database being marked corrupt and unusable. To clean up a corrupt database,
do a restore from a full backup, followed by any additional incremental backups. Since the corruption probably
happened with one of those backups, you might need to ignore a later backup set and use an earlier set.

To restore read-only files or dbspaces from an archive backup, the database may be running and the
administrator may connect to the database when issuing the RESTORE DATABASE statement. The read-only
file pathname doesn't need to match the names in the backup, if they otherwise match the database system
table information.

The database must not be running to restore a FULL, INCREMENTAL SINCE FULL, or INCREMENTAL restore of
either a READWRITE FILES ONLY or an all files backup. The database may or may not be running to restore a
backup of read-only files. When restoring specific files in a read-only dbspace, the dbspace must be offline.
When restoring read-only files in a read-write dbspace, the dbspace can be online or offline. The restore closes
the read-only files, restores the files, and reopens those files at the end of the restore.

You can use selective restore to restore a read-only dbspace, as long as the dbspace is still in the same read-
only state.

Other RESTORE DATABASE issues:

● RESTORE DATABASE to disk does not support raw devices as archival devices.
● SAP IQ does not rewind tapes before using them; on rewinding tape devices, it does rewind tapes after
using them. You must position each tape to the start of the SAP IQ data before starting the restore.
● During backup and restore operations, if SAP IQ cannot open the archive device (for example, when it
needs the media loaded) and the ATTENDED option is ON, it waits for ten seconds for you to put the next
tape in the drive, and then tries again. It continues these attempts indefinitely until either it is successful or
the operation is terminated with Ctrl + C .
● If you press Ctrl + C , RESTORE DATABASE fails and returns the database to its state before the
restoration began.
● If disk striping is used, the striped disks are treated as a single device.
● The file_name column in the SYSFILE system table for the SYSTEM dbspace is not updated during a
restore. For the SYSTEM dbspace, the file_name column always reflects the name when the database was
created. The file name of the SYSTEM dbspace is the name of the database file.

SAP IQ SQL Reference


SQL Statements INTERNAL 1613
Privileges

The permissions required to execute this statement are set using the -gu server command line option, as
follows:

● NONE – No user can issue this statement.


● DBA – Requires the SERVER OPERATOR system privilege.
● UTILITY_DB – Only those users who can connect to the utility_db database can issue this statement.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● (UNIX) This example restores the iqdemo database from tape devices /dev/rmt/0 and /dev/rmt/2 on a
Sun Solaris platform. On Solaris, a RESTORE from tape must specify the use of the rewinding device.
Therefore, do not include the letter n after the device name, which specifies no rewind on close. To
specify this feature with RESTORE DATABASE commands, use the naming convention appropriate for your
UNIX platform. (Windows does not support this feature.)

RESTORE DATABASE 'iqdemo'


FROM '/dev/rmt/0'
FROM '/dev/rmt/2'

● This example restores an encrypted database named marvin that was encrypted with the key <is!
seCret>:

RESTORE DATABASE 'marvin'


FROM 'marvin_bkup_file1'
FROM 'marvin_bkup_file2'
FROM 'marvin_bkup_file3'
KEY 'is!seCret'

● This example shows the syntax of a BACKUP DATABASE statement and two possible RESTORE DATABASE
statements. (This example uses objects in the iqdemo database for illustration purposes. Note that
iqdemo includes a sample user dbspace named iq_main that may not be present in your database.)
Given this BACKUP DATABASE statement:

BACKUP DATABASE READONLY DBSPACES iq_main


TO '/system1/IQ16/demo/backup/iqmain'

The dbspace iq_main can be restored using either of these RESTORE DATABASE statements:

RESTORE DATABASE 'iqdemo' READONLY DBSPACES iq_main


FROM '/system1/IQ16/demo/backup/iqmain'

SAP IQ SQL Reference


1614 INTERNAL SQL Statements
RESTORE DATABASE 'iqdemo'
FROM '/system1/IQ16/demo/backup/iqmain'

A selective backup backs up either all READWRITE dbspaces or specific read-only dbspaces or dbfiles.
Selective backups are a subtype of either full or incremental backups.
Notes:
○ You can take a READONLY selective backup and restore all objects from this backup (as in the second
example above).
○ You can take an all-inclusive backup and restore read-only files and dbspaces selectively.
○ You can take a READONLY selective backup of multiple read-only files and dbspaces and restore a
subset of read-only files and dbspaces selectively. See Permissions.
○ You can restore the read-only backup, only if the read-only files have not changed since the backup.
Once the dbspace is made read-write again, the read-only backup is invalid, unless you restore the
entire read-write portion of the database back to the point at which the read-only dbspace was read-
only.
○ Decide which backup subtype to use (either selective or non-selective) and use it consistently. If you
must switch from a non-selective to a selective backup, or vice versa, always take a non-selective full
backup before switching to the new subtype, to ensure that you have all changes.
● This example validates the database archives using the VERIFY clause, without performing any write
operations:

RESTORE DATABASE <database_name.db>


FROM '/sys1/dump/dmp1'
FROM '/sys1/dump/dmp2'
VERIFY

● When you use validate, specify a different database name to avoid Database name not unique errors.
If the original database is iqdemo.db, for example, use iq_demo_new.db instead:

RESTORE DATABASE iqdemo_new.db FROM iqdemo.bkp VERIFY

● Point-in-time recovery using point-in-time recovery logs only:

// enable Point in time recovery


SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON'
ALTER DBSPACE IQ_SYSTEM_LOG RENAME '/demo/pitrLog/PITRLOG'
BACKUP DATABASE FULL to '/demo/dataBackup/FULL1'
// perform some DDL/DML operations
CREATE TABLE T1 ( ID INT )
INSERT INTO T1 VALUES (1)
// record timestamp TS1 / OFFSET OFS1
TS1: select getdate()
OFS1: select db_property('LastCommitRedoPos')
// perform DDL/ DML operations
CREATE TABLE T2 ( ID INT )
INSERT INTO T2 VALUES (1)
// record timestamp TS2 / OFFSET OFS2
TS2: select getdate()
OFS2: select db_property('LastCommitRedoPos')
// restore the database to point in time TS1 / OFS1
// shut down the database
// start a utility server
RESTORE DATABASE 'iqdemo' FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL TIMESTAMP '<TS1>'
USING LOG PATH '/demo/pitrLog/' ,
OVERWRITE EXISTING
// or
RESTORE DATABASE 'iqdemo' FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL OFFSET <OFS1>

SAP IQ SQL Reference


SQL Statements INTERNAL 1615
USING LOG PATH '/demo/pitrLog/' OVERWRITE EXISTING

● Point-in-time recovery using point-in-time recovery logs and point-in-time recovery log backup archives:

// enable point-in-time recovery


SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON
ALTER DBSPACE IQ_SYSTEM_LOG RENAME '/demo/pitrLog/PITRLOG'
BACKUP DATABASE FULL to '/demo/dataBackup/FULL1'
// perform DDL / DML operations
CREATE TABLE T1 ( ID INT )
INSERT INTO T1 VALUES (1)
// record timestamp TS1 / OFFSET OFS1
TS1: select getdate()
OFS1: select db_property('LastCommitRedoPos')
// perform DDL / DML operations
CREATE TABLE T2 ( ID INT )
INSERT INTO T2 VALUES (1)
// record timestamp TS2 / OFFSET OFS2
TS2: select getdate()
OFS2: select db_property('LastCommitRedoPos')
// perform a PITR log backup
BACKUP DATABASE
POINT IN TIME RECOVERY LOGS ONLY TO '/demo/pitrLogBackup/PITR1'
// perform DDL/ DML operations
CREATE TABLE T3 ( ID INT )
INSERT INTO T3 VALUES (1)
// restore the database to point-in-time TS2 OR OFS2
// shutdown the database
// start a utility server
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL TIMESTAMP '<TS2>'
USING LOG PATH '/demo/pitrLogBackup/', '/demo/pitrLog/'
OVERWRITE EXISTING
// or
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL OFFSET <OFS2>
USING LOG PATH '/demo/pitrLogBackup/', '/demo/pitrLog/'
OVERWRITE EXISTING

● Point-in-time recovery on an RLV-enabled database with an incremental backup.

// perform a full database backup


BACKUP DATABASE FULL TO '/demo/dataBackup/FULL1'
// perform DDL / DML operations
CREATE TABLE T0 ( ID INT )
INSERT INTO T0 VALUES (1)
RECORD TIME STAMP TS0 / OFFSET OFS0
// enable point-in-time recovery using an incremental backup
SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON
ALTER DBSPACE IQ_SYSTEM_LOG RENAME '/demo/pitrLog/PITRLOG'
BACKUP DATABASE INCREMENTAL to '/demo/dataBackup/INCR1'
// perform DDL / DML operations
CREATE TABLE T1 ( ID INT )
INSERT INTO T1 VALUES (1)
// record timestamp TS1 / OFFSET OFS1
TS1: select getdate()
OFS1: select db_property('LastCommitRedoPos')
// perform DDL / DML operations
CREATE TABLE T2 ( ID INT )
INSERT INTO T2 VALUES (1)
// record timestamp TS2 / OFFSET OFS2
//perform a PITR log backup
BACKUP DATABASE
POINT IN TIME RECOVERY LOGS ONLY TO '/demo/pitrLogBackup/PITR1'
// note the RLV DBspace files and their location

SAP IQ SQL Reference


1616 INTERNAL SQL Statements
select * from sp_iqfile() where segmentType = 'RLV'"
// restore the database to point-in-time TS1 OR OFS1
// shutdown the database
// Do a physical file backup of all files in the RLV Dbspace.
// start a utility server
// Perform a restore of database from backup FULL1
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/FULL1'
OVERWRITE EXISTING
// restore the RLV Dbspace files from the backup taken above to its original
location
// perform a point-in-time recovery to time TS1 using incremental backup INCR1
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/INCR1'
RECOVER UNTIL TIMESTAMP '<TS1>'
USING LOG PATH '/demo/pitrLogBackup/PITR1/'
OVERWRITE EXISTING CLEAR LOG

● Point-in-time recovery on multiplex:

// enable point-in-time recovery


SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON
ALTER DBSPACE IQ_SYSTEM_LOG RENAME '/demo/pitrLog/PITRLOG'
// shut down all servers
// restart coordinator
// connect to coordinator and take a full backup
BACKUP DATABASE FULL to '/demo/dataBackup/FULL1'
// synchronize all secondary nodes & then start them
// perform DDL / DML operations in coordinator
// connect to coordinator
CREATE TABLE T1 ( ID INT );
INSERT INTO T1 VALUES (1);
COMMIT;
// record timestamp TS1 / OFFSET OFS1;
TS1: select getdate()
OFS1: select db_property('LastCommitRedoPos')
// perform DDL / DML operations on writers
// connect to Writer 2
CREATE TABLE T2 ( ID INT );
INSERT INTO T2 VALUES (1);
COMMIT;
// record timestamp TS2 / OFFSET OFS2;
TS2: select getdate()
OFS2: select db_property('LastCommitRedoPos')
// connect to writer3
INSERT INTO T1 VALUES(2);
INSERT INTO T2 VALUES(2);
COMMIT;
// record timestamp TS3 / OFFSET OFS3;
TS3: select getdate()
OFS3: select db_property('LastCommitRedoPos')
// perform a PITR log backup
BACKUP DATABASE
POINT IN TIME RECOVERY LOGS ONLY TO '/demo/pitrLogBackup/PITR1'
// perform DDL/ DML operations
// Connect to Writer3
CREATE TABLE T3 ( ID INT );
INSERT INTO T3 VALUES (1);
COMMIT;
// record timestamp ts4 / offset ofs4;
TS4: select getdate()
OFS4: select db_property('LastCommitRedoPos')
// restore the database to point-in-time TS3 OR OFS3
// shut down the database
// start a utility server and perform point-in-time
// recovery for the coordinator node

SAP IQ SQL Reference


SQL Statements INTERNAL 1617
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL TIMESTAMP '<TS3>'
USING LOG PATH '/demo/pitrLogBackup/', '/demo/pitrLog/'
OVERWRITE EXISTING
// or
RESTORE DATABASE 'iqdemo'
FROM '/demo/dataBackup/FULL1'
RECOVER UNTIL OFFSET <OFS3>
USING LOG PATH '/demo/pitrLogBackup/', '/demo/pitrLog/'
OVERWRITE EXISTING

● Re-enabling point-in-time recovery logging after a multiplex failover. In this scenario, writer 1 becomes the
coordinator after the failover:

// enable point-in-time recovery


SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON
ALTER DBSPACE IQ_SYSTEM_LOG RENAME '/demo/pitrLog/PITRLOG2'
// Shut down all servers
// Restart coordinator
BACKUP DATABASE FULL to '/demo/dataBackup/FULL1'
// Synchronize then start all secondary nodes

Related Information

BACKUP DATABASE Statement [page 1212]


REVOKE System Privilege Statement [page 1635]

9.4.154 RESUME Statement

Resumes execution of a procedure that returns result sets.

 Syntax

Syntax 1 – Supported in dbisqlc

RESUME <cursor-name>

Syntax 2 – Supported in dbisql

RESUME [ ALL ]

Parameters

cursor-name

Identifier or host-variable

SAP IQ SQL Reference


1618 INTERNAL SQL Statements
Remarks

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.

Syntax 1 – supported in dbisqlc but not dbisql (Interactive SQL) or when connected to the database using
the SAP SQL Anywhere JDBC driver.

Syntax 2 – supported in dbisql. Resumes the current procedure. If ALL is not specified, executing RESUME
displays the next result set or, if no more result sets are returned, completes the procedure. In dbisql, the
RESUME ALL statement cycles through all result sets in a procedure, without displaying them, and completes
the procedure. This is useful mainly in testing procedures.

The cursor must have been previously opened.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example shows embedded SQL:

EXEC SQL RESUME cur_employee;

EXEC SQL RESUME :cursor_var;

● The following example shows dbisql:

CALL sample_proc() ;
RESUME ALL;

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]

SAP IQ SQL Reference


SQL Statements INTERNAL 1619
REVOKE System Privilege Statement [page 1635]

9.4.155 RETURN Statement

Exits a function or procedure unconditionally, optionally providing a return value. Statements following RETURN
are not executed.

 Syntax

RETURN [ ( <expression> ) ]

Parameters

expression

If supplied, the value of <expression> is returned as the value of the function or procedure.

Within a function, the expression should be of the same data type as the RETURN data type of the function.

Remarks

RETURN is used in procedures for Transact-SQL-compatibility, and is used to return an integer error code.

Privileges

None

Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – Transact-SQL procedures use the RETURN statement to return an integer error
code.

SAP IQ SQL Reference


1620 INTERNAL SQL Statements
Examples

● The following example returns the product of three numbers:

CREATE FUNCTION product ( a numeric,


b numeric ,
c numeric)
RETURNS numeric
BEGIN
RETURN ( a * b * c ) ;
END

● The following example calculates the product of three numbers:

SELECT product (2, 3, 4)

product (2,3,4)
24

● The following example avoids executing a complex query, if it is meaningless:

Related Information

BEGIN … END Statement [page 1218]


CREATE PROCEDURE Statement [page 1321]
REVOKE System Privilege Statement [page 1635]

9.4.156 REVOKE CHANGE PASSWORD Privilege Statement

Removes the ability of a user to manage passwords and administer the system privilege.

 Syntax

REVOKE [ ADMIN OPTION FOR ] CHANGE PASSWORD


[ ( <target_user_list>
| ANY
| ANY WITH ROLES <target_role_list> ) ]
FROM <user_ID> [,...]

Parameters

target_user_list

Users the grantee has the potential to impersonate. The list must consist of existing users or user-
extended roles with login passwords. Separate the user_IDs in the list with commas.

SAP IQ SQL Reference


SQL Statements INTERNAL 1621
ANY

All database users with login passwords become potential target users to manage passwords for each
grantee.
ANY WITH ROLES target_role_list

List of target roles for each grantee. Any users who are granted any of the target roles become potential
target users for each grantee. The <target_role_list> must consist of existing roles and the users who
are granted said roles must consist of database users with login passwords. Use commas to separate
multiple user_IDs.
user_ID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Remarks

Depending on how the CHANGE PASSWORD system privilege was initially granted, using the ADMIN OPTION
FOR clause when revoking CHANGE PASSWORD has different results:

Clause Used When CHANGE PASSWORD was Originally Result When Using ADMIN OPTION FOR when revoking
Granted CHANGE PASSWORD

The WITH ADMIN OPTION clause Revokes only the ability to administer the CHANGE PASS­
WORD system privilege (that is, grant the system privilege to
another user) — the ability to actually manage passwords for
other users remains.

The WITH ADMIN ONLY OPTION clause Semantically equivalent to revoking the entire CHANGE
PASSWORD system privilege

The WITH NO ADMIN OPTION clause Nothing is revoked because there were no administrative
rights granted in the first place.

You can revoke the CHANGE PASSWORD system privilege from any combination of users and roles granted.

Privileges

Requires the CHANGE PASSWORD system privilege granted with administrative rights. See GRANT System
Privilege Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

SAP IQ SQL Reference


1622 INTERNAL SQL Statements
Examples

● The following example removes the ability of Joe to manage the passwords of Sally or Bob:

REVOKE CHANGE PASSWORD (Sally, Bob) FROM Joe

● The following example if the CHANGE PASSWORD system privilege was originally granted to Sam with the
WITH ADMIN OPTION clause, this example removes the ability of Sam to grant the CHANGE PASSWORD
system privilege to another user, but still allows Sam to manage passwords for those users specified in the
original GRANT CHANGE PASSWORD statement. However, if the CHANGE PASSWORD system privilege was
originally granted to Sam with the WITH ADMIN ONLY OPTION clause, this example removes all
permissions to the system privilege from Sam.

REVOKE ADMIN OPTION FOR CHANGE PASSWORD FROM Sam

Related Information

GRANT CHANGE PASSWORD Privilege Statement [page 1494]

9.4.157 REVOKE CONNECT Privilege Statement

Removes a user from the database.

 Syntax

REVOKE CONNECT
FROM <user_id> [,...]

Parameters

user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Remarks

Use system procedures or CREATE USER and DROP USER statements, not GRANT and REVOKE statements, to
add and remove user IDs.

SAP IQ SQL Reference


SQL Statements INTERNAL 1623
You cannot revoke the connect privileges from a user if he or she owns database objects, such as tables.
Attempting to do so with a REVOKE statement, or sp_droplogin or sp_iqdroplogin stored procedure
returns an error such as Cannot drop a user that owns tables in runtime system.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

 Note

If revoking CONNECT permissions or table permissions from another user, the target user cannot be
connected to the database.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

GRANT CONNECT Privilege Statement [page 1496]

9.4.158 REVOKE CREATE Privilege Statement

Removes CREATE privileges on the specified dbspace from the specified user IDs.

 Syntax

REVOKE CREATE ON <dbspace-name>


FROM <user_id> [,...]

Parameters

dbspace-name

Identifier.
user_id

SAP IQ SQL Reference


1624 INTERNAL SQL Statements
Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires the MANAGE ANY DBSPACE system privilege. See GRANT System Privilege Statement [page 1511]
for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example revokes the CREATE privilege on dbspace DspHist from user Smith:

REVOKE CREATE ON DspHist FROM Smith

● The following example revokes the CREATE privilege on dbspace DspHist from user ID fionat from the
database:

REVOKE CREATE ON DspHist FROM fionat

Related Information

GRANT CREATE Privilege Statement [page 1498]

9.4.159 REVOKE EXECUTE Privilege Statement

Removes EXECUTE permissions that were given using the GRANT statement.

 Syntax

REVOKE EXECUTE ON [ <owner>.]<procedure-name>


FROM <user_id> [,...]

SAP IQ SQL Reference


SQL Statements INTERNAL 1625
Parameters

user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires one of:

● You own the procedure


● MANAGE ANY OBJECT PRIVILEGE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – syntax is a Persistent Stored Module feature.


● SAP database products – supported by SAP Adaptive Server Enterprise. User management and security
models are different for SAP Adaptive Server Enterprise and SAP IQ.

Related Information

Revoking the Ability to Run a Privileged System Procedure [page 576]


GRANT EXECUTE Privilege Statement [page 1499]

9.4.160 REVOKE INTEGRATED LOGIN Statement

Removes the INTEGRATED LOGIN permissions that were given using the GRANT statement.

 Syntax

REVOKE INTEGRATED LOGIN


FROM <userID> [,...]

SAP IQ SQL Reference


1626 INTERNAL SQL Statements
Parameters

userID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

GRANT INTEGRATED LOGIN Statement [page 1500]

9.4.161 REVOKE KERBEROS LOGIN Statement

Removes KERBEROS LOGIN permissions that were given using the GRANT statement.

 Syntax

REVOKE KERBEROS LOGIN


FROM <userID> [,...]

Parameters

userID

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

SAP IQ SQL Reference


SQL Statements INTERNAL 1627
Privileges

Requires the MANAGE ANY USER system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

GRANT KERBEROS LOGIN Statement [page 1501]

9.4.162 REVOKE Object-Level Privilege Statement

Removes object-level privileges that were given using the GRANT statement.

 Syntax

REVOKE { <object-level-privilege> [,...]


[ <owner>.]<table-name>
<user_id> [,...]
<object-level-privilege> ::=
ALL [ PRIVILEGES ]
| ALTER
| DELETE
| INSERT
| LOAD
| REFERENCE [ ( <column-name> [, …] ) ]
| SELECT [ ( <column-name> [, …] ) ]
| TRUNCATE
| UPDATE [ ( <column-name>, …) ] }

Parameters

user_id

Must be the name of an existing user or immutable role. The list must consist of existing users with login
passwords. Separate the user_ids in the list with commas.
ALL

Grants all privileges to users


ALTER

SAP IQ SQL Reference


1628 INTERNAL SQL Statements
Users can alter this table with the ALTER TABLE statement. This privilege is not allowed for views.
DELETE

Users can delete rows from this table or view.


INSERT

Users can insert rows into the named table or view.


LOAD

Users can load data into the named table or view.


REFERENCES

Users can create indexes on the named tables, and foreign keys that reference the named tables. If column
names are specified, then users can reference only those columns. REFERENCES privileges on columns
cannot be granted for views, only for tables.
SELECT

Users can look at information in this view or table. If column names are specified, then the users can look
at only those columns. SELECT permissions on columns cannot be granted for views, only for tables.
TRUNCATE

Users can truncate the named table or view.


UPDATE

Users can update rows in this view or table. If column names are specified, users can update only those
columns. UPDATE privileges on columns cannot be granted for views, only for tables. To update a table,
users must have both SELECT and UPDATE privilege on the table.

Privileges

Requires one of:

● You own the table


● MANAGE ANY OBJECT PRIVILEGE system privilege granted with the GRANT OPTION clause

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – syntax is an entry-level feature.


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

● The following example prevents user Dave from inserting into the Employees table:

REVOKE INSERT ON Employees FROM Dave

SAP IQ SQL Reference


SQL Statements INTERNAL 1629
● The following example prevents user Dave from updating the Employees table:

REVOKE UPDATE ON Employees FROM Dave

Related Information

GRANT Object-Level Privilege Statement [page 1502]

9.4.163 REVOKE ROLE Statement

Removes a users membership in a role or his or her ability to administer the role.

 Syntax

Syntax 1 – Revokes System Roles

REVOKE ROLE <system-role>


FROM <grantee>, ...

<system-role> ::=
dboword translate="no">DIAGNOSTICS†††
| PUBLIC†††
| rs_systabgroup†††
| SA_DEBUG†††
| SYS†††
| SYS_REPLICATION_ADMIN_ROLE
| SYS_RUN_REPLICATION_ROLE
| SYS_SPATIAL_ADMIN_ROLE

<grantee> ::=
{ <system-role> | <user_id> }

†††The ADMIN OPTION FOR clause is not supported for system roles.
Syntax 2 – Revokes User-Defined Roles

REVOKE [ { EXERCISE | ADMIN } OPTION FOR ] ROLE <user-defined-role>


FROM <grantee>, ...

<grantee> ::=
{ <system-role> | <user_id> }

Syntax 3 – Revokes Compatibility Roles

REVOKE [ { EXERCISE | ADMIN } OPTION FOR ] ROLE <compatibility-role-name>


FROM <grantee>, ...

<compatibility-role-name> ::=
SYS_AUTH_BACKUP_ROLE
| SYS_AUTH_DBA_ROLE
| SYS_AUTH_PROFILE_ROLE
| SYS_AUTH_READCLIENTFILE_ROLE
| SYS_AUTH_READFILE_ROLE

SAP IQ SQL Reference


1630 INTERNAL SQL Statements
| SYS_AUTH_RESOURCE_ROLE
| SYS_AUTH_SA_ROLE
| SYS_AUTH_SSO_ROLE
| SYS_AUTH_VALIDATE_ROLE
| SYS_AUTH_WRITECLIENTFILE_ROLE
| SYS_AUTH_WRITEFILE_ROLE

<grantee> ::=
{ <system-role> | <user_id> }

Go to:

● Privileges
● Standards
● Examples

Parameters

(back to top)

role_name

Must already exist in the database. Separate multiple role names with commas.
user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.
{ EXERCISE | ADMIN } OPTION FOR

Specify the ADMIN OPTION FOR clause to revoke administration rights for the role, but leave exercise
rights. Specify the EXERCISE OPTION FOR clause to revoke exercise rights for the role, but leave
administration rights. If the clause is not specified, both rights are revoked.

Remarks

(back to top)

If a role that is being revoked was not granted to <grantee>, then the statement does nothing, and does not
return an error.

REVOKE ROLE fails with an error if, as a consequence of executing the statement, the number of
administrators for the role being revoked would fall below the required minimum as set by the min_role_admins
database option.

When revoking a role from the MANAGE ROLES system privilege, you must use the special internal
representation SYS_MANAGE_ROLES_ROLE. For example, REVOKE ROLE <role-name> FROM
SYS_MANAGE_ROLES_ROLE;.

The REVOKE syntax related to authorities, permissions, and groups used in pre-16.0 versions of the software is
still supported but deprecated.

SAP IQ SQL Reference


SQL Statements INTERNAL 1631
Privileges

(back to top)

To revoke the following roles requires the MANAGE ROLES system privilege. See GRANT System Privilege
Statement [page 1511] for assistance with granting privileges.

● diagnostics
● dbo
● PUBLIC
● rs_systabgroup
● SA_DEBUG
● SYS
● SYS_RUN_REPLICATE_ROLE
● SYS_SPATIAL_ADMIN_ROLE

To revoke the following compatibility role requires you be granted the specific compatibility role with
administrative privilege. See Grant Compatibility Roles in the SAP IQ Installation and Update Guide for your
platform for assistance in granting compatibility roles.

● SYS_AUTH_SA_ROLE
● SYS_AUTH_SSO_ROLE
● SYS_AUTH_DBA_ROLE
● SYS_AUTH_RESOURCE_ROLE
● SYS_AUTH_BACKUP_ROLE
● SYS_AUTH_VALIDATE_ROLE
● SYS_AUTH_WRITEFILE_ROLE
● SYS_AUTH_WRITEFILECLIENT_ROLE
● SYS_AUTH_READFILE_ROLE
● SYS_AUTH_READFILECLIENT_ROLE
● SYS_AUTH_PROFILE_ROLE
● SYS_AUTH_USER_ADMIN_ROLE
● SYS_AUTH_SPACE_ADMIN_ROLE
● SYS_AUTH_MULTIPLEX_ADMIN_ROLE
● SYS_AUTH_OPERATOR_ROLE
● SYS_AUTH_PERMS_ADMIN_ROLE
● <user-defined role name>

Standards

(back to top)

SQL – not in the ISO/ANSI SQL standard

SAP IQ SQL Reference


1632 INTERNAL SQL Statements
Examples

(back to top)

● The following example revokes the user-defined (standalone) role role1 from user1:

REVOKE ROLE role1 FROM user1

● After you execute this command, user1 no longer has the rights to perform any authorized tasks using
any system privileges granted to role1.
● The following example revokes the ability for user1 to administer the compatibility role
SYS_AUTH_WRITEFILE_ROLE:

REVOKE ADMIN OPTION FOR ROLE SYS_AUTH_WRITEFILE_ROLE FROM user1

user1 retains the ability to perform any authorized tasks granted by SYS_AUTH_WRITEFILE_ROLE.

Related Information

GRANT ROLE Statement [page 1504]

9.4.164 REVOKE SET USER Privilege Statement

Removes the ability for one user to impersonate another user and to administer the SET USER system
privilege.

 Syntax

REVOKE [ ADMIN OPTION FOR ] SETUSER


(<target_user_list>
| ANY
| ANY WITH ROLES <target_role_list> ] )
FROM <user_id> [,...]

Parameters

target_user_list

Must consist of existing users with login passwords and is the potential list of target users who can no
longer be impersonated by grantee users. Separate the user IDs in the list with commas.
ANY

The potential list of target users for each grantee consists of all database users with login passwords.
ANY WITH ROLES target_role_list

SAP IQ SQL Reference


SQL Statements INTERNAL 1633
The <target_role_list> must consist of existing roles, and the potential list of target users for each
grantee must consist of database users with login passwords that have a subset of roles in
<target_role_list>. Separate the list of roles with commas.
user_id

Each <user_id> must be the name of an existing user or immutable role. The list must consist of existing
users with login passwords. Separate the user_ids in the list with commas.

Remarks

Depending on how the SET USER system privilege was initially granted, using the ADMIN OPTION FOR clause
when revoking the SET USER system privilege has different results. If the SET USER system privilege was
originally granted with the WITH ADMIN OPTION clause, including the ADMIN OPTION FOR clause in the
revoke statement revokes only the ability to administer the SET USER system privilege (that is, grant the
system privilege to another user). The ability to actually impersonate another user remains. However, if the
SET USER system privilege was originally granted with the WITH ADMIN ONLY OPTION clause, including the
ADMIN OPTION FOR clause in the revoke statement is semantically equivalent to revoking the entire SET USER
system privilege. Finally, if the SET USER system privilege was originally grant with the WITH NO ADMIN
OPTION clause, and the ADMIN OPTION FOR clause is included in the revoke statement, nothing is revoked
because there were no administrative system privileges granted in the first place.

Privileges

Requires the SET USER system privilege granted with administrative rights. See GRANT System Privilege
Statement [page 1511] for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

● The following example stops Bob from being able to impersonate Sally or Bob:

REVOKE SET USER (Sally, Bob) FROM Bob

● The following example if the SET USER system privilege was originally granted to Sam with the WITH
ADMIN OPTION clause, this example removes the ability of Sam to grant the SET USER system privilege to
another user, but still allows Sam to impersonate those users already granted to him or her. However, if the

SAP IQ SQL Reference


1634 INTERNAL SQL Statements
SET USER system privilege was originally granted to Sam with the WITH ADMIN ONLY OPTION clause, this
example removes all permissions to the system privilege from Sam.

REVOKE ADMIN OPTION FOR SET USER FROM Sam

Related Information

GRANT SET USER Privilege Statement [page 1509]

9.4.165 REVOKE System Privilege Statement

Removes specific system privileges from specific users and the right to administer the privilege.

 Syntax

REVOKE [ ADMIN OPTION FOR ] <system_privilege_name> [,...]


FROM <user_id> [,...]

Parameters

ADMIN OPTION FOR

Each <system_privilege> must currently be granted to each <user_id> specified with administrative
privileges.

 Note

This clause revokes only the administrative privileges of the system privilege; the system privilege itself
remains granted. However, if the system privilege was originally granted with the WITH ADMIN ONLY
OPTION clause, the ADMIN OPTION FOR clause completely revokes the system privilege. Under this
scenario, use of the ADMIN OPTION FOR clause is not required to revoke administrative privileges.

system_privilege_name

Must be an existing system privilege.


user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

SAP IQ SQL Reference


SQL Statements INTERNAL 1635
Remarks

Depending on how the system privilege was initially granted, using the ADMIN OPTION FOR clause when
revoking a system privilege has different results. If the system privilege was originally granted with the WITH
ADMIN OPTION clause, including the ADMIN OPTION FOR clause in the revoke statement revokes only the
ability to administer the system privilege (that is, grant the system privilege to another user). The ability to
actually use the system privilege remains. However, if the system privilege was originally granted with the WITH
ADMIN ONLY OPTION clause, including the ADMIN OPTION FOR clause in the revoke statement is semantically
equivalent to revoking the entire system privilege.

Finally, if the system privilege was originally grant with the WITH NO ADMIN OPTION clause, and the ADMIN
OPTION FOR clause is included in the revoke statement, nothing is revoked because there were no
administrative system privileges granted in the first place.

Privileges

Requires administrative privilege over the system privilege being revoked. See GRANT System Privilege
Statement [page 1511] for assistance with granting privileges.

Standards

● SQL – other syntaxes are vendor extensions to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise

Examples

● The following example revokes the BACKUP DATABASE system privilege from user Jim:

REVOKE BACKUP DATABASE FROM Jim

● In the following example, assuming the BACKUP DATABASE system privilege was originally granted to user
Jim with the WITH ADMIN OPTION clause, this example revokes the ability to administer the BACKUP
DATABASE system privilege from user Jim:

REVOKE ADMIN OPTION FOR BACKUP DATABASE FROM Jim

The ability to perform tasks authorized by the system privilege remains. However, if the BACKUP
DATABASE system privilege was originally granted to user Jim with the WITH ADMIN ONLY OPTION
clause, this example removes all permissions to the system privilege from user Jim.

In this section:

Alphabetical List of System Privileges for REVOKE [page 1637]


A list of all system privileges.

SAP IQ SQL Reference


1636 INTERNAL SQL Statements
System Privileges for REVOKE Listed by Functional Area [page 1645]
A list of system privileges organized by functional area.

Related Information

Revoking the Ability to Run a Privileged System Procedure [page 576]


GRANT System Privilege Statement [page 1511]
GRANT USAGE ON SEQUENCE Privilege Statement [page 1528]
GRANT SET USER Privilege Statement [page 1509]
PREFETCH_FP_PERCENT Option [page 1953]
Set a Database Option [page 1727]
PREFETCH_HASH_PERCENT Option [page 1955]
Set a Database Option [page 1727]
PREFETCH_LOB_PERCENT Option [page 1956]
Set a Database Option [page 1727]
PREFETCH_TEXTPOST_PERCENT Option [page 1958]
Set a Database Option [page 1727]

9.4.165.1 Alphabetical List of System Privileges for REVOKE

A list of all system privileges.

System privileges control the rights of users to perform authorized database tasks.

The following is a list of available system privileges:

System Privilege Description Functional Area

ACCESS SERVER LS Allows logical server connection using the SERVER logical server Multiplex
context.

ACCESS USER PASSWORD Allows a user to access views that contain password hashes, and User and Login Man­
perform operations that involve accessing passwords, such as un­ agement
loading, extracting, or comparing database

ALTER ANY INDEX Allows a user to alter and comment on indexes and text indexes Indexes
on tables and views owned by any user.

ALTER ANY MATERIALIZED Allows a user to alter and comment on materialized views owned Materialized Views
VIEW by any user.

SAP IQ SQL Reference


SQL Statements INTERNAL 1637
System Privilege Description Functional Area

ALTER ANY OBJECT Allows a user to alter and comment on the following types of ob­ Objects
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

ALTER ANY OBJECT OWNER Allows a user to alter the owner of any type of table object. This Objects
privilege does not allow changing of the owner of other objects,
such as procedures, materialized views, and so on.

ALTER ANY PROCEDURE Allows a user to alter and comment on procedures and functions Procedures
owned by any user.

ALTER ANY SEQUENCE Allows a user to alter sequence generators owned by any user. Sequence

ALTER ANY TABLE Allows a user to: Tables

● Alter and comment on tables (including proxy tables) owned


by any user.
● Truncate tables, table partitions, or views owned by any user
● Comment on tables (including proxy tables) and columns in
tables owned by any user.

ALTER ANY TEXT CONFIGURA­ Allows a user to alter and comment on text configuration objects Text Configuration
TION owned by any user.

ALTER ANY TRIGGER Allows a user to: Triggers

● Alter triggers on tables and views.


● Issue comments on tables (also requires the ALTER object-
level privilege on the table).

ALTER ANY VIEW Allows a user to alter and comment on views owned by any user. Views

SAP IQ SQL Reference


1638 INTERNAL SQL Statements
System Privilege Description Functional Area

ALTER DATABASE Allows a user to: Database

● Upgrade a database.
● Perform cost model calibration.
● Load database statistics.
● Alter transaction logs (also requires the SERVER OPERATOR
system privilege).
● Change ownership of the database (also requires the MAN­
AGE ANY MIRROR SERVER system privilege).

ALTER DATATYPE Allows a user to alter data types. Data Type

BACKUP DATABASE Allows a user to back up a database. Database

CHANGE PASSWORD Allows a user to manage user passwords for any user. User and Login Man­
agement
This system privilege can apply to all users, or it can be limited to
a set of specified users, or users who are granted one or more
specified roles.

This system privilege is not required to change a user's own pass­


word.

CHECKPOINT Allows a user to force the database server to execute a check­ Database
point.

COMMENT ANY OBJECT Allows a user to comment on any type of object owned by any Objects
user that can be created using the CREATE ANY OBJECT system
privilege.

CREATE ANY INDEX Allows a user to create and comment on indexes and text indexes Indexes
on tables and views owned by any user.

CREATE ANY MATERIALIZED Allows a user to create and comment on materialized views Materialized Views
VIEW owned by any user.

CREATE ANY MUTEX SEMA­ Allows a user to create a mutex or semaphore owned by any user. Mutex and Sema­
PHORE phores

SAP IQ SQL Reference


SQL Statements INTERNAL 1639
System Privilege Description Functional Area

CREATE ANY OBJECT Allows a user to create and comment on the following types of ob­ Objects
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

CREATE ANY PROCEDURE Allows a user to create and comment on procedures and func­ Procedure
tions owned by any user.

CREATE ANY SEQUENCE Allows a user to create sequence generators, regardless of owner. Sequence

CREATE ANY TABLE Allows a user to: Table

● Create and comment on tables (including proxy tables)


owned by any user.
● Comment on columns in tables (including proxy tables)
owned by any user.

CREATE ANY TEXT CONFIGU­ Allows a user to alter and comment on text configuration objects Text Configuration
RATION owned by any user.

CREATE ANY TRIGGER Allows a user to create and comment (also requires the ALTER Triggers
object level privilege on the table) on tables and views.

CREATE ANY VIEW Allows a user to create and comment on views owned by any user. Views

CREATE DATABASE VARIABLE Allows a user to create, select from, update, and drop self-owned Database Variables
database-scope variables.

CREATE DATATYPE Allows a user to create data types. Database

CREATE EXTERNAL REFER­ Allows a user to create external references in the database. External Environment
ENCE
You must have the system privileges required to create specific
database objects before you can create external references.

For example, creating a self-owned text configuration object that


uses an external term breaker requires both the CREATE TEXT
CONFIGURATION and CREATE EXTERNAL REFERENCE system
privileges.

CREATE MATERIALIZED VIEW Allows a user to create and comment on self-owned materialized Materialized Views
views.

SAP IQ SQL Reference


1640 INTERNAL SQL Statements
System Privilege Description Functional Area

CREATE MESSAGE Allows a user to create messages. Miscellaneous

CREATE PROCEDURE Allows a user to create and comment on self-owned procedures Procedure
and functions. create a self-owned stored procedure or function.

CREATE PROXY TABLE Allows a user to create self-owned proxy tables. Table

CREATE TABLE Allows a user to: Table

● Create self-owned tables.


● Comment on self-owned columns and tables.

CREATE TEXT CONFIGURA­ Allows a user to create and comment on self-owned text configu- Text Configuration
TION ration objects.

CREATE VIEW Allows a user to create and comment on self-owned views. Re­ Views
quired to create self-owned views.

DEBUG ANY PROCEDURE Allows a user to debug any database object. Miscellaneous

DELETE ANY TABLE Allows a user to delete rows in tables and views owned by any Table
user.

DROP ANY INDEX Allows a user to drop indexes and text indexes on tables and views Indexes
owned by any user.

DROP ANY MATERIALIZED Allows a user to drop materialized views owned by any user. Materialized View
VIEW

DROP ANY MUTEX SEMA­ Allows a user to drop a mutex or semaphore owned by any user. Mutex and Sema­
PHORE phores

DROP ANY OBJECT Allows a user to drop the following types of objects owned by any Objects
user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

DROP ANY PROCEDURE Allows a user to drop procedures and functions owned by any Procedure
user.

DROP ANY SEQUENCE Allows a user to drop sequence generators owned by any user. Sequence

SAP IQ SQL Reference


SQL Statements INTERNAL 1641
System Privilege Description Functional Area

DROP ANY TABLE Allows a user to drop tables (including proxy tables) owned by any Table
user.

DROP ANY TEXT CONFIGURA­ Allows a user to drop text configuration objects owned by any Text Configuration
TION user.

DROP ANY VIEW Allows a user to drop views owned by any user. Views

DROP CONNECTION Allows a user to drop any connections to the database. Database

DROP DATATYPE Allows a user to drop data types. Database

DROP MESSAGE Allows a user to drop messages. Miscellaneous

EXECUTE ANY PROCEDURE Allows a user to execute procedures and functions owned by any Procedure
user.

INSERT ANY TABLE Allows a user to insert rows into tables and views owned by any Table
user.

LOAD ANY TABLE Allows a user to load data into tables owned by any user. Table

MANAGE ANY DATABASE VARI­ Allows a user to create and drop database-scope variables owned Database Variables
ABLE by self or by PUBLIC.

MANAGE ANY DBSPACE Allows a user to: Dbspaces

● Create, alter, drop, and comment on dbspaces.


● Grant and revoke CREATE object-level privileges on dbspa­
ces.
● Move data to any dbspace.
● Issue a read-only selective restore statement on any
dbspace.
● Run the database delete file function.

MANAGE ANY EVENT Allows a user to create, alter, drop, trigger, and comment on Miscellaneous
events.

MANAGE ANY EXTERNAL EN­ Allows a user to alter, comment on, start, and stop external envi­ External Environment
VIRONMENT ronments.

MANAGE ANY EXTERNAL OB­ Allows a user to install, comment on, and remove external envi­ External Environment
JECT ronment objects.

MANAGE ANY LDAP SERVER Allows a user to create, alter, drop, validate, and comment on Miscellaneous
LDAP servers.

MANAGE ANY LOGIN POLICY Allows a user to create, alter, drop, and comment on login poli­ User and Login Man­
cies. agement

MANAGE ANY MIRROR Allows a user to: Miscellaneous


SERVER
● Create, alter, drop, and comment on mirror servers.
● Change mirror server parameters.
● Set mirror server options.
● Change ownership of a database.

SAP IQ SQL Reference


1642 INTERNAL SQL Statements
System Privilege Description Functional Area

MANAGE ANY OBJECT PRIVI­ Allows a user to: Objects


LEGES
● Grant and revoke SELECT, INSERT, DELETE, UPDATE, AL­
TER, REFERENCES, LOAD, and TRUNCATE object-level privi­
leges on tables owned by any user.
● Grant and revoke SELECT, INSERT, DELETE, and UPDATE ob­
ject-level privileges on views owned by any user.
● Grant and revoke EXECUTE privileges on procedures and
functions owned by any user.
● Grant and revoke USAGE object-level privileges on sequence
generators owned by any user.
● Grant and revoke CREATE object-level privileges on dbspa­
ces.

MANAGE ANY PROPERTY HIS­ Allows a user to turn on and configure the tracking of database Server Operator
TORY server property values.

MANAGE ANY SPATIAL OB­ Allows a user to create, alter, drop, and comment on spatial refer­ Miscellaneous
JECT ence systems and spatial unit of measures.

MANAGE ANY STATISTICS Allows a user to create, alter, drop, and update database statistics Miscellaneous
for any table.

MANAGE ANY USER Allows a user to: User and Login Man­
agement
● Create, alter, drop, and comment on database users (includ­
ing assigning an initial password).
● Force a password change on next login for any user.
● Assign and reset the login policy for any user.
● Create, drop, and comment on integrated logins and Ker­
beros logins.
● Create and drop external logins.

MANAGE ANY WEB SERVICE Allows a user to create, alter, drop, and comment on web serv­ Miscellaneous
ices.

MANAGE AUDITING Allows a user to run the sa_audit_string stored procedure. Procedure

MANAGE LISTENERS Allows a user to start and stop network listeners. Server Operator

MANAGE MULTIPLEX Allows users to: Multiplex

● Create, alter, drop, or comment on logical servers and logical


server policies.
● Assign a dbspace to logical servers.
● Release a populated dbspace from the exclusive use of a logi­
cal server.
● Manages failover configurations, and perform a manual fail­
over.

MANAGE PROFILING Allows a user to manage database server tracing. The DIAGNOS­ Database
TICS system role is also required to fully utilize diagnostics func­
tionality for user information.

SAP IQ SQL Reference


SQL Statements INTERNAL 1643
System Privilege Description Functional Area

MANAGE ROLES Allows a user to create new roles and act as a global administrator Roles
for new and existing roles. By default, MANAGE ROLES is granted
administrative rights on each newly created role. A user requires
administrative rights on the role to delete it.

Administration of a role can also be granted directly to users ei­


ther during or after the creation of the role. When granted directly
to a user, the user does not require the MANAGE ROLES system
privilege to administer the role.

If no role administrator is specified during role creation, the MAN­


AGE ROLES system privilege is automatically granted to the role
with the ADMIN ONLY OPTION clause, allowing the global role ad­
ministrator to administer the role. If at least one role administra­
tor is specified during creation, the MANAGE ROLES system privi­
lege is not granted to the role, and global role administrators can­
not manage the role.

MONITOR Allows a user to monitor a database, including accessing privi­ Database


leged statistics, connected users, and locks.

READ CLIENT FILE Allows a user to read files on the client computer. Files

READ FILE Allows a user to read files on the database server computer. Files

REORGANIZE ANY OBJECT Allows a user to reorganize tables and materialized views owned Objects
by any user.

SELECT ANY TABLE Allows a user to query tables and views owned by any user. Table

SELECT PUBLIC DATABASE Allows a user to select the value of a database-scope variable Database Variables
VARIABLE owned by PUBLIC.

SERVER OPERATOR Allows a user to: Server Operator

● Create, drop, change ownership of a database, and restore


the catalog (only).
● Create, alter, and drop a server.
● Manage a server cache.
● Start and stop database or database engine.
● Encrypt databases.
● Change a database transaction log.

SET ANY PUBLIC OPTION Allows a user to set PUBLIC database options that do not require Database Options
the SET ANY SECURITY OPTION or the SET ANY SYSTEM OP­
TION system privileges.

SET ANY SECURITY OPTION Allows a user to set any PUBLIC security database options. Database Options

SET ANY SYSTEM OPTION Allows a user to set PUBLIC system database options. Database Options

SET ANY USER DEFINED OP­ Allows a user to set user-defined database options. Database Options
TION

SAP IQ SQL Reference


1644 INTERNAL SQL Statements
System Privilege Description Functional Area

SET USER (granted with admin­ Allows a user to temporarily assume the roles and privileges of User and Login Man­
istrative rights only) another user. agement

This system privilege can apply to all users, or can be limited to a


set of specified users, or users who are granted one or more
specified roles.

TRUNCATE ANY TABLE Allows a user to truncate data for tables and materialized views Table
owned by any user.

UPDATE ANY MUTEX SEMA­ Allows a user to update a mutex or semaphore owned by any Mutex and Sema­
PHORE user. phores

UPDATE ANY TABLE Allows a user to update rows in tables and views owned by any Table
user.

UPDATE PUBLIC DATABASE Allows a user to update database-scope variables owned by PUB­ Database Variables
VARIABLE LIC.

UPGRADE ROLE Allows a user to be a default administrator of any system privilege Roles
that is introduced when upgrading an SAP IQ database from ver­
sion 16.0. By default, the UPGRADE ROLE system privilege is
granted to the SYS_AUTH_SA_ROLE role, if it exists.

USE ANY SEQUENCE Allows a user to use sequence generators owned by any user. Sequence

VALIDATE ANY OBJECT Allows a user to validate tables, materialized views, indexes, and Objects
text indexes owned by any user.

WRITE CLIENT FILE Allows a user to write files to the client computer. Files

WRITE FILE Allows a user to write files on the database server computer. Files

9.4.165.2 System Privileges for REVOKE Listed by Functional


Area

A list of system privileges organized by functional area.

Functional Area System Privilege Description

Database Options SET ANY PUBLIC OPTION Allows a user to set PUBLIC database options that do not require
the SET ANY SECURITY OPTION or the SET ANY SYSTEM OP­
TION system privileges.

SET ANY SECURITY OPTION Allows a user to set any PUBLIC security database options.

SET ANY SYSTEM OPTION Allows a user to set PUBLIC system database options.

SET ANY USER DEFINED OP­ Allows a user to set user-defined database options.
TION

Database Variables CREATE DATABASE VARIABLE Allows a user to create, select from, update, and drop self-owned
database-scope variables.

MANAGE ANY DATABASE VARI­ Allows a user to create and drop database-scope variables owned
ABLE by self or by PUBLIC.

SAP IQ SQL Reference


SQL Statements INTERNAL 1645
Functional Area System Privilege Description

SELECT PUBLIC DATABASE Allows a user to select the value of a database-scope variable
VARIABLE owned by PUBLIC.

UPDATE PUBLIC DATABASE Allows a user to update database-scope variables owned by PUB­
VARIABLE LIC.

Database CHECKPOINT Allows a user to force the database server to execute a check­
point.

DROP DATATYPE Allows a user to drop data types.

MANAGE PROFILING Allows a user to manage database server tracing. The DIAGNOS­
TICS system role is also required to fully utilize diagnostics func­
tionality for user information.

MONITOR Allows a user to monitor a database, including accessing privi­


leged statistics, connected users, and locks.

ALTER DATABASE Allows a user to:

● Upgrade a database.
● Perform cost model calibration.
● Load database statistics.
● Alter transaction logs (also requires the SERVER OPERATOR
system privilege).
● Change ownership of the database (also requires the MAN­
AGE ANY MIRROR SERVER system privilege).

BACKUP DATABASE Allows a user to back up a database.

CREATE DATATYPE Allows a user to create data types.

DROP CONNECTION Allows a user to drop any connections to the database.

MANAGE ANY DBSPACE Allows a user to:

● Create, alter, drop, and comment on dbspaces.


● Grant and revoke CREATE object-level privileges on dbspa­
ces.
● Move data to any dbspace.
● Issue a read-only selective restore statement on any
dbspace.
● Run the database delete file function.

External Environment CREATE EXTERNAL REFER­ Allows a user to create external references in the database.
ENCE
You must have the system privileges required to create specific
database objects before you can create external references.

For example, creating a self-owned text configuration object that


uses an external term breaker requires both the CREATE TEXT
CONFIGURATION and CREATE EXTERNAL REFERENCE system
privileges.

MANAGE ANY EXTERNAL EN­ Allows a user to alter, comment on, start, and stop external envi­
VIRONMENT ronments.

MANAGE ANY EXTERNAL OB­ Allows a user to install, comment on, and remove external envi­
JECT ronment objects.

SAP IQ SQL Reference


1646 INTERNAL SQL Statements
Functional Area System Privilege Description

Files READ CLIENT FILE Allows a user to read files on the client computer.

READ FILE Allows a user to read files on the database server computer.

WRITE CLIENT FILE Allows a user to write files to the client computer.

WRITE FILE Allows a user to write files on the database server computer.

Indexes ALTER ANY INDEX Allows a user to alter and comment on indexes and text indexes
on tables and views owned by any user.

CREATE ANY INDEX Allows a user to create and comment on indexes and text indexes
on tables and views owned by any user.

DROP ANY INDEX Allows a user to drop indexes and text indexes on tables and views
owned by any user.

Materialized View DROP ANY MATERIALIZED Allows a user to drop materialized views owned by any user.
VIEW

ALTER ANY MATERIALIZED Allows a user to alter and comment on materialized views owned
VIEW by any user.

CREATE ANY MATERIALIZED Allows a user to create and comment on materialized views
VIEW owned by any user.

CREATE MATERIALIZED VIEW Allows a user to create and comment on self-owned materialized
views.

Miscellaneous ALTER DATATYPE Allows a user to alter data types.

CREATE MESSAGE Allows a user to create messages.

DEBUG ANY PROCEDURE Allows a user to debug any database object.

DROP MESSAGE Allows a user to drop messages.

MANAGE ANY EVENT Allows a user to create, alter, drop, trigger, and comment on
events.

MANAGE ANY LDAP SERVER Allows a user to create, alter, drop, validate, and comment on
LDAP servers.

MANAGE ANY MIRROR Allows a user to:


SERVER
● Create, alter, drop, and comment on mirror servers.
● Change mirror server parameters.
● Set mirror server options.
● Change ownership of a database.

MANAGE ANY SPATIAL OB­ Allows a user to create, alter, drop, and comment on spatial refer­
JECT ence systems and spatial unit of measures.

MANAGE ANY STATISTICS Allows a user to create, alter, drop, and update database statistics
for any table.

MANAGE ANY WEB SERVICE Allows a user to create, alter, drop, and comment on web serv­
ices.

Multiplex ACCESS SERVER LS Allows logical server connection using the SERVER logical server
context.

SAP IQ SQL Reference


SQL Statements INTERNAL 1647
Functional Area System Privilege Description

MANAGE MULTIPLEX Allows users to:

● Create, alter, drop, or comment on logical servers and logical


server policies.
● Assign a dbspace to logical servers.
● Release a populated dbspace from the exclusive use of a logi­
cal server.
● Manages failover configurations, and perform a manual fail­
over.

Mutex and Sema­ CREATE ANY MUTEX SEMA­ Allows a user to create a mutex or semaphore owned by any user.
phores PHORE

DROP ANY MUTEX SEMA­ Allows a user to drop a mutex or semaphore owned by any user.
PHORE

UPDATE ANY MUTEX SEMA­ Allows a user to update a mutex or semaphore owned by any
PHORE user.

Objects ALTER ANY OBJECT OWNER Allows a user to alter the owner of any type of table object. This
privilege does not allow changing of the owner of other objects,
such as procedures, materialized views, and so on.

ALTER ANY OBJECT Allows a user to alter and comment on the following types of ob­
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

COMMENT ANY OBJECT Allows a user to comment on any type of object owned by any
user that can be created using the CREATE ANY OBJECT system
privilege.

SAP IQ SQL Reference


1648 INTERNAL SQL Statements
Functional Area System Privilege Description

CREATE ANY OBJECT Allows a user to create and comment on the following types of ob­
jects owned by any user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

DROP ANY OBJECT Allows a user to drop the following types of objects owned by any
user:

● Data types
● Events
● Functions
● Indexes
● Materialized views
● Messages
● Procedures
● Sequence generators
● Spatial reference systems
● Spatial units of measure
● Statistics
● Tables
● Text configuration objects
● Text indexes
● Triggers
● Views

SAP IQ SQL Reference


SQL Statements INTERNAL 1649
Functional Area System Privilege Description

MANAGE ANY OBJECT PRIVI­ Allows a user to:


LEGES
● Grant and revoke SELECT, INSERT, DELETE, UPDATE, AL­
TER, REFERENCES, LOAD, and TRUNCATE object-level privi­
leges on tables owned by any user.
● Grant and revoke SELECT, INSERT, DELETE, and UPDATE ob­
ject-level privileges on views owned by any user.
● Grant and revoke EXECUTE privileges on procedures and
functions owned by any user.
● Grant and revoke USAGE object-level privileges on sequence
generators owned by any user.
● Grant and revoke CREATE object-level privileges on dbspa­
ces.

REORGANIZE ANY OBJECT Allows a user to reorganize tables and materialized views owned
by any user.

VALIDATE ANY OBJECT Allows a user to validate tables, materialized views, indexes, and
text indexes owned by any user.

Procedures ALTER ANY PROCEDURE Allows a user to alter and comment on procedures and functions
owned by any user.

CREATE ANY PROCEDURE Allows a user to create and comment on procedures and func­
tions owned by any user.

CREATE PROCEDURE Allows a user to create and comment on self-owned procedures


and functions. create a self-owned stored procedure or function.

DROP ANY PROCEDURE Allows a user to drop procedures and functions owned by any
user.

EXECUTE ANY PROCEDURE Allows a user to execute procedures and functions owned by any
user.

MANAGE AUDITING Allows a user to run the sa_audit_string stored procedure.

Roles MANAGE ROLES Allows a user to create new roles and act as a global administrator
for new and existing roles. By default, MANAGE ROLES is granted
administrative rights on each newly created role. A user requires
administrative rights on the role to delete it.

Administration of a role can also be granted directly to users ei­


ther during or after the creation of the role. When granted directly
to a user, the user does not require the MANAGE ROLES system
privilege to administer the role.

If no role administrator is specified during role creation, the MAN­


AGE ROLES system privilege is automatically granted to the role
with the ADMIN ONLY OPTION clause, allowing the global role ad­
ministrator to administer the role. If at least one role administra­
tor is specified during creation, the MANAGE ROLES system privi­
lege is not granted to the role, and global role administrators can­
not manage the role.

SAP IQ SQL Reference


1650 INTERNAL SQL Statements
Functional Area System Privilege Description

UPGRADE ROLE Allows a user to be a default administrator of any system privilege


that is introduced when upgrading an SAP IQ database from ver­
sion 16.0. By default, the UPGRADE ROLE system privilege is
granted to the SYS_AUTH_SA_ROLE role, if it exists.

Sequence ALTER ANY SEQUENCE Allows a user to alter sequence generators owned by any user.

CREATE ANY SEQUENCE Allows a user to create sequence generators, regardless of owner.

DROP ANY SEQUENCE Allows a user to drop sequence generators owned by any user.

USE ANY SEQUENCE Allows a user to use sequence generators owned by any user.

Server Operator MANAGE ANY PROPERTY HIS­ Allows a user to turn on and configure the tracking of database
TORY server property values.

MANAGE LISTENERS Allows a user to start and stop network listeners.

SERVER OPERATOR Allows a user to:

● Create, drop, change ownership of a database, and restore


the catalog (only).
● Create, alter, and drop a server.
● Manage a server cache.
● Start and stop database or database engine.
● Encrypt databases.
● Change a database transaction log.

Table CREATE PROXY TABLE Allows a user to create self-owned proxy tables.

CREATE TABLE Allows a user to:

● Create self-owned tables.


● Comment on self-owned columns and tables.

DELETE ANY TABLE Allows a user to delete rows in tables and views owned by any
user.

DROP ANY TABLE Allows a user to drop tables (including proxy tables) owned by any
user.

INSERT ANY TABLE Allows a user to insert rows into tables and views owned by any
user.

LOAD ANY TABLE Allows a user to load data into tables owned by any user.

SELECT ANY TABLE Allows a user to query tables and views owned by any user.

TRUNCATE ANY TABLE Allows a user to truncate data for tables and materialized views
owned by any user.

UPDATE ANY TABLE Allows a user to update rows in tables and views owned by any
user.

CREATE ANY TABLE Allows a user to:

● Create and comment on tables (including proxy tables)


owned by any user.
● Comment on columns in tables (including proxy tables)
owned by any user.

SAP IQ SQL Reference


SQL Statements INTERNAL 1651
Functional Area System Privilege Description

ALTER ANY TABLE Allows a user to:

● Alter and comment on tables (including proxy tables) owned


by any user.
● Truncate tables, table partitions, or views owned by any user
● Comment on tables (including proxy tables) and columns in
tables owned by any user.

Text Configuration ALTER ANY TEXT CONFIGURA­ Allows a user to alter and comment on text configuration objects
TION owned by any user.

CREATE TEXT CONFIGURA­ Allows a user to create and comment on self-owned text configu-
TION ration objects.

DROP ANY TEXT CONFIGURA­ Allows a user to drop text configuration objects owned by any
TION user.

CREATE ANY TEXT CONFIGU­ Allows a user to alter and comment on text configuration objects
RATION owned by any user.

Triggers ALTER ANY TRIGGER Allows a user to:

● Alter triggers on tables and views.


● Issue comments on tables (also requires the ALTER object-
level privilege on the table).

CREATE ANY TRIGGER Allows a user to create and comment (also requires the ALTER
object level privilege on the table) on tables and views.

ACCESS USER PASSWORD Allows a user to access views that contain password hashes, and
perform operations that involve accessing passwords, such as un­
loading, extracting, or comparing database

CHANGE PASSWORD Allows a user to manage user passwords for any user.

This system privilege can apply to all users, or it can be limited to


a set of specified users, or users who are granted one or more
specified roles.

This system privilege is not required to change a user's own pass­


word.

MANAGE ANY LOGIN POLICY Allows a user to create, alter, drop, and comment on login poli­
cies.

MANAGE ANY USER Allows a user to:

● Create, alter, drop, and comment on database users (includ­


ing assigning an initial password).
● Force a password change on next login for any user.
● Assign and reset the login policy for any user.
● Create, drop, and comment on integrated logins and Ker­
beros logins.
● Create and drop external logins.

SAP IQ SQL Reference


1652 INTERNAL SQL Statements
Functional Area System Privilege Description

SET USER (granted with admin­ Allows a user to temporarily assume the roles and privileges of
istrative rights only) another user.

This system privilege can apply to all users, or can be limited to a


set of specified users, or users who are granted one or more
specified roles.

Views ALTER ANY VIEW Allows a user to alter and comment on views owned by any user.

CREATE ANY VIEW Allows a user to create and comment on views owned by any user.

CREATE VIEW Allows a user to create and comment on self-owned views. Re­
quired to create self-owned views.

DROP ANY VIEW Allows a user to drop views owned by any user.

9.4.166 REVOKE USAGE ON SEQUENCE Privilege Statement

Removes USAGE privilege on a specified sequence.

 Syntax

REVOKE USAGE ON SEQUENCE <sequence-name>


FROM <user_id> [,...]

Parameters

user_id

Must be the name of an existing user or role that has a login password. Separate multiple user_IDs with
commas.

Privileges

Requires one of:

● You own the sequence.


● MANAGE ANY OBJECT PRIVILEGE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

SAP IQ SQL Reference


SQL Statements INTERNAL 1653
Standards

● SQL – syntax is a Persistent Stored Module feature.


● SAP database products – the security model is different in SAP Adaptive Server Enterprise and SAP IQ, so
other syntaxes differ.

Related Information

GRANT USAGE ON SEQUENCE Privilege Statement [page 1528]


GRANT USAGE ON SEQUENCE Privilege Statement [page 1528]

9.4.167 ROLLBACK Statement

Undoes any changes made since the last COMMIT or ROLLBACK.

 Syntax

ROLLBACK [ WORK ]

Remarks

ROLLBACK ends a logical unit of work (transaction) and undoes all changes made to the database during this
transaction. A transaction is the database work done between COMMIT or ROLLBACK statements on one
database connection.

Privileges

None

Side Effects

● Closes all cursors not opened WITH HOLD.


● Releases locks held by the transaction issuing the ROLLBACK.

SAP IQ SQL Reference


1654 INTERNAL SQL Statements
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise

Related Information

COMMIT Statement [page 1238]


ROLLBACK TO SAVEPOINT Statement [page 1655]
REVOKE System Privilege Statement [page 1635]

9.4.168 ROLLBACK TO SAVEPOINT Statement

Cancels any changes made since a savepoint was established. Changes made prior to the savepoint are not
undone; they are still pending.

 Syntax

ROLLBACK TO SAVEPOINT [ <savepoint-name> ]

Parameters

savepoint-name

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.

Remarks

There must have been a corresponding SAVEPOINT within the current transaction.

Privileges

None

SAP IQ SQL Reference


SQL Statements INTERNAL 1655
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. To implement similar features
in an SAP ASE-compatible manner, you can use nested transactions.

Related Information

RELEASE SAVEPOINT Statement [page 1604]


ROLLBACK Statement [page 1654]
SAVEPOINT Statement [page 1658]
REVOKE System Privilege Statement [page 1635]

9.4.169 ROLLBACK TRANSACTION Statement [T-SQL]

Cancels any changes made since a savepoint was established using SAVE TRANSACTION. Changes made prior
to the SAVE TRANSACTION are not undone; they are still pending.

 Syntax

ROLLBACK TRANSACTION [ <savepoint-name> ]

Parameters

savepoint-name

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.

Remarks

There must be a corresponding SAVE TRANSACTION within the current transaction.

Privileges

None

SAP IQ SQL Reference


1656 INTERNAL SQL Statements
Standards

SQL – vendor extension to ISO/ANSI SQL grammar

Examples

The following example returns 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 )
SAVE TRANSACTION before_delete
UPDATE #tmp SET row_num=row_num*10
DELETE FROM #tmp WHERE row_num >= 3
ROLLBACK TRANSACTION before_delete
SELECT * FROM #tmp
END

Related Information

BEGIN TRANSACTION Statement [T-SQL] [page 1223]


SAVE TRANSACTION Statement [T-SQL] [page 1657]
REVOKE System Privilege Statement [page 1635]

9.4.170 SAVE TRANSACTION Statement [T-SQL]

Establishes a savepoint within the current transaction.

 Syntax

SAVE TRANSACTION [ <savepoint-name> ]

Parameters

savepoint-name

An identifier that can be used in a ROLLBACK TRANSACTION statement. All savepoints are automatically
released when a transaction ends.

SAP IQ SQL Reference


SQL Statements INTERNAL 1657
Privileges

None

Standards

SQL – vendor extension to ISO/ANSI SQL grammar

Examples

The following example returns 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

Related Information

BEGIN TRANSACTION Statement [T-SQL] [page 1223]


ROLLBACK TRANSACTION Statement [T-SQL] [page 1656]
REVOKE System Privilege Statement [page 1635]

9.4.171 SAVEPOINT Statement

Establishes a savepoint within the current transaction.

 Syntax

SAVEPOINT [ <savepoint-name> ]

SAP IQ SQL Reference


1658 INTERNAL SQL Statements
Parameters

savepoint-name

An identifier that can be used in a RELEASE SAVEPOINT or ROLLBACK TO SAVEPOINT statement.

Remarks

All savepoints are automatically released when a transaction ends.

Savepoints that are established while a trigger is executing or while an atomic compound statement is
executing are automatically released when the atomic operation ends.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by SAP Adaptive Server Enterprise. To implement similar features
in an SAP ASE-compatible manner, use nested transactions.

Related Information

RELEASE SAVEPOINT Statement [page 1604]


ROLLBACK TO SAVEPOINT Statement [page 1655]
REVOKE System Privilege Statement [page 1635]

9.4.172 SELECT Statement

Retrieves information from the database.

 Syntax

SELECT [ ALL | DISTINCT ] [ <row-limitation-option1> ] <select-list>


… [ INTO { <host-variable-list> | <variable-list> | <table-name >} ]
… [ INTO LOCAL TEMPORARY TABLE { <table-name> } ]
… [ FROM <table-list> ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1659
… [ WHERE <search-condition> ]
… [ GROUP BY [ <expression> [, ...]
| ROLLUP ( <expression> [, ...] )
| CUBE ( <expression> [, ...] ) ] ]
… [ HAVING <search-condition> ]
… [ ORDER BY { <expression> | <integer> } [ ASC | DESC ] [, ...] ]
… [ FOR XML <xml-mode>]
… [ nopagenumber ]

<select-list> ::=
{ <column-name>
| <expression> [ [ AS ] <alias-name> ]
| * }

<row-limitation-option1> ::=
FIRST
| TOP {ALL | <limit-expression>} [START AT <startat-expression> ]

<limit-expression> ::=
<simple-expression>

<startat-expression> ::=
<simple-expression>

<row-limitation-option2> ::=
LIMIT { [ <offset-expression>, ] <limit-expression>
| <limit-expression> OFFSET <offset-expression> }

<offset-expression> ::=
<simple-expression>

<simple-expression> ::=
<integer>
| <variable>
| ( <simple-expression> )
| ( <simple-expression> { + | - | * } <simple-expression> )

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

ALL or DISTINCT

Filters query results. If neither is specified, all rows that satisfy the clauses of the SELECT statement are
retrieved. If DISTINCT is specified, duplicate output rows are eliminated. This is called the projection of the
result of the statement. In many cases, statements take significantly longer to execute when DISTINCT is
specified, so reserve the use of DISTINCT for cases where it is necessary.

SAP IQ SQL Reference


1660 INTERNAL SQL Statements
If DISTINCT is used, the statement cannot contain an aggregate function with a DISTINCT parameter.
row-limitation-option1

Specifies the number of rows returned from a query. FIRST returns the first row selected from the query.
TOP returns the specified number of rows from the query where <number-of-rows> is in the range 1 –
2147483647 and can be an integer constant or integer variable.

 Note

You cannot use TOP and LIMIT in the same query.

FIRST and TOP are used primarily with the ORDER BY clause. If you use these keywords without an ORDER
BY clause, the result might vary from run to run of the same query, as the optimizer might choose a
different query plan.

FIRST and TOP are permitted only in the top-level SELECT of a query, so they cannot be used in derived
tables or view definitions. Using FIRST or TOP in a view definition might result in the keyword being ignored
when a query is run on the view.

Using FIRST is the same as setting the ROW_COUNT database option to 1. Using TOP is the same as setting
the ROW_COUNT option to the same number of rows. If both TOP and ROW_COUNT are set, then the value of
TOP takes precedence.

The ROW_COUNT option could produce inconsistent results when used in a query involving global variables,
system functions or proxy tables. See ROW_COUNT Option for details.
select-list

Is a comma delimited list of expressions that specify what is retrieved from the database. If an asterisk (*)
is specified, all columns of all tables in the FROM clause (table-name all columns of the named table) are
selected. Aggregate functions and analytical functions are allowed in the <select-list>.

 Note

In SAP IQ, scalar subqueries (nested selects) are allowed in the select list of the top level SELECT, as in
SAP SQL Anywhere and SAP Adaptive Server Enterprise. Subqueries cannot be used inside a
conditional value expression (for example, in a CASE statement).

Subqueries can also be used in a WHERE or HAVING clause predicate (one of the supported predicate
types). However, inside the WHERE or HAVING clause, subqueries cannot be used inside a value
expression or inside a CONTAINS or LIKE predicate. Subqueries are not allowed in the ON clause of
outer joins or in the GROUP BY clause.

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. If you use the same
name or expression for a column alias as the column name, the name is processed as an aliased column,
not a table column name.
INTO { host-variable-list | variable-list | table-name }

Specifies the following:

● <host-variable-list> – 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

SAP IQ SQL Reference


SQL Statements INTERNAL 1661
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. Used in Embedded SQL only.
● <variable-list> – 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. Used in
procedures only
● <table-name> – creates a table and fills the table with data. If the table name starts with #, the table
is created as a temporary table. Otherwise, the table is created as a permanent base table. For
permanent tables to be created, the query must satisfy these conditions:
○ The <select-list> contains more than one item, and the INTO target is a single <table-name>
identifier, or
○ The select-list contains a * and the INTO target is specified as <owner.table>.
To create a permanent table with one column, the table name must be specified as <owner.table>.
Omit the owner specification for a temporary table.
This statement causes a COMMIT before execution as a side effect of creating the table. Requires the
CREATE TABLE system privilege 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.
A SELECT INTO from a stored procedure or function is not permitted, as SELECT INTO is an atomic
statement and you cannot do COMMIT, ROLLBACK, or some ROLLBACK TO SAVEPOINT statements in
an atomic statement.
Tables created using this statement 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.
Use of this clause is restricted to valid SAP SQL Anywhere queries. SAP IQ extensions are not
supported.
INTO LOCAL TEMPORARY TABLE

Creates a local, temporary table and populates it with the results of the query. When you use this clause,
you do not need to start the temporary table name with #.
FROM table-list

Retrieves rows and views specified in the <table-list>. Joins can be specified using join operators. For
more information, see FROM Clause. A SELECT statement with no FROM clause can be used to display the
values of expressions not derived from tables. For example, the following displays the value of the
@@version global variable:

SELECT @@version

This is equivalent to:

SELECT @@version
FROM DUMMY

 Note

If you omit the FROM clause, or if all tables in the query are in the SYSTEM dbspace, the query is
processed by SAP SQL Anywhere instead of SAP IQ and might behave differently, especially with
respect to syntactic and semantic restrictions and the effects of option settings.

SAP IQ SQL Reference


1662 INTERNAL SQL Statements
If you have a query that does not require a FROM clause, you can force the query to be processed by
SAP IQ by adding the clause “FROM iq_dummy,” where iq_dummy is a one-row, one-column table that
you create in your database.

WHERE search-condition

Specifies which rows are selected from the tables named in the FROM clause. It is also used to do joins
between multiple tables. This is accomplished by putting a condition in the WHERE clause that relates a
column or group of columns from one table with a column or group of columns from another table. Both
tables must be listed in the FROM clause.

The use of the same CASE statement is not allowed in both the SELECT and the WHERE clause of a
grouped query.

SAP IQ also supports the disjunction of subquery predicates. Each subquery can appear within the WHERE
or HAVING clause with other predicates and can be combined using the AND or OR operators.
GROUP BY

Groups columns, alias names, or functions. GROUP BY expressions must also appear in the select list. The
result of the query contains one row for each distinct set of values in the named columns, aliases, or
functions. The resulting rows are often referred to as groups since there is one row in the result for each
group of rows from the table list. In the case of GROUP BY, all NULL values are treated as identical.
Aggregate functions can then be applied to these groups to get meaningful results.

GROUP BY must contain more than a single constant. You do not need to add constants to the GROUP BY
clause to select the constants in grouped queries. If the GROUP BY expression contains only a single
constant, an error is returned and the query is rejected.

When GROUP BY is used, the select list, HAVING clause, and ORDER BY clause cannot reference any
identifiers except those named in the GROUP BY clause. This exception applies: The <select-list> and
HAVING clause may contain aggregate functions.
ROLLUP operator

Subtotals GROUP BY expressions that roll up from a detailed level to a grand total.
CUBE operator

Analyzes data by forming the data into groups in more than one dimension. CUBE requires an ordered list
of grouping expressions (dimensions) as arguments and enables the SELECT statement to calculate
subtotals for all possible combinations of the group of dimensions. The CUBE operator is part of the
GROUP BY clause.
HAVING search-condition

Based on the group values and not on the individual row values. The HAVING clause can be used only if
either the statement has a GROUP BY clause or if the select list consists solely of aggregate functions. Any
column names referenced in the HAVING clause must either be in the GROUP BY clause or be used as a
parameter to an aggregate function in the HAVING clause.
ORDER BY

Orders the results of a query. Each item in the ORDER BY list can be labeled as ASC for ascending order or
DESC for descending order. Ascending is assumed if neither is specified. If the expression is an integer n,
then the query results are sorted by the nth item in the select list.

SAP IQ SQL Reference


SQL Statements INTERNAL 1663
In Embedded SQL, the SELECT statement is used for retrieving results from the database and placing the
values into host variables with the INTO clause. The SELECT statement must return only one row. For
multiple row queries, you must use cursors.

You cannot include a Java class in the SELECT list, but you can, for example, create a function or variable
that acts as a wrapper for the Java class and then select it.
FOR XML

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. 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.
row-limitation-option2

Returns a subset of rows that satisfy the WHERE clause. Only one row-limitation clause can be specified at
a time. When specifying this clause, an ORDER BY clause is required to order the rows in a meaningful
manner. The row limitation clause is valid only in the top query block of a statement.

The LIMIT argument must be an integer or integer variable 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 row limitation clause LIMIT <offset-expression>, <limit-expression> is equivalent to LIMIT


<limit-expression> OFFSET <offset-expression>.

The LIMIT keyword is disabled by default. Use the RESERVED_KEYWORDS option to enable the LIMIT
keyword.

 Note

You cannot specify TOP and LIMIT in the same query.

Remarks

(back to top)

You can use a SELECT statement in Interactive SQL to browse data in the database or to export data from the
database to an external file.

You can also use a SELECT statement in procedures or in Embedded SQL. The SELECT statement with an INTO
clause is used for retrieving results from the database when the SELECT statement returns only one row.
(Tables created with SELECT INTO do not inherit IDENTITY/AUTOINCREMENT tables.) For multiple-row
queries, you must use cursors. When you select more than one column and do not use <#table>, SELECT
INTO creates a permanent base table. SELECT INTO <#table> always creates a temporary table regardless of
the number of columns. SELECT INTO table with a single column selects into a host variable.

SAP IQ SQL Reference


1664 INTERNAL SQL Statements
 Note

When writing scripts and stored procedures that SELECT INTO a temporary table, wrap any select list item
that is not a base column in a CAST expression. This guarantees that the column data type of the
temporary table is the required data type.

Tables with the same name but different owners require aliases. A query without aliases returns incorrect
results:

SELECT * FROM user1.t1


WHERE NOT EXISTS
(SELECT *
FROM user2.t1
WHERE user2.t1.col1 = user1.t.col1);

For correct results, use an alias for each table:

SELECT * FROM user1.t1 U1


WHERE NOT EXISTS
(SELECT *
FROM user2.t1 U2
WHERE U2.col1 = U1.col1);

The INTO clause with a <variable-list> is used only in procedures.

In SELECT statements, a stored procedure call can appear anywhere a base table or view is allowed. Note that
CIS functional compensation performance considerations apply. For example, a SELECT statement can also
return a result set from a procedure.

The ROLLUP Operator


The ROLLUP operator requires an ordered list of grouping expressions to be supplied as arguments. ROLLUP
first calculates the standard aggregate values specified in the GROUP BY. Then ROLLUP moves from right to
left through the list of grouping columns and creates progressively higher-level subtotals. A grand total is
created at the end. If <n> is the number of grouping columns, ROLLUP creates <n+1> levels of subtotals.

Restrictions on the ROLLUP operator:

● ROLLUP supports all of the aggregate functions available to the GROUP BY clause, but ROLLUP does not
currently support COUNT DISTINCT and SUM DISTINCT.
● ROLLUP can be used only in the SELECT statement; you cannot use ROLLUP in a SELECT subquery.
● A multiple grouping specification that combines ROLLUP, CUBE, and GROUP BY columns in the same
GROUP BY clause is not currently supported.
● Constant expressions as GROUP BY keys are not supported.

GROUPING is used with the ROLLUP operator to distinguish between stored NULL values and NULL values in
query results created by ROLLUP.

ROLLUP syntax:

SELECT … [ GROUPING ( <column-name >) …] …


GROUP BY [ <expression> [, …]
| ROLLUP ( <expression> [, …] ) ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1665
GROUPING takes a column name as a parameter and returns a Boolean value:

If the Value of the Result Is GROUPING Returns

NULL created by a ROLLUP operation 1 (TRUE)

NULL indicating the row is a subtotal 1 (TRUE)

not created by a ROLLUP operation 0 (FALSE)

a stored NULL 0 (FALSE)

The CUBE Operator

Restrictions on the CUBE operator:

● CUBE supports all of the aggregate functions available to the GROUP BY clause, but CUBE does not
currently support COUNT DISTINCT or SUM DISTINCT.
● CUBE does not currently support the inverse distribution analytical functions PERCENTILE_CONT and
PERCENTILE_DISC.
● CUBE can be used only in the SELECT statement; you cannot use CUBE in a SELECT subquery.
● A multiple GROUPING specification that combines ROLLUP, CUBE, and GROUP BY columns in the same
GROUP BY clause is not currently supported.
● Constant expressions as GROUP BY keys are not supported.

GROUPING is used with the CUBE operator to distinguish between stored NULL values and NULL values in
query results created by CUBE.

CUBE syntax:

SELECT … [ GROUPING ( <column-name> ) …] …


GROUP BY [ <expression> [, …]
| CUBE ( <expression> [, …] ) ]

GROUPING takes a column name as a parameter and returns a Boolean value:

If the Value of the Result Is GROUPING Returns

NULL created by a CUBE operation 1 (TRUE)

NULL indicating the row is a subtotal 1 (TRUE)

not created by a CUBE operation 0 (FALSE)

a stored NULL 0 (FALSE)

When generating a query plan, the SAP IQ optimizer estimates the total number of groups generated by the
GROUP BY CUBE hash operation. The MAX_CUBE_RESULTS database option sets an upper boundary for the
number of estimated rows the optimizer considers for a hash algorithm that can be run. If the actual number of
rows exceeds the MAX_CUBE_RESULT option value, the optimizer stops processing the query and returns the
error message "Estimate number: nnn exceed the DEFAULT_MAX_CUBE_RESULT of GROUP BY
CUBE or ROLLUP," where <nnn> is the number estimated by the optimizer. See MAX_CUBE_RESULT Option
for information on setting the MAX_CUBE_RESULT option.

Unexpected Query Results

In a few unusual circumstances, differences in semantics between SQL Anywhere and SAP IQ may produce
unexpected query results. These circumstances are:

SAP IQ SQL Reference


1666 INTERNAL SQL Statements
● A query is issued from inside a user-defined function
● A SELECT statement has no FROM clause
● A FROM clause contains some tables that were created IN SYSTEM and others that were not created IN
SYSTEM

In these circumstances, subtle differences between the semantics of SQL Anywhere and SAP IQ may be
exposed. These differences include:

● SAP IQ treats the CHAR and VARCHAR data types as distinct and different; SQL Anywhere treats CHAR data
as if it were VARCHAR.
● When the RAND function is passed an argument, the behavior is deterministic in SAP IQ and
nondeterministic in SAP SQL Anywhere.

Privileges

(back to top)

Requires SELECT object-level privilege on the named tables and views. See GRANT Object-Level Privilege
Statement [page 1502] for assistance with granting privileges

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise, with some differences in syntax.

Examples

(back to top)

● The following example lists all tables and views in the system catalog:

SELECT tname
FROM SYS.SYSCATALOG
WHERE tname LIKE 'SYS%' ;

● The following example lists all customers and the total value of their orders:

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
ORDER BY VALUE DESC

SAP IQ SQL Reference


SQL Statements INTERNAL 1667
● The following example lists the number of employees:

SELECT count(*)
FROM Employees;

● The following example is an Embedded SQL SELECT statement:

SELECT count(*) INTO :size FROM Employees;

● The following example lists the total sales by year, model, and color:

SELECT year, model, color, sum(sales)


FROM sales_tab
GROUP BY ROLLUP (year, model, color);

● The following example selects all items with a certain discount into a temporary table:

SELECT * INTO #TableTemp FROM lineitem


WHERE l_discount < 0.5

● The following example returns information about the employee that appears first when employees are
sorted by last name:

SELECT FIRST *
FROM Employees
ORDER BY Surname;

● The following examples return the first five employees when their names are sorted by last name:

SELECT TOP 5 *
FROM Employees
ORDER BY Surname;

SELECT *
FROM Employees
ORDER BY Surname
LIMIT 5;

● The following example lists the fifth and sixth employees sorted in descending order by last name:

SELECT *
FROM Employees
ORDER BY Surname DESC
LIMIT 4,2;

In this section:

Row Limitation Clauses in SELECT Query Blocks [page 1669]


The FIRST, TOP, and LIMIT clauses allow you to return a subset of the rows that satisfy the WHERE
clause. The FIRST, TOP, and LIMIT clauses can be used within any SELECT query block that includes an
ORDER BY clause. FIRST, TOP, and LIMIT can only be used in the top query block in a statement.

Related Information

Row Limitation Clauses in SELECT Query Blocks [page 1669]


CREATE VIEW Statement [page 1408]

SAP IQ SQL Reference


1668 INTERNAL SQL Statements
DECLARE CURSOR Statement [ESQL] [SP] [page 1415]
FETCH Statement [ESQL] [SP] [page 1475]
FROM Clause [page 1483]
MAX_CUBE_RESULT Option [page 1907]
OPEN Statement [ESQL] [SP] [page 1582]
UNION Statement [page 1699]
RESERVED_KEYWORDS Option [page 1981]
ROW_COUNT Option [page 1986]
SUBQUERY_CACHING_PREFERENCE Option [page 2017]
REVOKE System Privilege Statement [page 1635]

9.4.172.1 Row Limitation Clauses in SELECT Query Blocks

The FIRST, TOP, and LIMIT clauses allow you to return a subset of the rows that satisfy the WHERE clause. The
FIRST, TOP, and LIMIT clauses can be used within any SELECT query block that includes an ORDER BY clause.
FIRST, TOP, and LIMIT can only be used in the top query block in a statement.

 Syntax

The FIRST, TOP, and LIMIT clauses are row-limitation clauses and they have the following syntax:

<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 )

Only one row limitation clause can be specified for a SELECT clause. When specifying these clauses, an
ORDER BY clause is required to order the rows in a meaningful manner.

Parameters

row-limitation-option-1

SAP IQ SQL Reference


SQL Statements INTERNAL 1669
This type of clause can be used in SELECT query blocks only. The TOP and START AT arguments can be
simple arithmetic expressions over host variables, integer constants, or integer variables. The TOP
argument must evaluate to a value greater than or equal to 0. The START AT argument must evaluate to a
value greater than 0. If <startat-expression> is not specified the default is 1.

The expression limit-expression + startat-expression -1 must evaluate to a value less than


9223372036854775807 = 2^64-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

This type of clause can be used in SELECT query blocks only. 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 expression
limit-expression + offset-expression must evaluate to a value less than 9223372036854775807
= 2^64-1.

The row-limitation clause LIMIT offset-expression, limit-expression is equivalent to LIMIT


limit-expression OFFSET offset-expression. Both of these constructs are equivalent to TOP limit-
expression START AT (offset-expression + 1).

The LIMIT keyword is disabled by default. Use the reserved_keywords option to enable the LIMIT keyword.

Parent topic: SELECT Statement [page 1659]

Related Information

SELECT Statement [page 1659]

9.4.173 SET Statement [ESQL]

Assigns a value to a SQL variable.

 Syntax

SET <identifier> = <expression>

Go to:

● Privileges
● Standards
● Examples

SAP IQ SQL Reference


1670 INTERNAL SQL Statements
Remarks

(back to top)

The SET statement assigns a new value to a variable. The variable must have been previously created by 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, then the column value is used.

The <owner> specification is only for use when setting owned database-scope variables.

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.

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.

If you set a database-scope variable, however, the variable persists after a disconnect. When the database is
restarted, the value of a database-scope variable reverts to NULL or its default, if defined. The
SYSDATABASEVARIABLE system view contains a list of all database-scope variables and their initial values.

You cannot set a database-scope variable owned by another user.

Privileges

(back to top)

If you own the database-scope variable, no additional privilege is required. To set a database-scope variable
owned by PUBLIC, you must have the UPDATE PUBLIC DATABASE VARIABLE system privilege.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported. In SAP Adaptive Server Enterprise, variables are assigned using
the SELECT statement with no table, a Transact-SQL syntax that is also supported by SAP IQ. The SET
statement is used to set database options in SAP ASE.

Examples

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1671
● This code fragment inserts a large text value into the database:

EXEC SQL BEGIN DECLARE SECTION;


char buffer[5001];
EXEC SQL END DECLARE SECTION;
EXEC SQL CREATE VARIABLE hold_text VARCHAR;
EXEC SQL SET hold_text = '';
for(;;) {
/* read some data into buffer ... */
size = fread( buffer, 1, 5000, fp );
if( size <= 0 ) break;

/* buffer must be null-terminated */


buffer[size] = '\0';
/* add data to blob using concatenation */
EXEC SQL SET hold_text = hold_text || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES ( 1, hold_text );
EXEC SQL DROP VARIABLE hold_text;

● This code fragment inserts a large binary value into the database:

EXEC SQL BEGIN DECLARE SECTION;


DECL_BINARY( 5000 ) buffer;
EXEC SQL END DECLARE SECTION;
EXEC SQL CREATE VARIABLE hold_blob LONG BINARY;
EXEC SQL SET hold_blob = '';
for(;;) {
/* read some data into buffer ... */
size = fread( &(buffer.array), 1, 5000, fp );
if( size <= 0 ) break;
buffer.len = size;
/* add data to blob using concatenation
Note that concatenation works for
binary data too! */
EXEC SQL SET hold_blob = hold_blob || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES ( 1, hold_blob );
EXEC SQL DROP VARIABLE hold_blob;

● This simple example shows the creation of a variable called birthday, and sets 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:

size_t size;
FILE * fp;
EXEC SQL BEGIN DECLARE SECTION;
DECL_VARCHAR( 5000 ) buffer;
EXEC SQL END DECLARE SECTION;
fp = fopen( "blob.dat", "r" );
EXEC SQL CREATE VARIABLE hold_blob LONG VARCHAR;
EXEC SQL SET hold_blob = '';
for(;;) {
size = fread( (void *)buffer.array, 1, 5000, fp );
if( size <= 0 ) break;
buffer.len = (a_sql_ulen) size;
EXEC SQL SET hold_blob = hold_blob || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES( 1, hold_blob );
EXEC SQL COMMIT;
EXEC SQL DROP VARIABLE hold_blob;
fclose( fp );

SAP IQ SQL Reference


1672 INTERNAL SQL Statements
Related Information

CREATE VARIABLE Statement [page 1404]


DROP VARIABLE statement [page 1466]
REVOKE System Privilege Statement [page 1635]

9.4.174 SET Statement [T-SQL]

Sets database options in an SAP Adaptive Server Enterprise-compatible manner.

 Syntax

SET <option-name> <option-value>

<option-value> ::=
ANSINULL [ ON | OFF ]
| ANSI_PERMISSIONS [ ON | OFF ]
| CLOSE_ON_ENDTRANS ON
| QUOTED_IDENTIFIER [ ON | OFF ]
| ROWCOUNT <integer>
| STRING_RTRUNCATION [ ON | OFF ]
| TRANSACTION ISOLATION LEVEL [ 0 | 1 | 2 | 3 ]

Parameters

ANSINULL

The default behavior for comparing values to NULL in SAP IQ and SAP ASE is different. Setting ANSINULL
to OFF provides Transact-SQL compatible comparisons with NULL.
ANSI_PERMISSIONS

The default behavior in SAP IQ and SAP ASE regarding permissions required to carry out a DELETE
containing a column reference is different. Setting ANSI_PERMISSIONS to OFF provides Transact-SQL-
compatible permissions on DELETE.
CLOSE_ON_ENDTRANS

When set to ON (the default and only allowable value), cursors are closed at the end of a transaction. With
the option set ON, CLOSE_ON_ENDTRANS provides Transact-SQL-compatible behavior.
QUOTED_IDENTIFIER

Controls whether strings enclosed in double quotes are interpreted as identifiers (ON) or as literal strings
(OFF).
ROWCOUNT

In the Transact-SQL, limits to the specified integer the number of rows fetched for any cursor. This includes
rows fetched by repositioning the cursor. Any fetches beyond this maximum return a warning. The setting
is considered when returning the estimate of the number of rows for a cursor on an OPEN request.

SAP IQ SQL Reference


SQL Statements INTERNAL 1673
 Note

SAP IQ supports the <@@rowcount> global variable. SELECT, INSERT, DELETE, and UPDATE
statements affect the value of the ROWCOUNT clause. The ROWCOUNT clause has no effect on cursor
operation, the IF statement, or creating or dropping a table or procedure.

In SAP IQ, if ROWCOUNT is greater than the number of rows that dbisql can display, dbisql may do
extra fetches to reposition the cursor. The number of rows actually displayed may be less than the number
requested. Also, if any rows are refetched due to truncation warnings, the count might be inaccurate.

A value of zero resets the option to get all rows.


STRING_RTRUNCATION

The default behavior in SAP IQ and SAP ASE when nonspace characters are truncated on assigning SQL
string data is different. Setting STRING_RTRUNCATION to ON provides Transact-SQL-compatible string
comparisons, including hexadecimal string (binary data type) comparisons.
TRANSACTION ISOLATION LEVEL

Sets the locking isolation level for the current connection For SAP ASE, only 1 and 3 are valid options. For
SAP IQ, only 3 is a valid option.
SET PREFETCH

Is allowed by SAP IQ for compatibility, but has no effect.

Remarks

Database options in SAP IQ are set using the SET OPTION statement. However, SAP IQ also provides support
for the SAP ASE SET statement for a set of options particularly useful for compatibility.

Privileges

None

Standards

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – SAP IQ supports a subset of the SAP ASE database options.

Related Information

SET OPTION Statement [page 1677]

SAP IQ SQL Reference


1674 INTERNAL SQL Statements
REVOKE System Privilege Statement [page 1635]

9.4.175 SET CONNECTION Statement [ESQL] [Interactive


SQL]

Changes the active database connection.

 Syntax

SET CONNECTION [<connection-name>]

Remarks

The current connection state is saved, and resumed when it again becomes the active connection. If you omit
<connection-name>, but a connection exists that was not named, that connection becomes the active
connection.

 Note

When cursors are opened in Embedded SQL, they are associated with the current connection. When the
connection is changed, you cannot access the cursor names. The cursors remain active and in position and
can become accessed when the associated connection becomes active again.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar. Embedded SQL is a full-level feature.
● SAP database products – supported by Open Client/Open Server.

Examples

The following example sets the current connection to the connection named "conn1" from dbisql:

SET CONNECTION conn1

SAP IQ SQL Reference


SQL Statements INTERNAL 1675
Related Information

CONNECT Statement [ESQL] [Interactive SQL] [page 1241]


DISCONNECT Statement [Interactive SQL] [page 1432]
REVOKE System Privilege Statement [page 1635]

9.4.176 SET DESCRIPTOR Statement [ESQL]

Describes the variables in a SQL descriptor area, and places data into the descriptor area.

 Syntax

SET DESCRIPTOR <descriptor-name>


… { COUNT = { <integer> | <hostvar> }
| VALUE <n> <assignment> [, …] }

<assignment> ::=
{ { TYPE
| SCALE
| PRECISION
| LENGTH
| INDICATOR } = { <integer>
| <hostvar> }
| DATA = <hostvar> }

Parameters

COUNT

Sets the number of described variables within the descriptor area. The value for count cannot exceed the
number of variables specified when the descriptor area was allocated.
VALUE

The value <n> specifies the variable in the descriptor area upon which the assignments are performed.
DATA

Type checking is performed when using the DATA clause to ensure that the variable in the descriptor area
has the same type as the host variable. If an error occurs, the code is returned in the SQLCA.

Privileges

None

SAP IQ SQL Reference


1676 INTERNAL SQL Statements
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by Open Client/Open Server

Examples

See ALLOCATE DESCRIPTOR Statement [ESQL].

Related Information

ALLOCATE DESCRIPTOR Statement [ESQL] [page 1131]


DEALLOCATE DESCRIPTOR Statement [ESQL] [page 1411]
REVOKE System Privilege Statement [page 1635]

9.4.177 SET OPTION Statement

Changes options that affect the behavior of the database and its compatibility with Transact-SQL. Setting the
value of an option can change the behavior for all users or an individual user, in either a temporary or
permanent scope.

 Syntax

SET [ EXISTING ] [ TEMPORARY ] OPTION


… [ <user_id>. | PUBLIC.]<option-name> = [ <option-value> ]

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

option-value

A host-variable (indicator allowed), string, identifier, or number. The maximum length of <option-value>
when set to a string is 127 bytes.

SAP IQ SQL Reference


SQL Statements INTERNAL 1677
If <option-value> is omitted, the specified option setting is deleted from the database. If it was a
personal option setting, the value used reverts to the PUBLIC setting.

 Note

For all database options that accept integer values, SAP IQ truncates any decimal <option-value>
setting to an integer value. For example, the value 3.8 is truncated to 3.

EXISTING

Option values cannot be set for an individual user ID unless there is already a PUBLIC user ID setting for
that option.
TEMPORARY

Changes the duration that the change takes effect. Without the TEMPORARY clause, an option change is
permanent: it does not change until it is explicitly changed using SET OPTION statement.

When the TEMPORARY clause is applied using an individual user ID, the new option value is in effect as
long as that user is logged in to the database.

When the TEMPORARY clause is used with 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 user ID revert
to their permanent value.

If a TEMPORARY option is deleted, the option setting reverts to the permanent setting.

Remarks

(back to top)

The classes of options are:

● General database options


● Transact-SQL compatibility database options

Specifying either a user ID or the PUBLIC user ID determines whether the option is set for an individual user, a
role represented by <user_id>, or the PUBLIC user ID (the role to which all users are a member). If the option
applies to a role ID, option settings are not inherited by members of the role — the change is applied only to the
role ID. If no role is specified, the option change is applied to the currently logged-in user ID that issued the SET
OPTION statement. For example, this statement applies an option change to the PUBLIC user ID:

SET OPTION Public.login_mode = standard

In Embedded SQL, only database options can be set temporarily.

Changing the value of an option for the PUBLIC user ID sets the value of the option for any user that has not set
its own value. Option values cannot be set for an individual user ID unless there is already a PUBLIC user ID
setting for that option.

Temporarily setting an option for the PUBLIC user ID, as opposed to setting the value of the option
permanently, offers a security advantage. For example, when the LOGIN_MODE option is enabled, the database
relies on the login security of the system on which it is running. Enabling the option temporarily means a
database relying on the security of a Windows domain is not compromised if the database is shut down and

SAP IQ SQL Reference


1678 INTERNAL SQL Statements
copied to a local machine. In that case, the temporary enabling of LOGIN_MODE reverts to its permanent value,
which might be Standard, a mode in which integrated logins are not permitted.

 Caution

Changing option settings while fetching rows from a cursor is not supported, as it can lead to unpredictable
behavior. For example, changing the DATE_FORMAT setting while fetching from a cursor returns different
date formats among the rows in the result set. Do not change option settings while fetching rows.

Privileges

(back to top)

● No specific system privilege is required to set your own options.


● The SET ANY PUBLIC OPTION system privilege is required to set database options for another user.
● The SET ANY SYSTEM OPTION system privilege is required to set a SYSTEM option for the PUBLIC user ID.
● The SET ANY SECURITY OPTION system privilege is required to set a SECURITY option for the PUBLIC
user ID.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar.


● SAP database products – not supported by SAP Adaptive Server Enterprise. SAP IQ does support some
SAP Adaptive Server Enterprise options using the SET OPTION statement.

Examples

(back to top)

● The following example sets the DATE_FORMAT option:

SET OPTION public.date_format = 'Mmm dd yyyy'

● The following example sest the WAIT_FOR_COMMIT option to on:

SET OPTION wait_for_commit = 'on'

● The following example embeddes SQL examples:

EXEC SQL SET OPTION :user.:option_name = :value;


EXEC SQL SET TEMPORARY OPTION Date_format = 'mm/dd/yyyy';

SAP IQ SQL Reference


SQL Statements INTERNAL 1679
Related Information

Set a Database Option [page 1727]


Database Options [page 1720]
PREFETCH_FP_PERCENT Option [page 1953]
Set a Database Option [page 1727]
PREFETCH_HASH_PERCENT Option [page 1955]
Set a Database Option [page 1727]
PREFETCH_LOB_PERCENT Option [page 1956]
Set a Database Option [page 1727]
PREFETCH_TEXTPOST_PERCENT Option [page 1958]
Set a Database Option [page 1727]
REVOKE System Privilege Statement [page 1635]

9.4.178 SET OPTION Statement [Interactive SQL]

Changes Interactive SQL (dbisql) options.

 Syntax

Syntax 1

SET [ TEMPORARY ] OPTION


… [ <userid>. | PUBLIC.]<option-name> = [ <option-value> ]

Syntax 2

SET PERMANENT

Syntax 3

SET

Remarks

Syntax 2 (SET PERMANENT) stores all current dbisql options in the SYSOPTION system table. These settings
are automatically established every time dbisql is started for the current user ID.

Syntax 3 (SET) shows all current option settings. If there are temporary options set for dbisql or the database
server, these are shown; otherwise, permanent option settings are shown.

If you enter the name of an option incorrectly when you are setting the option, the incorrect name is saved in
the SYSOPTION table. You can remove the incorrectly entered name from the SYSOPTION table by setting the
option PUBLIC with an equality after the option name and no value:

SET OPTION PUBLIC.a_mistyped_name=;

SAP IQ SQL Reference


1680 INTERNAL SQL Statements
Privileges

No specific system privilege is required to set your own options.

The SET ANY PUBLIC OPTION system privilege is required to set database options for another user.

The SET ANY SYSTEM OPTION system privilege is required to set a SYSTEM option for the PUBLIC user ID.

The SET ANY SECURITY OPTION system privilege is required to set a SECURITY option for the PUBLIC user ID.

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Related Information

Database Options [page 1720]


REVOKE System Privilege Statement [page 1635]

9.4.179 SET SQLCA Statement [ESQL]

Tells the SQL preprocessor to use a SQLCA other than the default global <sqlca>.

 Syntax

SET SQLCA <sqlca>

Parameters

sqlca

Identifier or string

Remarks

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

SAP IQ SQL Reference


SQL Statements INTERNAL 1681
Permissions

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not supported by Open Client/Open Server

Examples

The following example shows a function that can 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 );
}

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.180 SETUSER Statement


Allows a user to temporarily assume the roles and system privileges of another user (also known as
impersonation) to perform operations, provided they already have the minimum required privileges to perform
the task to begin with.

 Note

The SET USER system privilege is two words; the SETUSER statement is one word.

 Syntax

SETUSER <user_id>

SAP IQ SQL Reference


1682 INTERNAL SQL Statements
Parameters

user_id

Must be the name of an existing user or role that has a login password.

Remarks

At-least criteria validation occurs when the SETUSER statement is executed, not when the SET USER system
privilege is granted.

To terminate a successful impersonation, issue the SETUSER statement without specifying a <user_id>.

Privileges

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Requires the following:

● The impersonator has been granted the right to impersonate the target user.
● The impersonator has, at minimum, all the roles and system privileges granted to the target user.
● The impersonator has been granted the said roles and system privileges with similar or higher
administrative rights.

 Note

For the purposes of meeting administrative rights criteria, the WITH ADMIN OPTION and WITH ADMIN
ONLY OPTION clauses are considered to grant similar administrative rights. They are also considered
to grant higher administrative rights than the WITH NO ADMIN OPTION clause. For example, User1 is
granted Role1 with the WITH ADMIN OPTION clause, User2 is granted Role1 with the WITH ADMIN
ONLY clause, and User3 is granted Role1 with the WITH NO ADMIN OPTION clause. User1 and
User2 are said to be granted Role1 with similar administrative rights. User1 and User2 are also said
to be granted Role1 with higher administrative rights than User3.

● If the target user has been granted a system privilege that supports extensions, the clauses used to grant
the system privilege to the impersonator are a super-set of those used for the target user. Only the SET
USER and CHANGE PASSWORD system privileges support extensions.
○ The ANY clause is considered a super-set of the <target_roles_list> and
<target_users_list> clauses. If the target user has been granted the SET USER system privilege
with an ANY grant, the impersonator must also have the ANY grant.
○ If the target user has been granted the SET USER system privilege with both the
<target_roles_list> and <target_users_list> clauses, the impersonator must also have been
granted the system privilege with the two clauses, and the target list of each clause must be equal to,
or a super set of, the corresponding clause grant of the target user. For example, if the target lists of
both the impersonator and target user contain User1, User2 and Role1, Role2, respectively, the
target list grants for each clause are said to be equal. Alternately, if the target list grants of the
impersonator contain User1, User2, and Role1, Role2, respectively, while the target list grants of the

SAP IQ SQL Reference


SQL Statements INTERNAL 1683
target user contain User1 and Role2 only, the target list grants of the impersonator are said to be a
super-set of the target user.
○ If the target user has been granted the SET USER system privilege with a single target list clause, the
target list of the impersonator must be equal to or a super-set of the list of the target user. For
example, the <target_user_list> of both the impersonator and the target user contain User1 and
User2 (equal) or the impersonator list contains User1, User2, while the target user contains User2;
User1, User2 (impersonator list) is a super-set of User2 (target user list).
○ By definition, a user can always impersonate himself or herself. Therefore, if the target user is granted
the right to impersonate the impersonator, this does not violate the equal to or a super-set of criteria
requirement of the impersonator. For example, User3 is the impersonator and User4 is the target
user. The <target_user_list> for User3 contains User4 and User5. The <target_user_list>
for User4 contains User3 and User5. If you remove the impersonator from the target list, the target
list of User3 meets the criteria requirement.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.181 SIGNAL Statement

Lets you raise an exception condition.

 Syntax

SIGNAL <exception-name>

Privileges

None

SAP IQ SQL Reference


1684 INTERNAL SQL Statements
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – not supported by SAP Adaptive Server Enterprise

Related Information

BEGIN … END Statement [page 1218]


RESIGNAL Statement [page 1607]
REVOKE System Privilege Statement [page 1635]

9.4.182 START DATABASE Statement [Interactive SQL]


Starts a database on the specified database server.

 Syntax

START DATABASE <database-file>


… [ AS <database-name > ]
… [ ON <engine-name> ]
… [ AUTOSTOP { YES | NO } ]
… [ KEY <key> ]

Parameters

AS database-name

(Optional) If not specified, the statement assigns a default name to the database. This default name is the
root of the database file. For example, a database in file c:\SAP\16_1\demo\iqdemo.db is given the
default name iqdemo.
ON engine-name

(Optional) If not specified, the statement uses the default database server. The default database server is
the first started server among those that are currently running.
AUTOSTOP { YES | NO }

(Optional) When set to YES (default), the database is unloaded when the last connection to it is dropped.
When set to NO, the database is not unloaded.
KEY key

(Optional) Specify to enter the KEY value (password) for strongly encrypted databases.

 Note

Start only one database on a given SAP IQ database server.

SAP IQ SQL Reference


SQL Statements INTERNAL 1685
Remarks

The database server must be running. The full path must be specified for the database file unless the file is
located in the current directory.

The START DATABASE statement does not connect dbisql to the specified database you must also issue a
CONNECT statement to make a connection.

Privileges

Requires the SERVER OPERATOR system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

● (UNIX) This example starts the database file /s1/IQ/sample_2.db on the current server:

START DATABASE '/s1/IQ/sample_2.db'

● (Windows) This example starts the database file c:\IQ\sample_2.db as sam2 on the server eng1:

START DATABASE 'c:\IQ\sample_2.db'


AS sam2
ON eng1

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1686 INTERNAL SQL Statements
9.4.183 START ENGINE Statement [Interactive SQL]

Starts a database server.

 Syntax

START ENGINE
AS <engine-name> [ STARTLINE <command-string> ]

Parameters

STARTLINE

Specifies a set of options for the server.


command-string

Specifies valid command strings that conform to the database server command line description. See
start_iq Database Server Startup Utility in the SAP IQ Utility Reference.

Remarks

Several server options are required for SAP IQ to operate well. To ensure that you are using the best options,
start your server by using either SAP IQ Cockpit or a configuration file with the start_iq command.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

● The following example starts a database server named eng1 without starting any databases on it:

START ENGINE AS eng1

SAP IQ SQL Reference


SQL Statements INTERNAL 1687
● The following example starts the same server with a cache of 8096 KB:

START ENGINE AS eng1 STARTLINE 'start_iq -c 8096'

Related Information

STOP ENGINE Statement [Interactive SQL] [page 1691]


REVOKE System Privilege Statement [page 1635]

9.4.184 START EXTERNAL ENVIRONMENT statement

Starts an external environment.

 Syntax

START EXTERNAL ENVIRONMENT <environment-name>

<environment-name> :
C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64
| JAVA
| JS
| PERL
| PHP

Parameters

environment-name

The name of the external environment to start.

Remarks

The START EXTERNAL ENVIRONMENT statement can be used to ensure that the external environment
module can be located and started. Since an external environment is automatically started, this statement is
not required.

SAP IQ SQL Reference


1688 INTERNAL SQL Statements
Privileges

None

Side effects

None

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

Start the Perl external environment.

START EXTERNAL ENVIRONMENT PERL;

Related Information

STOP EXTERNAL ENVIRONMENT statement [page 1692]


STOP EXTERNAL ENVIRONMENT statement [page 1692]
REVOKE System Privilege Statement [page 1635]

9.4.185 START JAVA Statement

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

 Syntax

START EXTERNAL ENVIRONMENT JAVA

SAP IQ SQL Reference


SQL Statements INTERNAL 1689
Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

The following example starts the Java VM:

START EXTERNAL ENVIRONMENT JAVA

Related Information

STOP JAVA Statement [page 1694]


REVOKE System Privilege Statement [page 1635]

9.4.186 STOP DATABASE Statement [Interactive SQL]

Stops a database on the specified database server.

 Syntax

STOP DATABASE <database-name>


… [ ON <engine-name> ]
… [ UNCONDITIONALLY ]

Parameters

database-name

The name specified in the -n parameter when the database is started, or specified in the DBN
(DatabaseName) connection parameter. This name is typically the file name of the database file that holds
the catalog store, without the .db extension, but can be any user-defined name.

SAP IQ SQL Reference


1690 INTERNAL SQL Statements
ON engine-name

(Optional) If not specified, all running engines are searched for a database of the specified name.
UNCONDITIONALLY

(Optional) If specified, the database is stopped, even if there are connections to the database. If not
specified, the database is not stopped if there are connections to it.

Privileges

Requires the SERVER OPERATOR system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

The following example stops the database named sample on the default server:

STOP DATABASE sample

Related Information

DISCONNECT Statement [Interactive SQL] [page 1432]


START DATABASE Statement [Interactive SQL] [page 1685]
REVOKE System Privilege Statement [page 1635]

9.4.187 STOP ENGINE Statement [Interactive SQL]

Stops a database server.

 Syntax

STOP ENGINE <engine-name> [ UNCONDITIONALLY ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1691
Parameters

UNCONDITIONALLY

If specified, the database server is stopped, even if there are connections to the server. If not specified, the
database server is not stopped if there are connections to it.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Examples

The following example stops the database server named sample:

STOP ENGINE sample

Related Information

START ENGINE Statement [Interactive SQL] [page 1687]


REVOKE System Privilege Statement [page 1635]

9.4.188 STOP EXTERNAL ENVIRONMENT statement

Stops an external environment.

 Syntax

STOP EXTERNAL ENVIRONMENT <environment-name>

<environment-name> :
C_ESQL32
| C_ESQL64

SAP IQ SQL Reference


1692 INTERNAL SQL Statements
| C_ODBC32
| C_ODBC64
| JAVA
| JS
| PERL
| PHP

Parameters

environment-name

The name of the external environment to stop.

Remarks

None.

Privileges

None

Side effects

None

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

This example stops the Perl external environment.

STOP EXTERNAL ENVIRONMENT PERL;

SAP IQ SQL Reference


SQL Statements INTERNAL 1693
Related Information

START EXTERNAL ENVIRONMENT statement [page 1688]


START EXTERNAL ENVIRONMENT statement [page 1688]
REVOKE System Privilege Statement [page 1635]

9.4.189 STOP JAVA Statement

Releases resources associated with the Java VM to economize on the use of system resources.

 Syntax

STOP EXTERNAL ENVIRONMENT JAVA

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – not applicable

Related Information

START JAVA Statement [page 1689]


REVOKE System Privilege Statement [page 1635]

9.4.190 TRIGGER EVENT Statement

Triggers a named event. The event may be defined for event triggers or be a scheduled event.

 Syntax

TRIGGER EVENT <event-name> [ ( <parm> = <value>, ... ) ]

SAP IQ SQL Reference


1694 INTERNAL SQL Statements
Remarks

Actions are tied to particular trigger conditions or schedules by a CREATE EVENT statement. You can use
TRIGGER EVENT 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

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. TRIGGER EVENT allows you to
explicitly supply these parameters, to simulate a context for the event handler.

When you trigger an event, specify the event name. You can list event names by querying the system table
SYSEVENT. For example:

SELECT event_id, event_name FROM SYS.SYSEVENT

Privileges

Requires the MANAGE ANY EVENT system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Related Information

ALTER EVENT Statement [page 1142]


CREATE EVENT Statement [page 1262]
REVOKE System Privilege Statement [page 1635]

9.4.191 TRUNCATE Statement

Deletes all rows from a table or materialized view without deleting the table definition.

 Syntax

TRUNCATE
TABLE [ <owner>.]<table-name>
[ PARTITION <partition-name>
| SUBPARTITION <subpartition-name> ]
| MATERIALIZED VIEW <owner>.] <materialized-view-name>

Parameters

PARTITION

SAP IQ SQL Reference


SQL Statements INTERNAL 1695
Specifies which partition to truncate, and does not affect data in other partitions.

 Note

Specifying an RLV-enabled table in the PARTITION clause results in an error.

SUBPARTITION

Truncates tables partitioned by a composite partitioning scheme.

 Note

Specifying an RLV-enabled table in the SUBPARTITION clause results in an error.

Remarks

TRUNCATE is equivalent to a DELETE statement without a WHERE clause, except that each individual row
deletion is not entered into the transaction log. After a TRUNCATE TABLE statement, the table structure and all
of the indexes continue to exist until you issue a DROP TABLE statement. The column definitions and
constraints remain intact, and permissions remain in effect.

The TRUNCATE statement is entered into the transaction log as a single statement, like data definition
statements. Each deleted row is not entered into the transaction log.

 Note

If the table you are truncating contains an identity column, the TRUNCATE statement does not reset the
identity number sequence. If you need to reset the identity number sequence, call the stored procedure
sp_iq_reset_identity. See sp_iq_reset_identity Procedure [page 746].

Privileges

Requires one of:

● You own the object


● TRUNCATE ANY TABLE system privilege
● ALTER ANY TABLE system privilege
● ALTER ANY OBJECT system privilege
● TRUNCATE object-level privilege on the table

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

For both temporary and base tables, you can execute TRUNCATE TABLE while other users have read access to
the table. This behavior differs from SAP SQL Anywhere, which requires exclusive access to truncate a base
table. SAP IQ table versioning ensures that TRUNCATE TABLE can occur while other users have read access;
however, the version of the table these users see depends on when the read and write transactions commit.

SAP IQ SQL Reference


1696 INTERNAL SQL Statements
Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

The following example delete all rows from the Sale table:

TRUNCATE TABLE Sale

Related Information

DELETE Statement [page 1424]


REVOKE System Privilege Statement [page 1635]

9.4.192 TRUNCATE TEXT INDEX Statement

Deletes the data in a MANUAL or an AUTO REFRESH text index.

 Syntax

TRUNCATE TEXT INDEX <text-index-name>


ON [ <owner>.]<table-name>

Parameters

ON

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, to alter the text configuration object for the text index to
change the stoplist, truncate the text index, change the text configuration object it refers to, and then refresh
the text index to populate it with new data.

SAP IQ SQL Reference


SQL Statements INTERNAL 1697
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.

The TRUNCATE TEXT INDEX requires exclusive access to the table. 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.

Privileges

Requires one of:

● You own the table


● ALTER ANY INDEX system privilege
● ALTER ANY OBJECT system privilege
● REFERENCES object-level privilege on the table

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Examples

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:

CREATE TEXT INDEX txt_index_manual ON GROUPO.MarketingInformation ( Description )


MANUAL REFRESH;
REFRESH TEXT INDEX txt_index_manual ON GROUPO.MarketingInformation;
TRUNCATE TEXT INDEX txt_index_manual ON GROUPO.MarketingInformation;

The truncated text index is repopulated with data the next time it is refreshed.

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1698 INTERNAL SQL Statements
9.4.193 UNION Statement

Combines the results of two or more select statements.

 Syntax

<select-without>-<order-by>
… UNION [ ALL ] <select-without>-<order-by>
… [ UNION [ ALL ] <select-without>-<order-by> ]…
… [ ORDER BY <integer> [ ASC | DESC ] [, …] ]

Parameters

ALL

The results of UNION ALL are the combined results of the component SELECT statements. The results of
UNION are the same as UNION ALL, except that duplicate rows are eliminated. Eliminating duplicates
requires extra processing, so UNION ALL should be used instead of UNION where possible.
ORDER BY

Only integers are allowed in the order by list. These integers specify the position of the columns to be
sorted.

Remarks

The results of several SELECT statements can be combined into a larger result using a UNION clause. The
component SELECT statements must each have the same number of items in the select list, and cannot
contain an ORDER BY clause. See FROM Clause.

If corresponding items in two select lists have different data types, SAP IQ chooses a data type for the
corresponding column in the result, and automatically converts the columns in each component SELECT
statement appropriately.

The column names displayed are the same column names that display for the first SELECT statement.

 Note

When SELECT statements include constant values and UNION ALL views but omit the FROM clause, use
iq_dummy to avoid errors. See FROM Clause for details.

Privileges

Requires SELECT object-level privilege for each component of the SELECT statements. See GRANT Object-
Level Privilege Statement [page 1502] for assistance with granting privileges

SAP IQ SQL Reference


SQL Statements INTERNAL 1699
Standards

● SQL – ISO/ANSI SQL compliant


● SAP database products – supported by SAP Adaptive Server Enterprise, which also supports a COMPUTE
clause.

Examples

This example lists all distinct surnames of employees and customers:

SELECT Surname
FROM Employees
UNION
SELECT Surname
FROM Customers

Related Information

FROM Clause [page 1483]


SELECT Statement [page 1659]
REVOKE System Privilege Statement [page 1635]

9.4.194 UPDATE Statement

Modifies existing rows of a single table, or a view that contains only one table.

 Syntax

UPDATE <table-name>
... SET [<column-name> = <expression>, ...
...[ FROM <table-expression> ]
...[ WHERE <search-condition> ]
...[ ORDER BY <expression> [ ASC | DESC ] , …]

<table-name> ::=
[ <owner>.]<table-name> [ [ AS ] <correlation-name> ]
| [ <owner>.]<view-name> [ [ AS ] <correlation-name> ]

<table-expression> ::=
<table-spec>
| <table-expression> <join-type> <table-spec> [ ON <condition> ]
| <table-expression>, ...

Go to:

SAP IQ SQL Reference


1700 INTERNAL SQL Statements
● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

SET

Use the SET clause to set column names or variables to the specified expression.

Use the SET clause to set the column to a computed column value by using this format:

SET <column-name> = <expression>, ...

Each specified column is set to the value of the expression. There are no restrictions on <expression>. If
<expression> is a <column-name>, then the previous value from that column is used.

If a column has a default defined, then use the SET clause to set a column to its default value.

You can also use the SET clause to assign a variable by using the following format:

SET @<variable-name> = <expression>, ...

The <owner> specification is only for use with database-scope variables.

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, then the
UPDATE statement updates the column value and leaves the variable unchanged. Variable and column
assignments can be combined in any order.
FROM

Allows tables to be updated based on 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>.

This statement illustrates a potential ambiguity in table names in UPDATE statements using a FROM
clause that contain table expressions, which use correlation names:

UPDATE table_1
SET column_1 = ...
FROM table_1 AS alias_1, table_2 AS alias_2
WHERE ...

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
SET column_1 = ...
FROM table_1 AS alias_1, table_1 AS alias_2

SAP IQ SQL Reference


SQL Statements INTERNAL 1701
WHERE ...

If the same table name in which you are updating rows is used in the FROM clause, they are considered to
reference the same table if one of the following is true:

● Both table references are not qualified by specifying a user ID


● Both table references are qualified by specifying a user ID
● Both table references are specified with a correlation name

In cases where the server cannot determine if the table references are identical, a SQL error appears. This
prevents the user from unintended semantics by updating unintended rows.
WHERE clause

If 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, with the FIRST or TOP clause, the
order can be significant.

You cannot use ordinal column numbers in the ORDER BY clause.

To use the ORDER BY clause, you cannot set the ansi_update_constraints option to Strict.

To update columns that appear in the ORDER BY clause, set the ansi_update_constraints option to Off.

Remarks

(back to top)

The table referenced in the UPDATE statement can be a base table or a temporary table.

Defaults on updates are honored for current user, user and current timestamp, and timestamp only.

Each named column is set to the value of the expression on the right-hand side of the equal sign. Even
<column-name> can be used in the expression—the old value is used.

The FROM clause can contain multiple tables with join conditions and returns all the columns from all the
tables specified and filtered by the join condition and/or WHERE condition.

Using the wrong join condition in a FROM clause causes unpredictable results. If the FROM clause specifies a
one-to-many join and the SET clause references a cell from the “many” side of the join, the cell is updated from
the first value selected. In other words, if the join condition causes multiple rows of the table to be updated per
row ID, the first row returned becomes the update result. For example:

UPDATE T1
SET T1.c2 = T2.c2
FROM T1 JOIN TO T2
ON T1.c1 = T2.c1

If table T2 has more than one row per T2.c1, results might be as follows:

T2.c1 T2.c2 T2.c3


1 4 3
1 8 1
1 6 4

SAP IQ SQL Reference


1702 INTERNAL SQL Statements
1 5 2

● With no ORDER BY clause, T1.c2 may be 4, 5, 6, 8.


● With ORDER BY T2.c3, T1.c2 is updated to 8.
● With ORDER BY T2.c3 DESC, T1.c2 is updated to 6.

SAP IQ rejects any UPDATE statement in which the table being updated is on the null-supplying side of an outer
join. In other words:

● In a left outer join, the table on the left side of the join cannot be missing any rows on joined columns.
● In a right outer join, the table on the right side of the join cannot be missing any rows on joined columns.
● In a full outer join, neither table can be missing any rows on joined columns.

For example, in this statement, table T1 is on the left side of a left outer join, and thus cannot contain be
missing any rows:

UPDATE T1
SET T1.c2 = T2.c4
FROM T1 LEFT OUTER JOIN T2
ON T1.rowid = T2.rowid

Normally, the order in which 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. If you
are not using the NUMBER(*) function, avoid using the ORDER BY clause, because the UPDATE statement
performs better without it.

In an UPDATE statement, if the NUMBER(*) function is used in the SET clause and the FROM clause specifies a
one-to-many join, NUMBER(*) generates unique numbers that increase, but do not increment sequentially due
to row elimination.

You can use the ORDER BY clause to control the result from an UPDATE statement when the FROM clause
contains multiple joined tables.

SAP IQ ignores the ORDER BY clause in the UPDATE statement and returns a message that the syntax is not
valid ANSI syntax.

The left side of each SET clause must be a column in a base table.

Views can be updated provided the SELECT statement defining the view does not contain a GROUP BY clause
or an aggregate function, or involve a UNION operation. The view should contain only one table.

Character strings inserted into tables are always stored in the case they are entered, regardless of whether the
database is case-sensitive or not. Thus a character data type column updated with the 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. The IQ server may return results in any combination of lowercase and
uppercase, so you cannot expect case-sensitive results in a database that is case-insensitive (CASE IGNORE).
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.

If the update violates any check constraints, the whole statement is rolled back.

SAP IQ supports scalar subqueries within the SET clause, for example:

UPDATE r
SET r.o= (SELECT MAX(t.o)
FROM t ... WHERE t.y = r.y),

SAP IQ SQL Reference


SQL Statements INTERNAL 1703
r.s= (SELECT SUM(x.s)
FROM x ...
WHERE x.x = r.x)
WHERE r.a = 10

SAP IQ supports DEFAULT column values in UPDATE statements. If a column has a DEFAULT value, this
DEFAULT value is used as the value of the column in any UPDATE statement that does not explicitly modify the
value for the column.

See CREATE TABLE Statement for details about updating IDENTITY/AUTOINCREMENT columns, which are
another type of DEFAULT column.

When updating database-scope variables using the SET clause, the setting does not persist between restarts of
the database, even though the variable does. When a database is restarted, the value of a database-scope
variable reverts to NULL or its default, if defined. The SYSDATABASEVARIABLE system view contains a list of all
database-scope variables and their default values.

You cannot update a database-scope variable owned by another user.

Privileges

(back to top)

Requires UPDATE object-level privilege on the columns being modified.

No privileges are required to update a database-scope variable you own. To update a database-scope variable
owned by PUBLIC, requires the UPDATE PUBLIC DATABASE VARIABLE system privilege.

See GRANT System Privilege Statement [page 1511] or GRANT Object-Level Privilege Statement [page 1502]
for assistance with granting privileges.

Standards

(back to top)

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – with these exceptions, syntax of the IQ UPDATE statement is generally
compatible with the SAP Adaptive Server Enterprise UPDATE statement. Syntax 1: SAP IQ supports
multiple tables with join conditions in the FROM clause.
Updates of remote tables are limited to SAP IQ syntax supported by CIS.

Examples

(back to top)

SAP IQ SQL Reference


1704 INTERNAL SQL Statements
● This example transfers employee Philip Chin (employee 129) from the sales department to the marketing
department:

UPDATE Employees
SET DepartmentID = 400
WHERE EmployeeID = 129;

● In this example, the Marketing Department (400) increases bonuses from 4% to 6% of each employee’s
base salary:

UPDATE Employees
SET bonus = base * 6/100
WHERE DepartmentID =400;

● In this example, each employee gets a pay increase with the department bonus:

UPDATE Employees
SET emp.Salary = emp.Salary + dept.bonus
FROM Employees emp, Departments dept
WHERE emp.DepartmentID = dept.DepartmentID;

● This example shows another way to give each employee a pay increase with the department bonus:

UPDATE Employees
SET emp.salary = emp.salary + dept.bonus
FROM Employees emp JOIN Departments dept
ON emp.DepartmentID = dept.DepartmentID;

Related Information

Row Limitation Clauses in SELECT Query Blocks [page 1669]


CREATE TABLE Statement [page 1377]
REVOKE System Privilege Statement [page 1635]

9.4.195 UPDATE (Positioned) Statement [ESQL] [SP]

Modifies the data at the current location of a cursor.

 Syntax

UPDATE <table-list>
SET <set-item>, ...
WHERE CURRENT OF <cursor-name>

<set-item> ::=
<column-name> [.<field-name>…] = <scalar-value>

SAP IQ SQL Reference


SQL Statements INTERNAL 1705
Parameters

cursor-name

Identifier or hostvar.
SET

The columns that are referenced in set-item must be in the base table that is updated. They cannot refer to
aliases, nor to columns from other tables or views. If the table you are updating is given a correlation name
in the cursor specification, you must use the correlation name in the SET clause. The expression on the
right side of the SET clause may reference columns, constants, variables, and expressions from the
SELECT clause of the query.
set-item

Expression cannot contain functions or expressions.


WHERE CURRENT OF

Avoid using ORDER BY in the WHERE CURRENT OF clause. The ORDER BY columns may be updated, but
the result set does not reorder. The results appear to fetch out of order and appear to be incorrect.

This example shows an UPDATE statement using WHERE CURRENT OF cursor:

UPDATE Employees SET surname = 'Jones'


WHERE CURRENT OF emp_cursor

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 cannot have been a
positioned DELETE statement.

The requested columns are set to the specified values for the row at the current row of the specified query. The
columns must be in the select list of the specified open cursor.

Changes effected by positioned UPDATE statements are visible in the cursor result set, except where client-side
caching prevents seeing these changes. Rows that are updated so that they no longer meet the requirements
of the WHERE clause of the open cursor are still visible.

Since SAP IQ does not support the CREATE VIEW... WITH CHECK OPTION, positioned UPDATE does not
support this option. The WITH CHECK OPTION clause does not allow an update that creates a row that is not
visible by the view.

A rowid column cannot be updated by a positioned UPDATE.

SAP IQ supports repeatedly updating the same row in the result set.

SAP IQ SQL Reference


1706 INTERNAL SQL Statements
Privileges

Requires UPDATE object-level permission on the columns being modified. See GRANT Object-Level Privilege
Statement [page 1502] for assistance with granting privileges

Standards

● The range of cursors that can be updated may contain vendor extensions to ISO/ANSI SQL grammar if the
ANSI_UPDATE_CONSTRAINTS option is set to OFF.
● Embedded SQL use is supported by Open Client/Open Server, and procedure and trigger use is supported
in SAP SQL Anywhere.

Related Information

DECLARE CURSOR Statement [ESQL] [SP] [page 1415]


DELETE Statement [page 1424]
DELETE (Positioned) Statement [ESQL] [SP] [page 1427]
UPDATE Statement [page 1700]
REVOKE System Privilege Statement [page 1635]

9.4.196 VALIDATE Statement

Validates the current database, or a single table, materialized view, or index in the IQ catalog (system) store.

 Caution

Perform the validation of a table or an entire database only while there are no connections that are making
changes to the database; otherwise, errors may be reported indicating some form of database corruption
even though no corruption actually exists.

 Syntax

Syntax 1 – Validates a Database

VALIDATE { CHECKSUM | DATABASE }

Syntax 2 – Validates Tables and Materialized Views

VALIDATE {
TABLE [ <owner>.]<table-name>
| MATERIALIZED VIEW [ <owner>.]<materialized-view-name> }
[ WITH EXPRESS CHECK ]

SAP IQ SQL Reference


SQL Statements INTERNAL 1707
Syntax 3 – Validates Indexes

VALIDATE {
INDEX <index-name>
| [ INDEX ] FOREIGN KEY <role-name>
| [ INDEX ] PRIMARY KEY }
ON [ <owner>.]<object-name>

<object-name> ::=
<table-name> | <materialized-view-name>

Syntax 4 – Validates Text Indexes

VALIDATE TEXT INDEX <index-name>


ON [ <owner>.]<table-name>

Parameters

CHECKSUM

Validates the checksum on each page of a database. The CHECKSUM clause 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. 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 CHECKSUM clause is not recommended for databases that have checksums disabled because it reads
the entire database from disk.
DATABASE

Ensures that the free map correctly identifies pages as either allocated or free and that no BLOBs have
been orphaned. The DATABASE clause 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 DATABASE clause 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.
TABLE

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. The TABLE clause also traverses all the
table's BLOBs, verifies BLOB allocation maps, and detects orphaned BLOBs. The TABLE clause 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 TABLE clause, like the
DATABASE clause, 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.

SAP IQ SQL Reference


1708 INTERNAL SQL Statements
INDEX

Performs the same operations as the TABLE clause 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.
TEXT INDEX

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

Privileges

Requires VALIDATE ANY OBJECT system privilege. See GRANT System Privilege Statement [page 1511] for
assistance with granting privileges.

Standards

ANSI SQL – compliance level: Transact-SQL extension

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.197 VALIDATE LDAP SERVER Statement

Validates changes to the settings of existing LDAP server configuration objects before applying them.

 Syntax

VALIDATE LDAP SERVER [ <ldapua-server-name> | <ldapua-server-attributes> ]


[ CHECK <userid> [ <user-dn-string> ] ]

<ldapua-server-attributes> ::=
SEARCH DN
URL { '<URL_string>' | NULL }
| ACCESS ACCOUNT { '<DN_string>' | NULL }

SAP IQ SQL Reference


SQL Statements INTERNAL 1709
| IDENTIFIED BY { '<password>' | NULL }
| IDENTIFIED BY ENCRYPTED { <encrypted-password> | NULL }
| AUTHENTICATION URL { '<URL_string>' | NULL }
| CONNECTION TIMEOUT <timeout_value>
| CONNECTION RETRIES <retry_value>
| TLS { ON | OFF }

Go to:

● Remarks
● Privileges
● Standards
● Examples

Parameters

(back to top)

ldapua-server-name

Identifies the LDAP server configuration object.


URL { 'URL_string' | NULL }

Identifies the host (by name or by IP address), port number, and the search to be performed for the DN
lookup for a given user ID. This value is validated for correct LDAP URL syntax before it is stored in the
ISYSLDAPSERVER system table. The maximum size for this string is 1024 bytes.
ACCESS ACCOUNT { 'DN_string' | NULL }

A user created on the LDAP server for use by SAP IQ, not a user within SAP IQ. The distinguished name
(DN) for this user is used to connect to the LDAP server. This user has permissions within the LDAP server
to search for DNs by user ID in the locations specified by the SEARCH DN URL. The maximum size for this
string is 1024 bytes.
IDENTIFIED BY { 'password' | NULL }

Provides the password associated with the ACCESS ACCOUNT user. The password is stored using
symmetric encryption on disk. Use the value NULL to clear the password and set it to none. The maximum
size of a clear text password is 255 bytes.
IDENTIFIED BY ENCRYPTED { encrypted-password | NULL }

Configures the password associated with the ACCESS ACCOUNT distinguished name in an encrypted
format. The binary value is the encrypted password and is stored on disk as is. Use the value NULL to clear
the password and set it to none. The maximum size of the binary is 289 bytes.
AUTHENTICATION URL { 'URL_string' | NULL }

Identifies the host (by name or IP address) and the port number of the LDAP server to use for
authentication of the user. This is the value defined for <URL_string> and is validated for correct LDAP
URL syntax before it is stored in ISYSLDAPSERVER system table. The DN of the user obtained from a prior
DN search and the user password bind a new connection to the authentication URL. A successful
connection to the LDAP server is considered proof of the identity of the connecting user. The maximum
size for this string is 1024 bytes.
CONNECTION TIMEOUT timeout_value

SAP IQ SQL Reference


1710 INTERNAL SQL Statements
Specifies the connection timeout from SAP IQ to the LDAP server for both DN searches and
authentication. This value is in milliseconds, with a default value of 10 seconds.
CONNECTION RETRIESretry_value

Specifies the number of retries on connections from SAP IQ to the LDAP server for both DN searches and
authentication. The valid range of values is 1 through 60, with a default value of 3.
TLS

Defines whether the TLS or Secure LDAP protocol is used for connections to the LDAP server for both DN
searches and authentication. When set to ON, the TLS protocol is used and the URL begins with "ldap://"
When set to OFF (or not specified), Secure LDAP protocol is used and the URL begins with “ldaps://”. When
using the TLS protocol, specify the database security option TRUSTED_CERTIFICATES_FILE with a file
name containing the certificate of the Certificate Authority (CA) that signed the certificate used by the
LDAP server.
CHECK userid

The userID whose existence is validated on the LDAP server.


user-dn-string

Compares a user's DN value with the user ID for verification purposes.

Remarks

(back to top)

This statement is useful for an administrator when setting up a new server to use LDAP user authentication,
and for diagnosing problems between the LDAP server configuration object and the external LDAP server. Any
connection made by the VALIDATE LDAP SERVER statement is temporary and is closed by the end of the
statement.

When validating the LDAP server configuration object by name, definitions from prior CREATE LDAP SERVER
and ALTER LDAP SERVER statements are used. Alternately, when <ldapua-server-attributes> are
specified instead of the LDAP server configuration object name, the specified attributes are validated. When
<ldapua-server-attributes> are specified, the URLs are parsed to identify syntax errors, and statement
processing stops is a syntax error is detected.

Whether using an LDAP server configuration object name or a successfully parsed set of <ldapua-server-
attributes>, a connection to the external LDAP server is attempted. If the parameter ACCESS ACCOUNT
and a password are specified, the values are used to establish the connection to the SEARCH DN URL. This is
the SEARCH DN URL, ACCESS ACCOUNT, and ACCESS ACCOUNT password.

When using the optional CHECK clause, the userID is used in the search to validate the existence of the user on
the external LDAP server. When the expected DN value for a given user is known, the value can be specified,
and is compared with the result of the search to determine success or failure.

Privileges

(back to top)

SAP IQ SQL Reference


SQL Statements INTERNAL 1711
Requires the MANAGE ANY LDAP SERVER system privilege. See GRANT System Privilege Statement [page
1511] for assistance with granting privileges.

Standards

(back to top)

ANSI SQL – compliance level: Transact-SQL extension

Examples

(back to top)

● This example assumes the apps_primary LDAP server configuration object was created as follows:

SET OPTION PUBLIC.login_mode = äStandard,LDAPUAä


CREATE LDAP SERVER apps_primary
SEARCH DN
URL 'ldap://my_LDAPserver:389/dc=MyCompany,dc=com??sub?cn=*'
ACCESS ACCOUNT 'cn=aseadmin, cn=Users, dc=mycompany, dc=com'
IDENTIFIED BY 'Secret99Password'
AUTHENTICATION URL 'ldap://my_LDAPserver:389/'
CONNECTION TIMEOUT 3000
WITH ACTIVATE

● This example validates the existence of a userID myusername by using the optional CHECK clause to
compare the userID to the expected user distinguished name (enclosed in quotation marks) on the
apps_primary LDAP server configuration object:

VALIDATE LDAP SERVER apps_primary


CHECK myusername 'cn=myusername,cn=Users,dc=mycompany,dc=com'

● In this example, the name of the LDAP server configuration object does not have to defined in the
VALIDATE LDAP SERVER statement if you include the search attributes:

VALIDATE LDAP SERVER


SEARCH DN
URL 'ldap://my_LDAPserver:389/dc=MyCompany,dc=com??sub?cn=*'
ACCESS ACCOUNT 'cn=aseadmin, cn=Users, dc=mycompany, dc=com'
IDENTIFIED BY 'Secret99Password'
AUTHENTICATION URL 'ldap://my_LDAPserver:389/'
CONNECTION TIMEOUT 3000
CHECK myusername 'cn=myusername,cn=Users,dc=mycompany,dc=com'

Related Information

REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1712 INTERNAL SQL Statements
9.4.198 WAITFOR Statement

Delays processing for the current connection for a specified amount of time or until a given time.

 Syntax

WAITFOR {
DELAY <time_value> | TIME <time_value> }
[ CHECK EVERY <integer> }
[ AFTER MESSAGE BREAK ]

Parameters

DELAY

Processing is suspended for the given <time_value> interval.


TIME

Processing is suspended until the server time reaches the <time_value> specified.
time_value

String.
CHECK EVERY integer

Controls how often the WAITFOR statement wakes up. By default, WAITFOR wakes up every 5 seconds. The
value is in milliseconds, and the minimum value is 250milliseconds.
AFTER MESSAGE BREAK

The WAITFOR statement can be used to wait for a message from another connection. In most cases, when
a message is received it is 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.

If the current server time is greater than the time specified, processing is suspended until that time on the
following day.

WAITFOR provides an alternative to the following statement, and might be useful for customers who choose not
to enable Java in the database:

call java.lang.Thread.sleep( <time_to_wait_in_millisecs> )

SAP IQ SQL Reference


SQL Statements INTERNAL 1713
In many cases, scheduled events are a better choice than using WAITFOR TIME, because scheduled events
execute on their own connection.

Privileges

None

Side Effects

The implementation of this statement uses a worker thread while it is waiting. This uses up one of the threads
specified by the -gn server command line option.

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – this statement is also implemented by SAP Adaptive Server Enterprise

Examples

● The following example waits for three seconds:

WAITFOR DELAY '00:00:03'

● The following example waits for 0.5 seconds (500 milliseconds):

WAITFOR DELAY '00:00:00:500'

● The following example waits until 8 p.m.:

WAITFOR TIME '20:00'

Related Information

CREATE EVENT Statement [page 1262]


REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1714 INTERNAL SQL Statements
9.4.199 WAITFOR SEMAPHORE statement

Decrements the counter associated with a semaphore.

 Syntax

WAITFOR SEMAPHORE [ <owner>.]<semaphore-name>


[ TIMEOUT <number-milliseconds> ]

Parameters

owner

The owner of the semaphore. <owner> can also be specified using an indirect identifier (for example,
`[@<variable-name>]`).
semaphore-name

The name of the semaphore. <semaphore-name> can also be specified using an indirect identifier (for
example, `[@<variable-name>]`).
TIMEOUT clause

Specify the duration of time, in milliseconds, to wait to decrement the counter associated with the
semaphore. If this clause is not specified, then the connection waits indefinitely until the count can be
decremented, or until an error is returned.

<number-milliseconds> can be specified using a variable (for example, TIMEOUT @timeout-value).


If <number-milliseconds> is set to a variable and the variable is NULL, the behavior is equivalent to not
specifying the clause.

Remarks

The WAITFOR SEMAPHORE statement decrements the counter associated with the semaphore. If the counter
is a positive integer, then the count is decremented and the statement completes. If the counter is 0, then the
connection waits until the counter is a positive integer, or until the duration specified by the TIMEOUT clause
passes, at which point an error is returned indicating the timeout.

An error is returned if the current connection is identified during deadlock detection while waiting on the
semaphore. An error is also returned if the semaphore is dropped.

If a connection that notified a semaphore is dropped or canceled, the counter decrement persists, so your
application needs to be able to address this case.

SAP IQ SQL Reference


SQL Statements INTERNAL 1715
Privileges

Requires one of:

● You own the semaphore


● UPDATE ANY MUTEX SEMAPHORE system privilege

See GRANT System Privilege Statement [page 1511] for assistance with granting privileges.

Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

 Example

The following statement decrements the counter for the license_counter semaphore by 1. If the semaphore
count is 0, then the statement waits indefinitely until the counter is incremented.

WAITFOR SEMAPHORE license_counter;

Related Information

CREATE SEMAPHORE statement [page 1358]


DROP SEMAPHORE statement [page 1452]
NOTIFY SEMAPHORE statement [page 1580]
CREATE SEMAPHORE statement [page 1358]
DROP SEMAPHORE statement [page 1452]
NOTIFY SEMAPHORE statement [page 1580]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1716 INTERNAL SQL Statements
9.4.200 WHENEVER Statement [ESQL]

Specifies error handling in an Embedded SQL program.

 Syntax

WHENEVER
{ SQLERROR | SQLWARNING | NOTFOUND }
… { GOTO <label> | STOP | CONTINUE | <C code;> }

Remarks

WHENEVER can be put anywhere in an Embedded SQL C program, and does not generate any code. The
preprocessor generates 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.

The default action is CONTINUE.

WHENEVER 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, WHENEVER is not used.
The WHENEVER statement causes the preprocessor to generate an <if ( SQLCODE )> test after each
statement.

 Note

The error conditions are in effect based on positioning in the C language source file and not on when the
statements are executed.

Privileges

None

Standards

● SQL – vendor extension to ISO/ANSI SQL grammar


● SAP database products – supported by Open Client/Open Server

SAP IQ SQL Reference


SQL Statements INTERNAL 1717
Examples

● The following example executes done when the NOTFOUND clause is met:

EXEC SQL WHENEVER NOTFOUND GOTO done;

● The following example uses the SQLERROR clause:

EXEC SQL WHENEVER SQLERROR


{
PrintError( &sqlca );
return( FALSE );
};

Related Information

REVOKE System Privilege Statement [page 1635]

9.4.201 WHILE Statement [T-SQL]

Provides repeated execution of a statement or compound statement.

 Syntax

WHILE <expression>
... <statement>

Remarks

The WHILE conditional affects the performance 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.

Privileges

None

SAP IQ SQL Reference


1718 INTERNAL SQL Statements
Standards

● SQL – Transact-SQL extension to ISO/ANSI SQL grammar


● SAP database products – supported by SAP Adaptive Server Enterprise

Examples

The following example shows a BREAK statement that breaks the WHILE loop, if the most expensive product
has a price less than $50. Otherwise, the loop continues until the average price is greater than $30:

WHILE (SELECT AVG(unit_price) FROM Products) < 30


BEGIN
DELETE FROM Products
WHERE UnitPrice = MAX(UnitPrice)
IF ( SELECT MAX(UnitPrice) FROM Products ) < 50
BREAK
END

Related Information

BEGIN … END Statement [page 1218]


REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


SQL Statements INTERNAL 1719
10 Database Options

Database options and Interactive SQL options customize and modify database behavior.

SAP IQ database options are divided into three classes: general, Transact-SQL compatibility, and Interactive
SQL.

In this section:

Introduction to Database Options [page 1720]


Database options control many aspects of database behavior including compatibility, error handling,
and concurrency.

Set a Database Option [page 1727]


You set options with the SET OPTION statement.

General Database Options [page 1728]


General database options is the class of options consisting of all options except Transact-SQL
compatibility options and Interactive SQL options.

Transact-SQL Compatibility Options [page 1733]


Transact-SQL compatibility options allow SAP IQ behavior to be compatible with SAP Adaptive Server
Enterprise, or to both support old behavior and allow ISO SQL92 behavior.

Interactive SQL Options [page 1735]


Interactive SQL options change how Interactive SQL interacts with the database.

Alphabetical List of Options [page 1736]


Descriptions of general, Transact-SQL compatibility, and Interactive SQL database options. Some
option names are followed by a class indicator in square brackets.

10.1 Introduction to Database Options

Database options control many aspects of database behavior including compatibility, error handling, and
concurrency.

For example, you can use database options for the purposes such as:

● Compatibility – lets you control how much like SAP Adaptive Server Enterprise your SAP IQ database
operates, and whether SQL that does not conform to SQL92 generates errors.
● Error handling – lets you control what happens when errors, such as dividing by zero or overflow errors,
occur.
● Concurrency and transactions – lets you control the degree of concurrency and details of COMMIT
behavior using options.

You set options with the SET OPTION statement, which has this general syntax:

SET [ EXISTING ] [ TEMPORARY ] OPTION

SAP IQ SQL Reference


1720 INTERNAL Database Options
... [ <userid>. | PUBLIC. ]<option-name> = [ <option-value> ]

Specify a user ID or role name to set the option only for that user or role. Every user belongs to the PUBLIC
role. If no user ID or role is specified, the option change is applied to the currently logged on user ID that issued
the SET OPTION statement.

For example, this statement applies a change to the PUBLIC user ID, a role to which all users belong:

SET OPTION Public.login_mode = standard

 Note

When you set an option to TEMPORARY without specifying a user or role, the new option value takes effect
only for the currently logged-on user ID that issued the statement, and only for the duration of the
connection. When you set an option to TEMPORARY for the PUBLIC role, the change remains in place for as
long as the database is running — when the database shuts down, TEMPORARY options for the PUBLIC role
revert back to their permanent value.

When you set an option without issuing the TEMPORARY keyword, the new option value is permanent for the
user or role who issued the statement.

See Scope and Duration of Database Options, Temporary Options, and SET OPTION Statement for more
information on temporary versus permanent option values.

The maximum length of <option-value>, when set to a string, is 127 bytes.

 Note

For all database options that accept integer values, SAP IQ truncates any decimal <option-value>
setting to an integer value. For example, the value 3.8 is truncated to 3.

 Caution

Do not change option settings while fetching rows.

In this section:

Current Option Settings [page 1722]


You can obtain a list of option settings, or the values of individual options, using sp_iqcheckoptions,
sa_conn_properties, the SET statement, SAP IQ Cockpit, and the SYSOPTIONS system view.

Scope and Duration of Database Options [page 1723]


You can set options at three levels of scope: public, user, and temporary.

Temporary Options [page 1724]


Adding the TEMPORARY keyword to the SET OPTION statement changes the duration of the change.

PUBLIC Options [page 1724]


PUBLIC options can be set for a user, user extended role, or the PUBLIC role. They can be set for self or
for another user or role.

SECURITY Options [page 1724]


SECURITY options are a special category of options, which are relevant to security of the database. It
can be set at user level or PUBLIC level depending on options.

SAP IQ SQL Reference


Database Options INTERNAL 1721
SYSTEM Options [page 1725]
SYSTEM options are a special category of options, which are relevant to security of the database. It can
be set at user level or PUBLIC level.

Delete an Option Setting [page 1725]


Omit the <option-value> to delete the option setting from the database.

Initial Option Settings [page 1726]


You can use stored procedures to configure the initial database option settings of a user.

Deprecated Database Options [page 1727]


See New Features Summary SAP IQ 16.1 for information about database options deprecated in this
release.

Related Information

Scope and Duration of Database Options [page 1723]


Temporary Options [page 1724]
SET OPTION Statement [page 1677]

10.1.1 Current Option Settings

You can obtain a list of option settings, or the values of individual options, using sp_iqcheckoptions,
sa_conn_properties, the SET statement, SAP IQ Cockpit, and the SYSOPTIONS system view.

● For the connected user, the sp_iqcheckoptions stored procedure displays a list of the current value and
the default value of database options that have been changed from the default. sp_iqcheckoptions
considers all SAP IQ and SAP SQL Anywhere database options. SAP IQ modifies some SAP SQL Anywhere
option defaults, and these modified values become the new default values. Unless the new SAP IQ default
value is changed again, sp_iqcheckoptions does not list the option.
sp_iqcheckoptions also lists server start-up options that have been changed from the default values.
When a DBA runs sp_iqcheckoptions, he or she sees all options set on a permanent basis for all roles
and users and sees temporary options set for DBA. Users who are not DBAs see their own temporary
options. All users see nondefault server start-up options.
The sp_iqcheckoptions stored procedure requires no parameters. In Interactive SQL, run:

sp_iqcheckoptions

The system table DBA.SYSOPTIONDEFAULTS contains all of the names and default values of the SAP IQ
and SAP SQL Anywhere options. You can query this table to see all option default values.
● Current option settings for your connection are available as a subset of connection properties. You can list
all connection properties using the sa_conn_properties system procedure:

call sa_conn_properties

● In Interactive SQL, the SET statement with no arguments lists the current setting of options:

SET

SAP IQ SQL Reference


1722 INTERNAL Database Options
● In SAP IQ Cockpit, right-click a database and select Options from the submenu.
● Query the SYSOPTIONS system view:

SELECT *
FROM SYSOPTIONS

This shows all PUBLIC values, and those USER values that have been explicitly set.
● Use the connection_property system function to obtain an individual option setting. For example, this
statement returns the value of the Ansinull option:

SELECT connection_property ('Ansinull')

10.1.2 Scope and Duration of Database Options

You can set options at three levels of scope: public, user, and temporary.

Temporary options take precedence over user and public settings. User-level options take precedence over
public settings. If you set a user-level option for the current user, the corresponding temporary option is set as
well.

Some options, such as COMMIT behavior, are database-wide in scope. Setting these options requires DBA
permissions. Other options, such as ISOLATION_LEVEL, can also be applied to only the current connection,
and need no special permissions.

Changes to option settings take place at different times, depending on the option. Changing a global option
such as RECOVERY_TIME takes place the next time the server is started. Some of the options that take effect
after the server is restarted:

● CACHE_PARTITIONS
● CHECKPOINT_TIME
● OS_FILE_CACHE_BUFFERING
● OS_FILE_CACHE_BUFFERING_TEMPDB
● PREFETCH_BUFFER_LIMIT
● PREFETCH_BUFFER_PERCENT
● RECOVERY_TIME
● SWEEPER_THREADS_PERCENT
● WASH_AREA_BUFFERS_PERCENT

Options that affect only the current connection generally take place immediately. For example, you can change
option settings in the middle of a transaction.

 Caution

Changing options when a cursor is open can lead to unreliable results. For example, changing
DATE_FORMAT might not change the format for the next row when a cursor is opened. Depending on the
way the cursor is being retrieved, it might take several rows before the change works its way to the user.

SAP IQ SQL Reference


Database Options INTERNAL 1723
10.1.3 Temporary Options

Adding the TEMPORARY keyword to the SET OPTION statement changes the duration of the change.

Ordinarily an option change is permanent: it will not change until it is explicitly changed using the SET OPTION
statement.

When the SET TEMPORARY OPTION statement is executed, the new option value takes effect only for the
current connection, and only for the duration of the connection.

When the SET TEMPORARY OPTION is used to set a PUBLIC option, the change is in place for as long as the
database is running. When the database is shut down, TEMPORARY options for the PUBLIC user ID revert back
to their permanent value.

Setting an option for the PUBLIC user ID temporarily offers a security advantage. For example, when the
LOGIN_MODE option is enabled, the database relies on the login security of the system on which it is running.
Enabling LOGIN_MODE temporarily means that a database relying on the security of a Windows domain will not
be compromised if the database is shut down and copied to a local machine. In this case, the LOGIN_MODE
option reverts to its permanent value, which could be Standard, a mode where integrated logins are not
permitted.

10.1.4 PUBLIC Options

PUBLIC options can be set for a user, user extended role, or the PUBLIC role. They can be set for self or for
another user or role.

Setting a PUBLIC option for the PUBLIC role sets the value for all users who do not already have the PUBLIC
option set at the user level. Setting a PUBLIC option for a user or user-extended role overrides any value
defined at the PUBLIC role level.

No system privilege is required to set a PUBLIC option for self, but does require the SET ANY PUBLIC OPTION
system privilege to set for another user, user-extended role, or PUBLIC role. PUBLIC options cannot be set for
user-defined roles. PUBLIC database options take effect immediately. No shut down and restart of the
database server is required for the change to take effect.

10.1.5 SECURITY Options

SECURITY options are a special category of options, which are relevant to security of the database. It can be
set at user level or PUBLIC level depending on options.

Changes to SECURITY database options take effect immediately. Requires the SET ANY SECURITY OPTION
system privilege to set SECURITY database options.

No shut down and restart of the database server is required for the change to take effect.

SAP IQ SQL Reference


1724 INTERNAL Database Options
10.1.6 SYSTEM Options

SYSTEM options are a special category of options, which are relevant to security of the database. It can be set
at user level or PUBLIC level.

Requires the SET ANY SYSTEM OPTION system privilege to set SYSTEM options. Takes effect immediately.

10.1.7 Delete an Option Setting

Omit the <option-value> to delete the option setting from the database.

If <option-value> is omitted, the specified option setting is deleted from the database. If <option-value>
is a personal option setting, the value reverts back to the PUBLIC setting. If a TEMPORARY option is deleted, the
option setting reverts back to the permanent setting.

For example, reset the ANSINULL option to its default value:

SET OPTION ANSINULL =

If you incorrectly type the name of an option when you are setting the option, the incorrect name is saved in the
SYSOPTION table. You can remove the incorrectly typed name from the SYSOPTION table by setting the option
PUBLIC with an equality after the option name and no value:

SET OPTION PUBLIC.a_mistyped_name=;

For example, if you set an option and incorrectly type the name, you can verify that the option was saved by
selecting from the SYSOPTIONS view:

SET OPTION PUBLIC.a_mistyped_name='ON';


SELECT * FROM SYSOPTIONS ORDER BY 2;

User Name Option Setting

PUBLIC a_mistyped_name ON

PUBLIC Abort_On_Error_File

PUBLIC Abort_On_Error_Line 0

PUBLIC Abort_On_Error_Number 0

...

Remove the incorrectly typed option by setting the option to no value, then verify that the option is removed:

SET OPTION PUBLIC.a_mistyped_name=;


SELECT * FROM SYSOPTIONS ORDER BY 2;

SAP IQ SQL Reference


Database Options INTERNAL 1725
User Name Option Setting

PUBLIC Abort_On_Error_File

PUBLIC Abort_On_Error_Line 0

PUBLIC Abort_On_Error_Number 0

...

If you remove the PUBLIC option and then try to add the USER option, an error message displays:
Couldn't execute the statement.
Invalid option 'chained' -- no PUBLIC setting exists
SQLCODE=-200?ODBC 3 State="42000"
Line 1,Column 29

To reset the PUBLIC option to the default value, explicitly set the default value:

SET OPTION PUBLIC.chained ='ON';

10.1.8 Initial Option Settings

You can use stored procedures to configure the initial database option settings of a user.

You can connect to SAP IQ through the TDS (tabular data stream) protocol (Open Client and jConnect for JDBC
connections) or through the SAP IQ protocol (ODBC, Embedded SQL).

If users have both TDS and the SAP IQ-specific protocol, you can configure their initial settings using stored
procedures. As it is shipped, SAP IQ uses this method to set Open Client connections and jConnect
connections to reflect default SAP Adaptive Server Enterprise behavior.

The initial settings are controlled using the LOGIN_PROCEDURE option, which is called after all the checks have
been performed to verify that the connection is valid. The LOGIN_PROCEDURE option names a stored
procedure to run when users connect. The default setting is to use the sp_login_environment system
stored procedure. You can specify a different stored procedure.

The sp_login_environment procedure checks to see if the connection is being made over TDS. If it is, it calls
the sp_tsql_environment procedure, which sets several options to new default values for the current
connection.

Related Information

LOGIN_PROCEDURE Option [page 1901]

SAP IQ SQL Reference


1726 INTERNAL Database Options
10.1.9 Deprecated Database Options

See New Features Summary SAP IQ 16.1 for information about database options deprecated in this release.

10.2 Set a Database Option

You set options with the SET OPTION statement.

Procedure

Issue the SET OPTION statement, which has this general syntax:

SET [ EXISTING ] [ TEMPORARY ] OPTION


... [ <userid>. | PUBLIC. ]<option-name> = [ <option-value> ]

Related Information

SET OPTION Statement [page 1677]


PREFETCH_FP_PERCENT Option [page 1953]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]
PREFETCH_HASH_PERCENT Option [page 1955]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]
PREFETCH_LOB_PERCENT Option [page 1956]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]
PREFETCH_TEXTPOST_PERCENT Option [page 1958]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


Database Options INTERNAL 1727
10.3 General Database Options

General database options is the class of options consisting of all options except Transact-SQL compatibility
options and Interactive SQL options.

In this section:

Data Extraction Options [page 1733]


The data extraction facility allows you to extract data from a database by redirecting the output of a
SELECT statement from the standard interface to one or more disk files or named pipes.

Related Information

Transact-SQL Compatibility Options [page 1733]


Interactive SQL Options [page 1735]
AES_ENCRYPT_HEADER_FORMAT Option [page 1752]
AFFINITY_AUTOEXCLUDE_TIMEOUT Option [page 1753]
AGGREGATION_PREFERENCE Option [page 1754]
ALLOW_SNAPSHOT_VERSIONING Option [page 1758]
ALLOW_READ_CLIENT_FILE Option [page 1757]
ANSI_UPDATE_CONSTRAINTS Option [page 1762]
ASE_BINARY_DISPLAY Option [page 1766]
ASE_FUNCTION_BEHAVIOR Option [page 1767]
AUDITING Option [Database] [page 1768]
auto_commit option [page 1769]
BASE_TABLES_IN_RLV_STORE Option [page 1771]
BIT_VECTOR_PINNABLE_CACHE_PERCENT Option [page 1772]
BLOCKING Option [page 1773]
BLOCKING_TIMEOUT Option [page 1774]
BT_PREFETCH_MAX_MISS Option [page 1775]
BT_PREFETCH_SIZE Option [page 1776]
BTREE_PAGE_SPLIT_PAD_PERCENT Option [page 1777]
CACHE_AFFINITY_PERCENT Option [page 1779]
CACHE_PARTITIONS Option [page 1780]
CHECKPOINT_TIME Option [page 1782]
CONVERSION_MODE Option [page 1789]
CONVERT_VARCHAR_TO_1242 Option [page 1796]
CIS_ROWSET_SIZE Option [page 1783]
COOPERATIVE_COMMIT_TIMEOUT Option [page 1797]
COOPERATIVE_COMMITS Option [page 1798]
CREATE_HG_AND_FORCE_PHYSICAL_DELETE Option [page 1799]
CREATE_HG_WITH_EXACT_DISTINCTS Option [page 1800]

SAP IQ SQL Reference


1728 INTERNAL Database Options
CURSOR_WINDOW_ROWS Option [page 1801]
DAS_TCP_TIMEOUT Option
DATE_FIRST_DAY_OF_WEEK Option [page 1803]
DATE_FORMAT Option [page 1804]
DATE_ORDER Option [page 1806]
DBCC_LOG_PROGRESS Option [page 1807]
DBCC_PINNABLE_CACHE_PERCENT Option [page 1808]
DEBUG_MESSAGES Option [page 1809]
DEDICATED_TASK Option [page 1811]
DEFAULT_DBSPACE Option [page 1812]
DEFAULT_DISK_STRIPING Option [page 1814]
DEFAULT_HAVING_SELECTIVITY_PPM Option [page 1815]
DEFAULT_KB_PER_STRIPE Option [page 1817]
DEFAULT_LIKE_MATCH_SELECTIVITY_PPM Option [page 1818]
DEFAULT_LIKE_RANGE_SELECTIVITY_PPM Option [page 1819]
DEFAULT_PROXY_TABLE_ROW_COUNT Option [page 1820]
DEFAULT_TABLE_UDF_ROW_COUNT Option [page 1821]
DELAYED_COMMIT_TIMEOUT Option [page 1822]
DELAYED_COMMITS Option [page 1823]
DISABLE_RI_CHECK Option [page 1824]
DQP_ENABLED Option [page 1827]
(Deprecated) DQP_ENABLED_OVER_NETWORK Option [page 1829]
EARLY_PREDICATE_EXECUTION Option [page 1833]
ENABLE_ASYNC_IO Option
ENABLE_LOB_VARIABLES Option [page 1835]
EXTENDED_JOIN_SYNTAX Option [page 1836]
FLOATING_POINT_ACCUMULATOR Option [page 1838]
FORCE_DROP Option [page 1840]
FORCE_NO_SCROLL_CURSORS Option [page 1841]
FORCE_UPDATABLE_CURSORS Option [page 1842]
FP_LOOKUP_SIZE Option [page 1843]
FP_LOOKUP_SIZE_PPM Option [page 1844]
FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]
FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
FP_PREDICATE_WORKUNIT_PAGES Option [page 1854]
FPL_EXPRESSION_MEMORY_KB Option [page 1855]
GARRAY_FILL_FACTOR_PERCENT Option [page 1856]
GARRAY_INSERT_PREFETCH_SIZE Option [page 1857]
GARRAY_PAGE_SPLIT_PAD_PERCENT Option [page 1858]
GARRAY_RO_PREFETCH_SIZE Option [page 1859]

SAP IQ SQL Reference


Database Options INTERNAL 1729
HASH_PINNABLE_CACHE_PERCENT Option [page 1860]
HASH_THRASHING_PERCENT Option [page 1861]
HG_DELETE_METHOD Option [page 1862]
HG_SEARCH_RANGE Option [page 1864]
HTTP_SESSION_TIMEOUT Option [page 1865]
IDENTITY_ENFORCE_UNIQUENESS Option [page 1866]
IDENTITY_INSERT Option [page 1867]
IN_SUBQUERY_PREFERENCE Option [page 1868]
INDEX_ADVISOR Option [page 1870]
INDEX_ADVISOR_MAX_ROWS Option [page 1872]
INDEX_PREFERENCE Option [page 1873]
INFER_SUBQUERY_PREDICATES Option [page 1875]
IQ_LOG_MAX_SIZE Option [page 1876]
IQ_POINT_IN_TIME_RECOVERY_LOGGING Option [page 1879]
IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL Option [page 1878]
IQGOVERN_MAX_PRIORITY Option [page 1882]
IQGOVERN_PRIORITY Option [page 1883]
IQGOVERN_PRIORITY_TIME Option [page 1884]
ISOLATION_LEVEL Option [page 1885]
JAVA_LOCATION Option [page 1886]
JAVA_VM_OPTIONS Option [page 1887]
JOIN_EXPANSION_FACTOR Option [page 1888]
JOIN_OPTIMIZATION Option [page 1889]
JOIN_PREFERENCE Option [page 1891]
JOIN_SIMPLIFICATION_THRESHOLD Option [page 1893]
LF_BITMAP_CACHE_KB Option [page 1894]
LOAD_ZEROLENGTH_ASNULL Option [page 1895]
LOG_CONNECT Option [page 1897]
LOG_CURSOR_OPERATIONS Option [page 1898]
LOG_DEADLOCKS Option [page 1899]
LOGIN_MODE Option [page 1900]
LOGIN_PROCEDURE Option [page 1901]
MAIN_RESERVED_DBSPACE_MB Option [page 1902]
MAX_CARTESIAN_RESULT Option [page 1903]
MAX_CLIENT_NUMERIC_PRECISION Option [page 1904]
MAX_CLIENT_NUMERIC_SCALE Option [page 1906]
MAX_CUBE_RESULT Option [page 1907]
MAX_CURSOR_COUNT Option [page 1908]
MAX_HASH_ROWS Option [page 1909]
MAX_IQ_THREADS_PER_CONNECTION Option [page 1910]
MAX_IQ_THREADS_PER_TEAM Option [page 1911]
MAX_JOIN_ENUMERATION Option [page 1912]
MAX_PARTITIONED_HASH_MB Option [page 1914]

SAP IQ SQL Reference


1730 INTERNAL Database Options
MAX_PREFIX_PER_CONTAINS_PHRASE Option [page 1915]
MAX_QUERY_PARALLELISM Option [page 1916]
MAX_QUERY_TIME Option [page 1917]
MAX_RV_REMOTE_TRANSFER_MB Option [page 1918]
MAX_STATEMENT_COUNT Option [page 1919]
MAX_TEMP_SPACE_PER_CONNECTION Option [page 1920]
MINIMIZE_STORAGE Option [page 1925]
MIN_NUMERIC_DIVISION_SCALE Option [page 1922]
min_password_length option [page 1922]
MIN_ROLE_ADMINS Option [page 1924]
MONITOR_OUTPUT_DIRECTORY Option [page 1926]
MPX_AUTOEXCLUDE_TIMEOUT Option [page 1928]
MPX_GTR_ENABLED Option [page 1930]
MPX_HEARTBEAT_FREQUENCY Option [page 1931]
MPX_IDLE_CONNECTION_TIMEOUT Option [page 1931]
MPX_LIVENESS_TIMEOUT Option [page 1932]
MPX_MAX_CONNECTION_POOL_SIZE Option [page 1933]
MPX_MAX_UNUSED_POOL_SIZE Option [page 1935]
MPX_MIPC_TIMEOUT Option [page 1935]
MPX_WORK_UNIT_TIMEOUT Option [page 1936]
NOEXEC Option [page 1939]
NON_ANSI_NULL_VARCHAR Option [page 1940]
NOTIFY_MODULUS Option [page 1942]
ODBC_DISTINGUISH_CHAR_AND_VARCHAR Option [page 1943]
ON_CHARSET_CONVERSION_FAILURE Option [page 1944]
POST_LOGIN_PROCEDURE Option [page 1947]
PRECISION Option [page 1949]
PREFETCH Option [page 1950]
PREFETCH_BUFFER_LIMIT Option [page 1951]
PREFETCH_BUFFER_PERCENT Option [page 1952]
PREFETCH_GARRAY_PERCENT Option [page 1954]
PREFETCH_SORT_PERCENT Option [page 1957]
PRESERVE_SOURCE_FORMAT Option [Database] [page 1959]
QUERY_DETAIL Option [page 1962]
QUERY_NAME Option [page 1963]
QUERY_PLAN Option [page 1964]
QUERY_PLAN_AFTER_RUN Option [page 1965]
QUERY_PLAN_AS_HTML Option [page 1966]
QUERY_PLAN_AS_HTML_DIRECTORY Option [page 1969]
QUERY_PLAN_MIN_TIME Option [page 1970]
QUERY_PLAN_TEXT_ACCESS Option [page 1971]
QUERY_PLAN_TEXT_CACHING Option [page 1973]
QUERY_ROWS_RETURNED_LIMIT Option [page 1974]

SAP IQ SQL Reference


Database Options INTERNAL 1731
QUERY_TEMP_SPACE_LIMIT Option [page 1975]
QUERY_TIMING Option [page 1976]
RECOVERY_TIME Option [page 1978]
reserved_connections option [page 1979]
RESERVED_KEYWORDS Option [page 1981]
RETURN_DATE_TIME_AS_STRING Option [page 1982]
REVERT_TO_V15_OPTIMIZER Option [page 1983]
ROUND_TO_EVEN Option [page 1984]
ROW_COUNT Option [page 1986]
RV_AUTO_MERGE Option [page 1987]
RV_AUTO_MERGE_EVAL_INTERVAL Option [page 1988]
RV_BLOCK_SIZE_ALLOCATION_STRATEGY Option [page 1989]
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE Option [page 1991]
RV_FIX_DATA_BLOCKSIZE Option [page 1992]
RV_INITIAL_FIX_DATA_BLOCKSIZE Option [page 1994]
RV_MAX_ACTIVE_SUBFRAGMENT_COUNT Option [page 1995]
RV_MAX_LOOKUP_MB Option [page 1996]
RV_MAX_TOKEN Option [page 1997]
RV_MERGE_NODE_MEMSIZE Option [page 1999]
RV_MERGE_TABLE_COMMIT_AGE Option [page 2000]
RV_MERGE_TABLE_DELPERCENT Option [page 2001]
RV_MERGE_TABLE_MEMPERCENT Option [page 2002]
RV_MERGE_TABLE_NUMROWS Option [page 2003]
RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZE Option [page 2004]
RV_RESERVED_DBSPACE_MB Option [page 2005]
RV_VAR_DATA_BLOCKSIZE Option [page 2006]
SCALE Option [page 2008]
SNAPSHOT_VERSIONING Option [page 2010]
SIGNIFICANTDIGITSFORDOUBLEEQUALITY Option [page 2009]
SORT_COLLATION Option [page 2011]
SORT_PINNABLE_CACHE_PERCENT Option [page 2013]
SUBQUERY_CACHING_PREFERENCE Option [page 2017]
SUBQUERY_FLATTENING_PERCENT Option [page 2019]
SUBQUERY_FLATTENING_PREFERENCE Option [page 2020]
SUBQUERY_PLACEMENT_PREFERENCE Option [page 2021]
SUPPRESS_TDS_DEBUGGING Option [page 2022]
SWEEPER_THREADS_PERCENT Option [page 2023]
TDS_EMPTY_STRING_IS_NULL Option [Database] [page 2025]
TEMP_EXTRACT_APPEND Option [page 2026]
TEMP_EXTRACT_BINARY Option [page 2027]
TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]
TEMP_EXTRACT_DIRECTORY Option [page 2031]
TEMP_EXTRACT_ESCAPE_QUOTES Option [page 2032]

SAP IQ SQL Reference


1732 INTERNAL Database Options
TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]
TEMP_EXTRACT_NAMEn Options [page 2040]
TEMP_EXTRACT_NULL_AS_EMPTY Option [page 2042]
TEMP_EXTRACT_NULL_AS_ZERO Option [page 2043]
TEMP_EXTRACT_QUOTE Option [page 2044]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
TEMP_EXTRACT_SIZEn Options [page 2050]
TEMP_EXTRACT_SWAP Option [page 2052]
TEMP_EXTRACT_VARYING Option [page 2053]
TEMP_RESERVED_DBSPACE_MB Option [page 2054]
TEMP_SPACE_LIMIT_CHECK Option [page 2055]
TEXT_DELETE_METHOD Option [page 2057]
TIME_FORMAT Option [page 2058]
TIMESTAMP_FORMAT Option [page 2059]
TOP_NSORT_CUTOFF_PAGES Option [page 2061]
TRIM_PARTIAL_MBC Option [page 2062]
TRUSTED_CERTIFICATES_FILE Option [page 2063]
USER_RESOURCE_RESERVATION Option [page 2065]
VERIFY_PASSWORD_FUNCTION Option [page 2066]
WASH_AREA_BUFFERS_PERCENT Option [page 2069]
WAIT_FOR_COMMIT Option [page 2068]
WD_DELETE_METHOD Option [page 2071]

10.3.1 Data Extraction Options

The data extraction facility allows you to extract data from a database by redirecting the output of a SELECT
statement from the standard interface to one or more disk files or named pipes.

The TEMP_EXTRACT_... database options are used to control the data extraction feature.

10.4 Transact-SQL Compatibility Options

Transact-SQL compatibility options allow SAP IQ behavior to be compatible with SAP Adaptive Server
Enterprise, or to both support old behavior and allow ISO SQL92 behavior.

For further compatibility with SAP ASE, you can set some of these options for the duration of the current
connection using the Transact-SQL SET statement instead of the SAP IQ SET OPTION statement.

In this section:

SAP IQ SQL Reference


Database Options INTERNAL 1733
Transact-SQL Option Settings for SAP ASE Compatibility [page 1734]
The default setting for some options differs from the SAP Adaptive Server Enterprise default setting. To
ensure compatible behavior, you should explicitly set the options.

Related Information

General Database Options [page 1728]


Interactive SQL Options [page 1735]
Alphabetical List of Options [page 1736]
ALLOW_NULLS_BY_DEFAULT Option [TSQL] [page 1756]
ANSI_CLOSE_CURSORS_ON_ROLLBACK Option [TSQL] [page 1759]
ANSI_PERMISSIONS Option [TSQL] [page 1760]
ANSI_SUBSTRING Option [TSQL] [page 1761]
ANSINULL Option [TSQL] [page 1764]
CHAINED Option [TSQL] [page 1781]
CLOSE_ON_ENDTRANS Option [TSQL] [page 1784]
CONTINUE_AFTER_RAISERROR Option [TSQL] [page 1786]
CONVERSION_ERROR Option [TSQL] [page 1787]
DIVIDE_BY_ZERO_ERROR Option [TSQL] [page 1825]
NEAREST_CENTURY Option [TSQL] [page 1938]
NON_KEYWORDS Option [TSQL] [page 1941]
ON_ERROR Option [Interactive SQL] [page 1945]
ON_TSQL_ERROR Option [TSQL] [page 1946]
QUOTED_IDENTIFIER Option [TSQL]
SET Statement [T-SQL] [page 1673]
SQL_FLAGGER_ERROR_LEVEL Option [TSQL] [page 2014]
SQL_FLAGGER_WARNING_LEVEL Option [TSQL] [page 2015]
STRING_RTRUNCATION Option [TSQL] [page 2016]
TSQL_VARIABLES Option [TSQL] [page 2064]

10.4.1 Transact-SQL Option Settings for SAP ASE


Compatibility

The default setting for some options differs from the SAP Adaptive Server Enterprise default setting. To ensure
compatible behavior, you should explicitly set the options.

When a connection is made using the Open Client or JDBC interfaces, some option settings are explicitly set
for the current connection to be compatible with SAP ASE.

Option ASE-Compatible Setting

ALLOW_NULLS_BY_DEFAULT OFF

SAP IQ SQL Reference


1734 INTERNAL Database Options
Option ASE-Compatible Setting

ANSINULL OFF

CHAINED OFF

CONTINUE_AFTER_RAISERROR ON

DATE_FORMAT YYYY-MM-DD

DATE_ORDER MDY

ESCAPE_CHARACTER OFF

ISOLATION_LEVEL 1

ON_TSQL_ERROR CONDITIONAL

QUOTED_IDENTIFIER OFF

TIME_FORMAT HH:NN:SS.SSS

TIMESTAMP_FORMAT YYYY-MM-DD HH:NN:SS.SSS

TSQL_VARIABLES OFF

10.5 Interactive SQL Options

Interactive SQL options change how Interactive SQL interacts with the database.

 Syntax

Syntax 1

SET [ TEMPORARY ] OPTION


... [ <userid>. | PUBLIC. ] <option-name> = [ <option-value> ]

Syntax 2

SET PERMANENT

Syntax 3

SET

Parameters

<userid> ::=
<identifier>, <string> or <host-variable>

<option-name> ::=
<identifier>, <string> or <host-variable>

SAP IQ SQL Reference


Database Options INTERNAL 1735
<option-value> ::=
<host-variable> (indicator allowed), <string>, <identifier>,
or <number>

Remarks

In Syntax 1, you cannot use the TEMPORARY keyword between the BEGIN and END keywords of a compound
statement.

In Syntax 2, SET PERMANENT stores all current Interactive SQL options in the SYSOPTIONS system table.
These settings are automatically established every time Interactive SQL is started for the current user ID.

Syntax 3 is used to display all of the current option settings. If there are temporary options set for Interactive
SQL or the database server, these are displayed; otherwise, the permanent option settings are displayed.

Related Information

General Database Options [page 1728]


Transact-SQL Compatibility Options [page 1733]
Alphabetical List of Options [page 1736]
DEFAULT_ISQL_ENCODING Option [Interactive SQL] [page 1816]
ON_ERROR Option [Interactive SQL] [page 1945]

10.6 Alphabetical List of Options

Descriptions of general, Transact-SQL compatibility, and Interactive SQL database options. Some option
names are followed by a class indicator in square brackets.

The database option class indicators are:

● [Interactive SQL] – The option changes how Interactive SQL interacts with the database.
● [TSQL] – The option allows SAP IQ behavior to be made compatible with SAP Adaptive Server Enterprise,
or to both support old behavior and allow ISO SQL92 behavior.

In this section:

AES_ENCRYPT_HEADER_FORMAT Option [page 1752]


Decrypts encrypted data upgraded or imported from databases prior to SAP IQ 15.4.

AFFINITY_AUTOEXCLUDE_TIMEOUT Option [page 1753]


The amount of time before SAP IQ removes a shut down node from the affinity map and reassigns its
partitions to other nodes.

AGGREGATION_PREFERENCE Option [page 1754]

SAP IQ SQL Reference


1736 INTERNAL Database Options
Controls the choice of algorithms for processing an aggregate.

ALLOW_NULLS_BY_DEFAULT Option [TSQL] [page 1756]


Controls whether new columns created without specifying either NULL or NOT NULL are allowed to
contain NULL values.

ALLOW_READ_CLIENT_FILE Option [page 1757]


Enables client-side data transfer.

ALLOW_SNAPSHOT_VERSIONING Option [page 1758]


Controls what values you can set the SNAPSHOT_VERSIONING option to. Applies to RLV-enabled tables
only.

ANSI_CLOSE_CURSORS_ON_ROLLBACK Option [TSQL] [page 1759]


Controls whether cursors that were opened WITH HOLD are closed when a ROLLBACK is performed.

ANSI_PERMISSIONS Option [TSQL] [page 1760]


Controls permissions checking for DELETE and UPDATE statements.

ANSI_SUBSTRING Option [TSQL] [page 1761]


Controls the behavior of the SUBSTRING (SUBSTR) function when negative values are provided for the
start or length parameters.

ANSI_UPDATE_CONSTRAINTS Option [page 1762]


Controls the range of updates that are permitted.

ANSINULL Option [TSQL] [page 1764]


Controls the interpretation of using = and != with NULL.

ASE_BINARY_DISPLAY Option [page 1766]


Specifies that the display of SAP IQ binary columns is consistent with the display of SAP Adaptive
Server Enterprise binary columns.

ASE_FUNCTION_BEHAVIOR Option [page 1767]


Specifies that output of SAP IQ functions, including INTTOHEX and HEXTOINT, is consistent with the
output of SAP Adaptive Server Enterprise functions.

AUDITING Option [Database] [page 1768]


Enables and disables auditing in the database.

auto_commit option [page 1769]


Causes an automatic commit after every request.

BASE_TABLES_IN_RLV_STORE Option [page 1771]


Registers newly created tables in the RLV store, enabling row-level versioning. RLV-enabled tables are
eligible for multiple writer concurrent access. You can override this setting at the table level using the
CREATE_TABLE statement.

BIT_VECTOR_PINNABLE_CACHE_PERCENT Option [page 1772]


Maximum percentage of a user’s temp memory that a persistent bit-vector object can pin.

BLOCKING Option [page 1773]


Controls the behavior in response to locking conflicts. BLOCKING is not supported on secondary nodes
of a multiplex.

BLOCKING_TIMEOUT Option [page 1774]


Controls the length of time a transaction waits to obtain a lock. BLOCKING_TIMEOUT is not supported
on secondary nodes of a multiplex.

BT_PREFETCH_MAX_MISS Option [page 1775]

SAP IQ SQL Reference


Database Options INTERNAL 1737
Controls the way SAP IQ determines whether to continue prefetching B-tree pages for a given query.

BT_PREFETCH_SIZE Option [page 1776]


Restricts the size of the read-ahead buffer for the High_Group B-tree.

BTREE_PAGE_SPLIT_PAD_PERCENT Option [page 1777]


Determines per-page fill factor during page splits for B-tree structures.

CACHE_AFFINITY_PERCENT Option [page 1779]


The maximum percentage of main buffer cache to use for affinity. Non-affinity data can use this area if
insufficient affinity data exists.

CACHE_PARTITIONS Option [page 1780]


Sets the number of partitions to be used for the main and temporary buffer caches.

CHAINED Option [TSQL] [page 1781]


Controls transaction mode in the absence of a BEGIN TRANSACTION statement.

CHECKPOINT_TIME Option [page 1782]


Set the maximum length of time, in minutes, that the database server runs without doing a checkpoint.

CIS_ROWSET_SIZE Option [page 1783]


Sets the number of rows that are returned from remote servers for each fetch.

CLOSE_ON_ENDTRANS Option [TSQL] [page 1784]


Controls closing of cursors at the end of a transaction.

COLLECT_IQ_PERFORMANCE_STATS option [page 1785]


Enables statement performance monitoring for SAP IQ queries.

CONTINUE_AFTER_RAISERROR Option [TSQL] [page 1786]


Controls behavior following a RAISERROR statement.

CONVERSION_ERROR Option [TSQL] [page 1787]


Controls reporting of data type conversion failures on fetching information from the database.

CONVERSION_MODE Option [page 1789]


Restricts implicit conversion between binary data types (BINARY, VARBINARY, and LONG BINARY) and
other non-binary data types (BIT, TINYINT, SMALLINT, INT, UNSIGNED INT, BIGINT, UNSIGNED
BIGINT, CHAR, VARCHAR, and LONG VARCHAR) on various operations. Also allows all explicit
conversions to be permitted as implicit conversions on various operations.

CONVERT_VARCHAR_TO_1242 Option [page 1796]


Converts pre-version 12.4.2 VARCHAR data to compressed format.

COOPERATIVE_COMMIT_TIMEOUT Option [page 1797]


Governs when a COMMIT entry in the transaction log is written to disk.

COOPERATIVE_COMMITS Option [page 1798]


Controls when commits are written to disk.

CREATE_HG_AND_FORCE_PHYSICAL_DELETE Option [page 1799]


Governs 16.1 tiered HG index delete behavior.

CREATE_HG_WITH_EXACT_DISTINCTS Option [page 1800]


Determines whether the database engine creates tiered HG or single-tiered HG indexes.

CURSOR_WINDOW_ROWS Option [page 1801]


Defines the number of cursor rows to buffer.

DATE_FIRST_DAY_OF_WEEK Option [page 1803]

SAP IQ SQL Reference


1738 INTERNAL Database Options
Determines the first day of the week.

DATE_FORMAT Option [page 1804]


Sets the format used for dates retrieved from the database.

DATE_ORDER Option [page 1806]


Controls the interpretation of date formats.

DBCC_LOG_PROGRESS Option [page 1807]


Reports the progress of the sp_iqcheckdb system stored procedure.

DBCC_PINNABLE_CACHE_PERCENT Option [page 1808]


Controls the percent of the cache used by the sp_iqcheckdb system stored procedure.

DEBUG_MESSAGES Option [page 1809]


Controls whether or not MESSAGE statements that include a DEBUG ONLY clause are executed.

DEDICATED_TASK Option [page 1811]


Dedicates a request handling task to handling requests from a single connection.

DEFAULT_DBSPACE Option [page 1812]


Changes the default dbspace where tables are created.

DEFAULT_DISK_STRIPING Option [page 1814]


Sets the default disk striping value for all dbspaces.

DEFAULT_HAVING_SELECTIVITY_PPM Option [page 1815]


Provides default selectivity estimates to the optimizer for most HAVING clauses in parts per million.

DEFAULT_ISQL_ENCODING Option [Interactive SQL] [page 1816]


Specifies the code page used by READ and OUTPUT statements.

DEFAULT_KB_PER_STRIPE Option [page 1817]


Sets an upper threshold in KB on the amount to write to a stripe before write operations move on to the
next stripe.

DEFAULT_LIKE_MATCH_SELECTIVITY_PPM Option [page 1818]


Provides default selectivity estimates (in parts per million) to the optimizer for most LIKE predicates.

DEFAULT_LIKE_RANGE_SELECTIVITY_PPM Option [page 1819]


Provides default selectivity estimates (in parts per million) to the optimizer for leading constant LIKE
predicates.

DEFAULT_PROXY_TABLE_ROW_COUNT Option [page 1820]


Enables you to override the default estimate of the number of rows to return from a proxy table.

DEFAULT_TABLE_UDF_ROW_COUNT Option [page 1821]


Enables you to override the default estimate of the number of rows to return from a table UDF (either a
C, C++, or Java table UDF).

DELAYED_COMMIT_TIMEOUT Option [page 1822]


Determines when the server returns control to an application following a COMMIT.

DELAYED_COMMITS Option [page 1823]


Determines when the server returns control to an application following a COMMIT.

DISABLE_RI_CHECK Option [page 1824]


Allows load, insert, update, or delete operations to bypass the referential integrity check, improving
performance.

DIVIDE_BY_ZERO_ERROR Option [TSQL] [page 1825]

SAP IQ SQL Reference


Database Options INTERNAL 1739
Controls the reporting of division by zero.

DML_OPTIONS90 Option [page 1826]


Controls whether zone maps are used querying to potentially improve performance.

DQP_ENABLED Option [page 1827]


Temporary database option DQP_ENABLED allows you to enable or disable distributed query processing
at the connection level.

(Deprecated) DQP_ENABLED_OVER_NETWORK Option [page 1829]


Temporary database option DQP_ENABLED_OVER_NETWORK allows you to enable or disable distributed
query processing over the network at the connection level.

DQP_OPTIONS13 Option [page 1830]


Enables TCP-based remote procedure calls for distributed query processing.

DQP_TCP_TIMEOUT Option [page 1832]


Specifies a timeout value (in seconds) that influences the system-calculated timeout value for
individual TCP remote procedure calls (RPCs) used in multiplex internal communications for
distributed query processing.

EARLY_PREDICATE_EXECUTION Option [page 1833]


Controls whether simple local predicates are executed before query optimization.

ENABLE_ASYNC_IO Option [page 1834]


Allows a DBA to enable or disable the asynchronous IO used by the RLV persistence log.

ENABLE_LOB_VARIABLES Option [page 1835]


Controls the data type conversion of large object variables.

EXTENDED_JOIN_SYNTAX Option [page 1836]


Controls whether queries with an ambiguous syntax for multi-table joins are allowed or are reported as
an error.

FILE_PREALLOCATE_SAMPLING_THRESHOLD Option [page 1837]


Speeds up dbfile creation time if the underlying file system is slow.

FLOATING_POINT_ACCUMULATOR Option [page 1838]


Controls which accumulator to use for SUM or AVG of floating-point numbers.

FORCE_DROP Option [page 1840]


Causes SAP IQ to leak, rather than reclaim, database disk space during a DROP command.

FORCE_NO_SCROLL_CURSORS Option [page 1841]


Forces all cursors to be non-scrolling.

FORCE_UPDATABLE_CURSORS Option [page 1842]


Controls whether cursors that have not been declared as updatable can be updated.

FP_LOOKUP_SIZE Option [page 1843]


Specifies the number of lookup pages and cache memory allocated for Lookup FP indexes in SAP IQ 15.
databases.

FP_LOOKUP_SIZE_PPM Option [page 1844]


Controls the amount of main buffer cache allocated to FP indexes in SAP IQ 15databases.

FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]


Limits the number of distinct values in columns that implicitly load as NBit FP.

FP_NBIT_ENFORCE_LIMITS Option [page 1847]

SAP IQ SQL Reference


1740 INTERNAL Database Options
Enforces sizing limits for explicit and implicit NBit columns.

FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]


Provides support for tokenized FP indexes similar to that available in SAP IQ 15.

FP_NBIT_LOOKUP_MB Option [page 1850]


Limits the total dictionary size per column for implicit NBit FP columns.

FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]


Sets a threshold for the total dictionary size for implicit NBit rollovers to Flat FP.

FP_PREDICATE_WORKUNIT_PAGES Option [page 1854]


Specifies degree of parallelism used in the default index.

FPL_EXPRESSION_MEMORY_KB Option [page 1855]


Controls the use of memory for the optimization of queries involving functional expressions against
columns having enumerated storage.

GARRAY_FILL_FACTOR_PERCENT Option [page 1856]


Specifies the percent of space on each HG garray page to reserve for future incremental inserts into
existing groups.

GARRAY_INSERT_PREFETCH_SIZE Option [page 1857]


Specifies number of pages used for prefetch.

GARRAY_PAGE_SPLIT_PAD_PERCENT Option [page 1858]


Determines per-page fill factor during page splits on the garray and specifies the percent of space on
each HG garray page to reserve for future incremental inserts.

GARRAY_RO_PREFETCH_SIZE Option [page 1859]


Specifies number of pages used for prefetch.

HASH_PINNABLE_CACHE_PERCENT Option [page 1860]


Controls the maximum percentage of a user’s temp memory that a hash object can pin.

HASH_THRASHING_PERCENT Option [page 1861]


Specifies the percent of hard disk I/Os allowed during the execution of a statement that includes a
query involving hash algorithms, before the statement is rolled back and an error message is reported.

HG_DELETE_METHOD Option [page 1862]


Specifies the algorithm used during a delete in a HG index.

HG_SEARCH_RANGE Option [page 1864]


Specifies the maximum number of Btree pages used in evaluating a range predicate in the HG index.

HTTP_SESSION_TIMEOUT Option [page 1865]


Specifies the amount of time, in minutes, that the client waits for an HTTP session to time out before
giving up.

IDENTITY_ENFORCE_UNIQUENESS Option [page 1866]


Creates a unique HG index on each IDENTITY/AUTOINCREMENT column, if the column is not already a
primary key.

IDENTITY_INSERT Option [page 1867]


Enables users to insert values into or to update an IDENTITY or AUTOINCREMENT column.

IN_SUBQUERY_PREFERENCE Option [page 1868]


Controls the choice of algorithms for processing an IN subquery.

INDEX_ADVISOR Option [page 1870]

SAP IQ SQL Reference


Database Options INTERNAL 1741
Generates messages suggesting additional column indexes that may improve performance of one or
more queries.

INDEX_ADVISOR_MAX_ROWS Option [page 1872]


Sets the maximum number of unique advice messages stored by the index advisor to max_rows.

INDEX_PREFERENCE Option [page 1873]


Controls the choice of indexes to use for queries.

INFER_SUBQUERY_PREDICATES Option [page 1875]


Controls the optimizer’s inference of additional subquery predicates.

IQ_LOG_MAX_SIZE Option [page 1876]


Sets the maximum size of the point-in-time recovery archive in megabytes.

IQ_LOG_THRESHOLD_SIZE Option [page 1877]


Configures the log file threshold for point-in-time recovery.

IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL Option [page 1878]


Sets a time interval between automatic backups of the point in time recovery logs.

IQ_POINT_IN_TIME_RECOVERY_LOGGING Option [page 1879]


Enables point-in-time recovery logging.

IQ_SYSTEM_MAIN_ALLOCATION_RATIO Option [page 1880]


Controls the divisor for allocation of space from IQ_SYSTEM_MAIN dbspace for use by a multiplex
writer.

IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD Option [page 1881]


Controls the amount of space reserved in IQ_SYSTEM_MAIN that is kept free for recovery operations.

IQGOVERN_MAX_PRIORITY Option [page 1882]


Limits the allowed IQGOVERN_PRIORITY setting.

IQGOVERN_PRIORITY Option [page 1883]


Assigns a priority to each query waiting in the -iqgovern queue.

IQGOVERN_PRIORITY_TIME Option [page 1884]


Limits the time a high priority query waits in the queue before starting.

ISOLATION_LEVEL Option [page 1885]


Controls the locking isolation level for catalog store tables.

JAVA_LOCATION Option [page 1886]


Specifies the path of the Java VM for the database.

JAVA_VM_OPTIONS Option [page 1887]


Specifies command line options that the database server uses when it launches the Java VM.

JOIN_EXPANSION_FACTOR Option [page 1888]


Controls how conservative the optimizer’s join result estimates are in unusually complex situations.

JOIN_OPTIMIZATION Option [page 1889]


Enables or disables the optimization of the join order.

JOIN_PREFERENCE Option [page 1891]


Controls the choice of algorithms when processing joins.

JOIN_SIMPLIFICATION_THRESHOLD Option [page 1893]


Controls the minimum number of tables being joined together before any join optimizer simplifications
are applied.

SAP IQ SQL Reference


1742 INTERNAL Database Options
LF_BITMAP_CACHE_KB Option [page 1894]
Specifies the amount of memory to use for a load into a LF index.

LOAD_ZEROLENGTH_ASNULL Option [page 1895]


Specifies LOAD statement behavior under certain conditions.

LOG_CONNECT Option [page 1897]


Controls logging of user connections.

LOG_CURSOR_OPERATIONS Option [page 1898]


Controls logging of cursor operations.

LOG_DEADLOCKS Option [page 1899]


Controls whether deadlock reporting is turned on or off.

LOGIN_MODE Option [page 1900]


Controls the use of standard, integrated, Kerberos, LDAP, and PAM logins for the database.

LOGIN_PROCEDURE Option [page 1901]


Specifies a login procedure that sets connection compatibility options at start-up.

MAIN_RESERVED_DBSPACE_MB Option [page 1902]


Controls the amount of space SAP IQ reserves in the IQ main store.

MAX_CARTESIAN_RESULT Option [page 1903]


Limits the number of rows resulting from a Cartesian join.

MAX_CLIENT_NUMERIC_PRECISION Option [page 1904]


Controls the maximum precision for numeric data sent to the client.

MAX_CLIENT_NUMERIC_SCALE Option [page 1906]


Controls the maximum scale for numeric data sent to the client.

MAX_CUBE_RESULT Option [page 1907]


Sets the maximum number of rows that the IQ optimizer considers for a GROUP BY CUBE operation.

MAX_CURSOR_COUNT Option [page 1908]


Specifies a resource governor to limit the maximum number of cursors that a connection can use at
once.

MAX_HASH_ROWS Option [page 1909]


Sets the maximum number of rows that the IQ optimizer considers for a hash algorithm.

MAX_IQ_THREADS_PER_CONNECTION Option [page 1910]


Controls the number of threads for each connection.

MAX_IQ_THREADS_PER_TEAM Option [page 1911]


Controls the number of threads allocated to perform a single operation (such as a LIKE predicate on a
column) executing within a connection.

MAX_JOIN_ENUMERATION Option [page 1912]


Controls the maximum number of tables to be optimized for join order after optimizer simplifications
have been applied.

MAX_PARTITIONED_HASH_MB Option [page 1914]


Sets an upper bound, expressed in megabytes, on the amount of temporary cache space that the
optimizer can assume will be available for hash-partitioned hash-based query operators.

MAX_PREFIX_PER_CONTAINS_PHRASE Option [page 1915]


Specifies the number of prefix terms allowed in a text search expression.

SAP IQ SQL Reference


Database Options INTERNAL 1743
MAX_QUERY_PARALLELISM Option [page 1916]
Sets upper bound for parallel execution of GROUP BY operations and for arms of a UNION.

MAX_QUERY_TIME Option [page 1917]


Sets a time limit so that the optimizer can disallow very long queries.

MAX_RV_REMOTE_TRANSFER_MB Option [page 1918]


Limit the volume of RLV-enabled table data allowed to be transferred from the RLV store when a
statement is executed on another node.

MAX_STATEMENT_COUNT Option [page 1919]


Specifies a resource governor to limit the maximum number of prepared statements that a connection
can use at once.

MAX_TEMP_SPACE_PER_CONNECTION Option [page 1920]


Limits temporary store space used per connection.

MIN_NUMERIC_DIVISION_SCALE Option [page 1922]


Controls the number of decimal places displayed for division operations on constant numeric values.

min_password_length option [page 1922]


Sets the minimum length for new passwords in the database.

MIN_ROLE_ADMINS Option [page 1924]


Configures of the minimum number of required administrators for all roles.

MINIMIZE_STORAGE Option [page 1925]


Minimizes use of disk space for newly created columns in SAP IQ 15 databases.

MONITOR_OUTPUT_DIRECTORY Option [page 1926]


Controls placement of output files for the IQ buffer cache monitor.

MPX_AUTOEXCLUDE_TIMEOUT Option [page 1928]


Timeout for autoexcluding a secondary node on the coordinator node. This option does not apply to the
designated failover node.

MPX_DAS_COMMUNICATION_ENABLED Option [page 1929]


Controls the state of initialization of the network interface during SAP IQ server startup. This option is
set on a MPX-coordinator or Simplex node.

MPX_GTR_ENABLED Option [page 1930]


Enables global transaction resiliency functionality on the coordinator. Global transaction resiliency
allows DML read-write transactions on writers to survive temporary communication failures between
coordinator and writer and temporary failure of coordinator due to server failure, shutdown, or failover.

MPX_HEARTBEAT_FREQUENCY Option [page 1931]


Interval until the heartbeat thread wakes and performs periodic operations, such as checking for
coordinator connectivity and cleaning up the connection pool on the secondary node. The heartbeat
thread maintains a dedicated internal connection from secondary server to coordinator.

MPX_IDLE_CONNECTION_TIMEOUT Option [page 1931]


Time after which an unused connection in the connection pool on a secondary node will be closed.

MPX_LIVENESS_TIMEOUT Option [page 1932]


Time, in seconds, before a heartbeat on a secondary server declares the coordinator offline if the
heartbeat fails to reconnect to the coordinator after the first disconnect. This option also determines
how long the coordinator keeps a global transaction in a suspended state.

MPX_MAX_CONNECTION_POOL_SIZE Option [page 1933]

SAP IQ SQL Reference


1744 INTERNAL Database Options
Maximum number of connections allowed in the connection pool on a secondary node.

MPX_MAX_UNUSED_POOL_SIZE Option [page 1935]


Maximum number of unused connections in the connection pool on a secondary node.

MPX_MIPC_TIMEOUT Option [page 1935]


Specifies the timeout, in seconds, for MIPC (multiplex interprocess communication) calls.

MPX_WORK_UNIT_TIMEOUT Option [page 1936]


Time, in seconds, before a multiplex DQP leader reassigns incomplete distributed work to another DQP
worker node.

NEAREST_CENTURY Option [TSQL] [page 1938]


Controls the interpretation of two-digit years, in string-to-date conversions.

NOEXEC Option [page 1939]


Generates the optimizer query plans instead of executing the plan.

NON_ANSI_NULL_VARCHAR Option [page 1940]


Controls whether zero-length VARCHAR data is treated as NULLs for insert, load, and update
operations.

NON_KEYWORDS Option [TSQL] [page 1941]


Turns off individual keywords, allowing their use as identifiers.

NOTIFY_MODULUS Option [page 1942]


Controls the default frequency of notify messages issued by certain commands.

ODBC_DISTINGUISH_CHAR_AND_VARCHAR Option [page 1943]


Controls how the SAP IQ ODBC driver describes CHAR columns.

ON_CHARSET_CONVERSION_FAILURE Option [page 1944]


Controls the action taken, if an error is encountered during character conversion.

ON_ERROR Option [Interactive SQL] [page 1945]


Controls the action taken if an error is encountered while executing statements in Interactive SQL.

ON_TSQL_ERROR Option [TSQL] [page 1946]


Controls error handling in stored procedures.

POST_LOGIN_PROCEDURE Option [page 1947]


Specifies a login procedure whose result set contains messages that are displayed by the client
application immediately after a user successfully logs in.

PRECISION Option [page 1949]


Specifies the maximum number of digits in the result of any decimal arithmetic, for queries on the
catalog store only.

PREFETCH Option [page 1950]


Allows you to turn fetching on or off or to use the ALWAYS value to prefetch the cursor results, even for
SENSITIVE cursor types and for cursors that involve a proxy table.

PREFETCH_BUFFER_LIMIT Option [page 1951]


Specifies the amount of memory used for prefetching.

PREFETCH_BUFFER_PERCENT Option [page 1952]


Specifies the percent of memory used for prefetching.

PREFETCH_FP_PERCENT Option [page 1953]

SAP IQ SQL Reference


Database Options INTERNAL 1745
Specifies the percent of prefetch resources for column data in all DML operations (insert, update,
delete, query).

PREFETCH_GARRAY_PERCENT Option [page 1954]


Specifies the percent of prefetch resources designated for performing all DML operations (insert,
update, delete, query) on HG indexes.

PREFETCH_HASH_PERCENT Option [page 1955]


Specifies the percent of prefetch resources in queries involving hash-based algorithms.

PREFETCH_LOB_PERCENT Option [page 1956]


Specifies the percent of prefetch resources in queries involving the character large object data type or
the binary large object data type.

PREFETCH_SORT_PERCENT Option [page 1957]


Specifies the percent of prefetch resources designated for sorting objects.

PREFETCH_TEXTPOST_PERCENT Option [page 1958]


Specifies the percent of prefetch resources in queries that use CONTAINS on columns with text indexes.

PRESERVE_SOURCE_FORMAT Option [Database] [page 1959]


Controls whether the original source definition of procedures, views, and event handlers is saved in
system files. If saved, the formatted source is saved in the column source in SYSTABLE,
SYSPROCEDURE, and SYSEVENT.

PROGRESS_MESSAGES Option [page 1960]


Controls whether progress messages are sent from the database server to the client.

QUERY_DETAIL Option [page 1962]


Specifies whether or not to include additional query information in the Query Detail section of the
query plan.

QUERY_NAME Option [page 1963]


Gives a name to an executed query in its query plan.

QUERY_PLAN Option [page 1964]


Specifies whether or not additional query plans are printed to the SAP IQ message file.

QUERY_PLAN_AFTER_RUN Option [page 1965]


Prints the entire query plan after query execution is complete.

QUERY_PLAN_AS_HTML Option [page 1966]


Generates graphical query plans in HTML format for viewing in a Web browser.

QUERY_PLAN_AS_HTML_DIRECTORY Option [page 1969]


Specifies the directory into which SAP IQ writes the HTML query plans.

QUERY_PLAN_MIN_TIME Option [page 1970]


Specifies a threshold for query execution. The post-query plan is generated only if query execution time
exceeds the threshold.

QUERY_PLAN_TEXT_ACCESS Option [page 1971]


Enables or prevents users from accessing query plans from the Interactive SQL client or from using
SQL functions to get plans.

QUERY_PLAN_TEXT_CACHING Option [page 1973]


Allows you to specify whether or not SAP IQ generates and caches IQ plans for queries executed by the
user.

QUERY_ROWS_RETURNED_LIMIT Option [page 1974]

SAP IQ SQL Reference


1746 INTERNAL Database Options
Sets the row threshold for rejecting queries based on estimated size of result set.

QUERY_TEMP_SPACE_LIMIT Option [page 1975]


Specifies the maximum estimated amount of temp space before a query is rejected.

QUERY_TIMING Option [page 1976]


Determines whether or not to collect specific timing statistics and display them in the query plan.

QUOTED_IDENTIFIER Option [TSQL] [page 1977]


Controls the interpretation of strings that are enclosed in double quotes.

RECOVERY_TIME Option [page 1978]


Sets the maximum length of time, in minutes, that the database server takes to recover from system
failure.

reserved_connections option [page 1979]


Controls the minimum number of concurrent connections that a database must reserve for standard
connections. This option is useful when your database server accepts HTTP/HTTPS connections.

RESERVED_KEYWORDS Option [page 1981]


Turns on individual keywords that are disabled by default.

RETURN_DATE_TIME_AS_STRING Option [page 1982]


Controls how a date, time, or timestamp value is passed to the client application when queried.

REVERT_TO_V15_OPTIMIZER Option [page 1983]


Setting this option ON forces the query optimizer to mimic SAP IQ 15.x behavior.

ROUND_TO_EVEN Option [page 1984]


Controls behavior of the SQL function ROUND when querying SAP IQ tables.

ROW_COUNT Option [page 1986]


Limits the number of rows returned from a query.

RV_AUTO_MERGE Option [page 1987]


This option enables or disables automatic merges of the RLV store into the IQ main store for row-level,
versioning-enabled tables.

RV_AUTO_MERGE_EVAL_INTERVAL Option [page 1988]


This option configures the evaluation period used to determine when an automated merge of the row-
level versioned (RLV) and IQ main stores should occur.

RV_BLOCK_SIZE_ALLOCATION_STRATEGY Option [page 1989]


Defines the strategy to use for subsequent array allocation for fixed length datatype columns in the
RLV in-memory store.

RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE Option [page 1991]


Defines the delta size increase size (in bytes) for subsequent array allocation for fixed length datatype
columns in the RLV in-memory store. The nth block size is the value of (n-1)th block size +
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE. This is used by the Delta Increase allocation
strategy.

RV_FIX_DATA_BLOCKSIZE Option [page 1992]


Defines the size (in bytes) of every subsequent array allocation for fixed length datatype columns in the
RLV in-memory store. It is used by the Constant allocation strategy.

RV_INITIAL_FIX_DATA_BLOCKSIZE Option [page 1994]


Defines the size (in bytes) of the first array allocation for fixed length datatype columns in the RLV in-
memory store. It is used as a starting size by all fixed block allocation strategies.

SAP IQ SQL Reference


Database Options INTERNAL 1747
RV_MAX_ACTIVE_SUBFRAGMENT_COUNT Option [page 1995]
This value maximizes utilization of the number of cores on the machine.

RV_MAX_LOOKUP_MB Option [page 1996]


This value limits the total in-memory dictionary size for implicit NBit FP columns.

RV_MAX_TOKEN Option [page 1997]


This value provides an upper bound for the number of NBit tokens used in the in-memory dictionary.

RV_MERGE_NODE_MEMSIZE Option [page 1999]


Sets the percentage of total RLV memory size as a merge threshold for the node.

RV_MERGE_TABLE_COMMIT_AGE Option [page 2000]


Triggers an RLV merge to occur based on a time interval since the last commit.

RV_MERGE_TABLE_DELPERCENT Option [page 2001]


Defines the threshold of deleted and committed table rows to trigger a merge expressed as a
percentage. If the number of deleted rows used surpasses the threshold, a merge occurs.

RV_MERGE_TABLE_MEMPERCENT Option [page 2002]


Sets the percentage of memory used as a merge threshold for an RLV-enabled table. If the memory
used surpasses the threshold, a merge occurs.

RV_MERGE_TABLE_NUMROWS Option [page 2003]


Sets the number of rows used as a merge threshold for an RLV-enabled table. If the number of rows
used surpasses the threshold, a merge occurs.

RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZE Option [page 2004]


Defines the percentage size increase for subsequent array allocation for fixed length datatype columns
in the RLV in-memory store. The nth block size is the value of (n-1)th block size + ((n-1)th
block size * RV_PERCENT_INCREASE_IN_FIX_DTA_BLOCKSIZE / 100). This is used by the
Percent Increase allocation strategy.

RV_RESERVED_DBSPACE_MB Option [page 2005]


A portion of the RLV store must be reserved for memory used by data structures during critical
operations.

RV_VAR_DATA_BLOCKSIZE Option [page 2006]


Defines the size (in bytes) of every array allocation for variable length datatype columns in the RLV in-
memory store.

SCALE Option [page 2008]


Specifies the minimum number of digits after the decimal point when an arithmetic result is truncated
to the maximum PRECISION, for queries on the catalog store only.

SIGNIFICANTDIGITSFORDOUBLEEQUALITY Option [page 2009]


Specifies the number of significant digits to the right of the decimal in exponential notation that are
used in equality tests between two complex arithmetic expressions.

SNAPSHOT_VERSIONING Option [page 2010]


Controls whether RLV-enabled tables are accessed using single-writer table-level versioning, or
multiple writer row-level versioning. Applies to RLV-enabled tables only.

SORT_COLLATION Option [page 2011]


Allows implicit use of the SORTKEY function on ORDER BY expressions.

SORT_PINNABLE_CACHE_PERCENT Option [page 2013]


Specifies the maximum percentage of currently available buffers a sort object tries to pin.

SAP IQ SQL Reference


1748 INTERNAL Database Options
SQL_FLAGGER_ERROR_LEVEL Option [TSQL] [page 2014]
Controls the behavior in response to any SQL code that is not part of the specified standard.

SQL_FLAGGER_WARNING_LEVEL Option [TSQL] [page 2015]


Controls the response to any SQL that is not part of the specified standard.

STRING_RTRUNCATION Option [TSQL] [page 2016]


Determines whether an error is raised when an INSERT or UPDATE truncates a CHAR or VARCHAR string.

SUBQUERY_CACHING_PREFERENCE Option [page 2017]


Controls which algorithm to use for processing correlated subquery predicates.

SUBQUERY_FLATTENING_PERCENT Option [page 2019]


Allows the user to change the threshold at which the optimizer decides to transform scalar subqueries
into joins.

SUBQUERY_FLATTENING_PREFERENCE Option [page 2020]


Allows a user to override the decisions of the optimizer when transforming (flattening) scalar or
EXISTS subqueries into joins.

SUBQUERY_PLACEMENT_PREFERENCE Option [page 2021]


Controls the placement of correlated subquery predicate operators within a query plan.

SUPPRESS_TDS_DEBUGGING Option [page 2022]


Determines whether TDS debugging information appears in the server window.

SWEEPER_THREADS_PERCENT Option [page 2023]


Specifies the percentage of SAP IQ threads used to sweep out buffer caches.

TABLE_UDF_ROW_BLOCK_CHUNK_SIZE_KB Option [page 2024]


Controls the size, in kilobytes, for server-allocated row blocks. Row blocks are used by Table UDFs and
TPFs.

TDS_EMPTY_STRING_IS_NULL Option [Database] [page 2025]


Controls whether empty strings are returned as NULL or a string containing one blank character for
TDS connections.

TEMP_EXTRACT_APPEND Option [page 2026]


Specifies that any rows extracted by the data extraction facility are added to the end of an output file.

TEMP_EXTRACT_BINARY Option [page 2027]


In combination with the TEMP_EXTRACT_SWAP option, specifies the type of extraction performed by
the data extraction facility.

TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]


Specifies the delimiter between columns in the output of the data extraction facility for an ASCII
extraction.

TEMP_EXTRACT_COMPRESS Option [page 2030]


Writes the output file for exports in gzip format. This results in significant savings of disk space when
exporting tables.

TEMP_EXTRACT_DIRECTORY Option [page 2031]


Controls whether a user is allowed to use the data extraction facility. Also controls the directory into
which temp extract files are placed and overrides a directory path specified in the
TEMP_EXTRACT_NAMEn options.

TEMP_EXTRACT_ESCAPE_QUOTES Option [page 2032]

SAP IQ SQL Reference


Database Options INTERNAL 1749
Specifies whether all quotes in fields containing quotes are escaped in the output of the data extraction
facility for an ASCII extraction.

TEMP_EXTRACT_FILE_EXTENSION Option [page 2034]


Sets the file name extension for the generated output file of the data parallel extraction facility. When
you specify the TEMP_EXTRACT_FILE_EXTENSION option, each file name generated becomes
<prefix> <thread_ID>_<filecount>.<file extension>.

TEMP_EXTRACT_FILE_PREFIX Option [page 2035]


Sets the prefix of file name for the generated output file of the data parallel extraction facility.
<thread_ID> starts from 1. <filecount> starts from 1 for each thread ID. The<filecount> part
increments when the size of the output file reaches the file size limit specified by the
TEMP_EXTRACT_SIZE option.

TEMP_EXTRACT_GZ_COMPRESSION_LEVEL Option [page 2036]


The compression level balances compression with speed when the TEMP_EXTRACT_COMPRESS option
is set to ON.

TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]


Adds a prefix field of specified length (byte) for a varchar or varbinary column in the generated output
file. This PREFIX field in the extract file holds the length of the column data.

TEMP_EXTRACT_MAX_PARALLEL_DEGREE Option [page 2039]


Sets the maximum parallel degree for the data extraction facility. The
TEMP_EXTRACT_MAX_PARALLEL_DEGREE option limits the maximum number of threads that run in
parallel to extract data.

TEMP_EXTRACT_NAMEn Options [page 2040]


Specifies the names of the output files or named pipes used by the data extraction facility. There are
eight options: TEMP_EXTRACT_NAME1 through TEMP_EXTRACT_NAME8.

TEMP_EXTRACT_NULL_AS_EMPTY Option [page 2042]


Controls the representation of null values in the output of the data extraction facility for an ASCII
extraction.

TEMP_EXTRACT_NULL_AS_ZERO Option [page 2043]


Controls the representation of null values in the output of the data extraction facility for an ASCII
extraction.

TEMP_EXTRACT_QUOTE Option [page 2044]


Specifies the string to be used as the quote to enclose fields in the output of the data extraction facility
for an ASCII extraction, when either the TEMP_EXTRACT_QUOTES option or the
TEMP_EXTRACT_QUOTES_ALL option is set ON.

TEMP_EXTRACT_QUOTES Option [page 2046]


Specifies that string fields are enclosed in quotes in the output of the data extraction facility for an
ASCII extraction.

TEMP_EXTRACT_QUOTES_ALL Option [page 2047]


Specifies that all fields are enclosed in quotes in the output of the data extraction facility for an ASCII
extraction.

TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]


Specifies the delimiter between rows in the output of the data extraction facility for an ASCII extraction.

TEMP_EXTRACT_SIZE Option [page 2049]

SAP IQ SQL Reference


1750 INTERNAL Database Options
Sets the maximum size (KB) of the corresponding output files generated by the parallel data extraction
facility.

TEMP_EXTRACT_SIZEn Options [page 2050]


Specifies the maximum sizes of the corresponding output files used by the data extraction facility.

TEMP_EXTRACT_SWAP Option [page 2052]


In combination with the TEMP_EXTRACT_BINARY option, specifies the type of extraction performed by
the data extraction facility.

TEMP_EXTRACT_VARYING Option [page 2053]


Used in conjunction with TEMP_EXTRACT_LENGTH_PREFIX, the TEMP_EXTRACT_VARYING option
outputs varchar or varbinary column data in a variable-length format in the extracted file. The prefix
field specified by TEMP_EXTRACT_LENGTH_PREFIX option holds the length of column data.

TEMP_RESERVED_DBSPACE_MB Option [page 2054]


Controls the amount of space SAP IQ reserves in the temporary IQ store.

TEMP_SPACE_LIMIT_CHECK Option [page 2055]


Checks for catalog store temporary space on a per connection basis.

TEXT_DELETE_METHOD Option [page 2057]


Specifies the algorithm used during a delete in a TEXT index.

TIME_FORMAT Option [page 2058]


Sets the format used for times retrieved from the database.

TIMESTAMP_FORMAT Option [page 2059]


Sets the format used for timestamps retrieved from the database.

TOP_NSORT_CUTOFF_PAGES Option [page 2061]


Sets the result size threshold for TOP N algorithm selection.

TRIM_PARTIAL_MBC Option [page 2062]


Allows automatic trimming of partial multibyte character data.

TRUSTED_CERTIFICATES_FILE Option [page 2063]


Specifies the trust relationship for outbound Transport Layer Security (TLS) connections made by
LDAP User Authentication, INC, DAS INC, and MIPC connections.

TSQL_VARIABLES Option [TSQL] [page 2064]


Controls whether the @ sign can be used as a prefix for Embedded SQL host variable names.

USER_RESOURCE_RESERVATION Option [page 2065]


Adjusts memory use for the number of current users.

VERIFY_PASSWORD_FUNCTION Option [page 2066]


Specifies a user-supplied authentication function that can be used to implement password rules.

WAIT_FOR_COMMIT Option [page 2068]


Determines when foreign key integrity is checked as data is manipulated.

WASH_AREA_BUFFERS_PERCENT Option [page 2069]


Specifies the percentage of the buffer caches above the wash marker.

WD_DELETE_METHOD Option [page 2071]


Specifies the algorithm used during a delete in a WD index.

SAP IQ SQL Reference


Database Options INTERNAL 1751
Related Information

Introduction to Database Options [page 1720]


General Database Options [page 1728]
Transact-SQL Compatibility Options [page 1733]
Interactive SQL Options [page 1735]

10.6.1 AES_ENCRYPT_HEADER_FORMAT Option

Decrypts encrypted data upgraded or imported from databases prior to SAP IQ 15.4.

Importing or upgrading data encrypted in a previous version of SAP IQ to a later release can result in
decryption errors. Use this option to ensure that your encrypted data is decrypted properly during an import or
upgrade.

Allowed Values

● -1 – decrypts data encrypted in the same format as the current release


● 127 – decrypts upgraded or imported 12.7 data
● 153 – decrypts upgraded or imported 15.3 data to the next patch level or release
● 154 – decrypts upgraded or imported 15.4 data to the next patch level or release
● 1000 – decrypts data upgraded or imported in a release independent format (patched 15.x or 16.x data)

Default

-1

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1752 INTERNAL Database Options
Remarks

Allowed values identify the source release.

Use the following to set this option:

SET OPTION public.AES_ENCRYPT_HEADER_FORMAT = '<VAL>'

In some cases, SAP IQ may not be able to read encrypted data in a database upgraded from a previous release:
There was an error reading the results of the SQL statement.
The displayed results may be incorrect or incomplete.
Decryption error: Incorrect CAST type varchar(16) for decrypt data of
type numeric(16,0).
-- (hos_encrypt.cxx 359)
SQLCODE=-1001064, ODBC 3 State="HY000"
This issue applies to encrypted data upgraded or imported from databases prior to SAP IQ 15.4. If this error
occurs, contact technical support. Diagnosing encryption issues requires the assistance of an SAP IQ product
support engineer. Incorrect usage can result in decryption errors.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.2 AFFINITY_AUTOEXCLUDE_TIMEOUT Option

The amount of time before SAP IQ removes a shut down node from the affinity map and reassigns its partitions
to other nodes.

Allowed Values

0 to 10080 minutes (1 week)

Default

10 minutes

SAP IQ SQL Reference


Database Options INTERNAL 1753
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

The amount of time before SAP IQ removes a shut down node from the affinity map and reassigns its partitions
to other nodes.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.3 AGGREGATION_PREFERENCE Option

Controls the choice of algorithms for processing an aggregate.

Allowed Values

-6 to 6

● 0 – lets the optimizer choose.


● 1 – prefers aggregation with a sort.
● 2 – prefers aggregation using IQ indexes.
● 3 – prefers aggregation with a hash.
● 4 – prefers aggregation with a distinct/grouping sort.
● 5 – prefers aggregation with a sort if grouping columns include all the partitioning keys of a hash
partitioned table.
● 6 – prefers aggregation with a hash if grouping columns include all the partitioning keys of a hash
partitioned table.
● -1 – avoids aggregation with a sort.
● -2 – avoids aggregation using IQ indexes.
● -3 – avoids aggregation with a hash.
● -4 – avoids aggregation with a distinct/grouping sort.

SAP IQ SQL Reference


1754 INTERNAL Database Options
● -5 – avoids aggregation with a sort if grouping columns include all the partitioning keys of a hash
partitioned table.
● -6 – avoids aggregation with a hash if grouping columns include all the partitioning keys of a hash
partitioned table.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For aggregation (GROUP BY, DISTINCT, SET functions) within a query, the SAP IQ optimizer has a choice of
several algorithms for processing the aggregate. AGGREGATION_PREFERENCE lets you override the costing
decision of the optimizer when choosing the algorithm. the option does not override internal rules that
determine whether an algorithm is legal within the query engine.

This option is normally used for internal testing and for manually tuning queries that the optimizer does not
handle well. Only experienced DBAs should use it. Inform SAP Technical Support, if you need to set
AGGREGATION_PREFERENCE, as setting this option might mean that a change to the optimizer may be
appropriate.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1755
10.6.4 ALLOW_NULLS_BY_DEFAULT Option [TSQL]

Controls whether new columns created without specifying either NULL or NOT NULL are allowed to contain
NULL values.

Allowed Values

ON, OFF

Default

● ON
● OFF for Open Client and JDBC connections

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The ALLOW_NULLS_BY_DEFAULT option is included for Transact-SQL compatibility.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1756 INTERNAL Database Options
10.6.5 ALLOW_READ_CLIENT_FILE Option

Enables client-side data transfer.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SECURITY OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Enable this option to read from files on a client computer, for example by using the READ_CLIENT_FILE
function.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1757
10.6.6 ALLOW_SNAPSHOT_VERSIONING Option

Controls what values you can set the SNAPSHOT_VERSIONING option to. Applies to RLV-enabled tables only.

Allowed Values

● any – no restrictions on what the SNAPSHOT_VERSIONING option can be set to.


● row-level – restricts setting the SNAPSHOT_VERSIONING option to the value row-level only.
● table-level – restricts setting the SNAPSHOT_VERSIONING option to the value table-level only.

Default

any

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Related Information

SNAPSHOT_VERSIONING Option [page 2010]


SNAPSHOT_VERSIONING Option [page 2010]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1758 INTERNAL Database Options
10.6.7 ANSI_CLOSE_CURSORS_ON_ROLLBACK Option
[TSQL]

Controls whether cursors that were opened WITH HOLD are closed when a ROLLBACK is performed.

Allowed Values

ON

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The ANSI SQL/3 standard requires all cursors be closed when a transaction is rolled back. This option forces
that behavior and cannot be changed. The CLOSE_ON_ENDTRANS option overrides this option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1759
10.6.8 ANSI_PERMISSIONS Option [TSQL]

Controls permissions checking for DELETE and UPDATE statements.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

With ANSI_PERMISSIONS ON, SQL92 permission requirements for DELETE and UPDATE statements are
checked. The default value is OFF in SAP Adaptive Server Enterprise. This table outlines the differences:

Permissions Required with ANSI_PERMIS­ Permissions Required with ANSI_PERMIS­


SQL Statement SIONS OFF SIONS ON

UPDATE UPDATE permission on the columns where ● UPDATE permission on the columns
values are being set
where values are being set
● SELECT permission on all columns ap­
pearing in the WHERE clause.
● SELECT permission on all columns on
the right side of the SET clause.

DELETE DELETE permission on table ● DELETE permission on table.


● SELECT permission on all columns ap­
pearing in the WHERE clause.

SAP IQ SQL Reference


1760 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.9 ANSI_SUBSTRING Option [TSQL]

Controls the behavior of the SUBSTRING (SUBSTR) function when negative values are provided for the start or
length parameters.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When the ANSI_SUBSTRING option is set to ON, the behavior of the SUBSTRING function corresponds to
ANSI/ISO SQL/2003 behavior. A negative or zero start offset is treated as if the string were padded on the left
with non-characters, and gives an error if a negative length is provided.

When this option is set to OFF, the behavior of the SUBSTRING function is the same as in earlier versions of SAP
IQ: a negative start offset means an offset from the end of the string, and a negative length means the desired

SAP IQ SQL Reference


Database Options INTERNAL 1761
substring ends length characters to the left of the starting offset. Using a start offset of 0 is equivalent to a start
offset of 1.

Avoid using non-positive start offsets or negative lengths with the SUBSTRING function. Where possible, use
the LEFT or RIGHT functions instead.

Example

These examples show the difference in the values returned by the SUBSTRING function based on the setting of
the ANSI_SUBSTRING option:

SUBSTRING( 'abcdefgh',-2,4 );
ansi_substring = Off ==> 'gh'
// substring starts at second-last character
ansi_substring = On ==> 'gh'
// takes the first 4 characters of
// ???abcdefgh and discards all ?

SUBSTRING( 'abcdefgh',4,-2 );
ansi_substring = Off ==> 'cd'
ansi_substring = On ==> value -2 out of range
for destination

SUBSTRING( 'abcdefgh',0,4 );
ansi_substring = Off ==> 'abcd'
ansi_substring = On ==> 'abcd'

Related Information

SUBSTRING Function [String] [page 536]


SUBSTRING Function [String] [page 536]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.10 ANSI_UPDATE_CONSTRAINTS Option

Controls the range of updates that are permitted.

Allowed Values

OFF, CURSORS, STRICT

SAP IQ SQL Reference


1762 INTERNAL Database Options
Default

CURSORS

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

SAP IQ provides several extensions that allow updates that are not permitted by the ANSI SQL standard. These
extensions provide powerful, efficient mechanisms for performing updates. However, in some cases, they
cause behavior that is not intuitive. This behavior might produce anomalies such as lost updates if the user
application is not designed to expect the behavior of these extensions.

ANSI_UPDATE_CONSTRAINTS controls whether updates are restricted to those permitted by the SQL92
standard.

If the option is set to STRICT, these updates are prevented:

● Updates of cursors containing JOINS


● Updates of columns that appear in an ORDER BY clause
● The FROM clause is not allowed in UPDATE statements.

If the option is set to CURSORS, these same restrictions are in place, but only for cursors. If a cursor is not
opened with FOR UPDATE or FOR READ ONLY, the database server determines whether updates are
permitted based on the SQL92 standard.

If ANSI_UPDATE_CONSTRAINTS is set to CURSORS or STRICT, cursors containing an ORDER BY clause default


to FOR READ ONLY; otherwise, they continue to default to FOR UPDATE.

Example

This code has a different effect, depending on the setting of ANSI_UPDATE_CONSTRAINTS:

CREATE TABLE mmg (a CHAR(3));


CREATE TABLE mmg1 (b CHAR(3));

INSERT INTO mmg VALUES ('001');

SAP IQ SQL Reference


Database Options INTERNAL 1763
INSERT INTO mmg VALUES ('002');
INSERT INTO mmg VALUES ('003')
INSERT INTO mmg1 VALUES ('003');
SELECT * FROM mmg;
SELECT * FROM mmg1;

Option 1
Set ANSI_UPDATE_CONSTRAINTS to STRICT:

SET OPTION public.Ansi_update_constraints = 'strict';


DELETE MMG FROM MMG1 WHERE A=B;

This results in an error indicating that the attempted update operation is not allowed.

Option 2
Set ANSI_UPDATE_CONSTRAINTS to CURSORS or OFF:

SET OPTION public.Ansi_update_constraints = 'CURSORS'; // or 'OFF'


DELETE mmg FROM mmg1 WHERE A=B;

In this case, the deletion should complete without the error.

Related Information

UPDATE Statement [page 1700]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.11 ANSINULL Option [TSQL]

Controls the interpretation of using = and != with NULL.

Allowed Values

ON, OFF

Default

● ON

SAP IQ SQL Reference


1764 INTERNAL Database Options
● OFF for Open Client and JDBC connections

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

With ANSINULL ON, results of comparisons with NULL using '=' or '!=' are unknown. This includes results of
comparisons implied by other operations such as CASE.

Setting ANSINULL ON to OFF allows comparisons with NULL to yield results that are not unknown, for
compatibility with SAP Adaptive Server Enterprise.

 Note

Unlike SAP SQL Anywhere, SAP IQ does not generate the warning “null value eliminated in
aggregate function” (SQLSTATE=01003) for aggregate functions on columns containing NULL values.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1765
10.6.12 ASE_BINARY_DISPLAY Option

Specifies that the display of SAP IQ binary columns is consistent with the display of SAP Adaptive Server
Enterprise binary columns.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

ASE_BINARY_DISPLAY affects the output of the SELECT statement.

This option affects only columns in the IQ store. It does not affect variables, catalog store columns or SAP SQL
Anywhere columns. When this option is ON, SAP IQ displays the column in readable ASCII format; for example,
0x1234567890abcdef. When this option is OFF, SAP IQ displays the column as binary output (not ASCII).

Set ASE_BINARY_DISPLAY OFF to support bulk copy operations on binary data types. SAP IQ supports bulk
loading of remote data via the LOAD TABLE USING CLIENT FILE statement.

Related Information

LOAD TABLE Statement [page 1549]


Set a Database Option [page 1727]

SAP IQ SQL Reference


1766 INTERNAL Database Options
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.13 ASE_FUNCTION_BEHAVIOR Option

Specifies that output of SAP IQ functions, including INTTOHEX and HEXTOINT, is consistent with the output of
SAP Adaptive Server Enterprise functions.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When ASE_BEHAVIOR_FUNCTION is ON, some of the SAP IQ data type conversion functions, including
HEXTOINT and INTTOHEX, return output that is consistent with the output of SAP ASE functions. The
differences in the SAP ASE and SAP IQ output, with respect to formatting and length, exist because SAP ASE
primarily uses signed 32-bit as the default and SAP IQ primarily uses unsigned 64-bit as the default.

SAP IQ does not provide support for 64-bit integer, as SAP ASE does not have a 64-bit integer data type.

SAP IQ SQL Reference


Database Options INTERNAL 1767
Example

In this example, the HEXTOINT function returns a different value based on whether ASE_BEHAVIOR_FUNCTION
is ON or OFF.

The HEXTOINT function returns 4294967287 with ASE_BEHAVIOR_FUNCTION OFF:

select hextoint('fffffff7') from iq_dummy

The HEXTOINT function returns -9 with ASE_BEHAVIOR_FUNCTION ON:

select hextoint('fffffff7') from iq_dummy

Related Information

CONVERSION_ERROR Option [TSQL] [page 1787]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.14 AUDITING Option [Database]

Enables and disables auditing in the database.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) level only.

SAP IQ SQL Reference


1768 INTERNAL Database Options
● Requires the SET ANY SECURITY OPTION system privilege to set this option. Takes effect immediately.

Remarks

Auditing is the recording of details about many events in the database in the transaction log. Auditing provides
some security features, at the cost of some performance. When you turn on auditing for a database, you
cannot stop using the transaction log. You must turn auditing off before you turn off the transaction log.
Databases with auditing on cannot be started in read-only mode.

For the AUDITING option to work, you must set the auditing option to ON, and use the
sa_enable_auditing_type system procedure to indicate the types of information to audit, including any
combination of permission checks, connection attempts, DDL statements, public options, triggers. Auditing
will not take place if either of these conditions is true:

● The AUDITING option is set to OFF


● Auditing options have been disabled

If you set the AUDITING option to ON, and do not specify auditing options, all types of auditing information are
recorded.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.15 auto_commit option

Causes an automatic commit after every request.

Allowed values

On, Off

Default

Off

SAP IQ SQL Reference


Database Options INTERNAL 1769
Scope

PUBLIC role For current user For other users

Allowed to set permanently? No No No

Allowed to set temporarily? No Yes (current connection only) No

Remarks

If this option is set to On, then the database server automatically commits after every request. This option can
only be set temporarily for a connection.

When an application enables automatic commit using the specific driver API, the SQL Anywhere JDBC, ODBC,
ADO.NET, and OLE DB drivers automatically set the auto_commit option to On if they are connected to a
version SAP IQ 16.1 database server. For previous versions, the driver reverts back to handling automatic
commits on the client side. By default, automatic commit is enabled for these drivers.

 Note

Do not set the auto_commit server option directly when using an API such as JDBC, ODBC, ADO.NET, or
OLE DB. Use the API-specific mechanism for enabling or disabling automatic commit. For example, in
ODBC set the SQL_ATTR_AUTOCOMMIT connection attribute using SQLSetConnectAttr. When you use
the API, the driver can track the current setting of automatic commit.

 Note

Use a BEGIN block to set the database option from an Interactive SQL session to avoid setting the
Interactive SQL option of the same name:

BEGIN
SET TEMPORARY OPTION AUTO_COMMIT = 'ON';
END;

Use this Interactive SQL command to verify the new setting of the database option:

SET;

 Note

The auto_commit option is different from the chained option. Setting auto_commit to On forces the
database server to commit after every request. Setting the chained option to Off forces the database server
to commit after each statement. This distinction is most important when executing a stored procedure.
Setting the chained option to Off will result in a commit request after the execution of each individual
statement within the procedure. Setting the auto_commit option to On will result in a single commit
request once the entire procedure finishes executing. In cases where automatic commit is necessary, it is
much better to use the auto_commit option rather than the chained option.

SAP IQ SQL Reference


1770 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.16 BASE_TABLES_IN_RLV_STORE Option

Registers newly created tables in the RLV store, enabling row-level versioning. RLV-enabled tables are eligible
for multiple writer concurrent access. You can override this setting at the table level using the CREATE_TABLE
statement.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When set to ON, newly created tables are registered in the RLV store. RLV-enabled tables are optimized for
real-time updates.

The { ENABLE | DISABLE } RLV STORE clause of the CREATE_TABLE statement always overrides the
BASE_TABLES_IN_RLV_STORE option.

Once Base_Tables_in_RLV_STORE option is enabled, any newly created IQ base tables are automatically
RLV-enabled. Enabling this option has no impact on existing IQ base tables.

SAP IQ SQL Reference


Database Options INTERNAL 1771
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.17 BIT_VECTOR_PINNABLE_CACHE_PERCENT Option

Maximum percentage of a user’s temp memory that a persistent bit-vector object can pin.

Allowed Values

0 to 100

Default

40

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

BIT_VECTOR_PINNABLE_CACHE_PERCENT controls the percentage of a user’s temp memory allocation that


any one persistent bit-vector object can pin in memory. It defaults to 40%, and should not generally be
changed by users.

This option is primarily for use by Technical Support. If you change the value of
BIT_VECTOR_PINNABLE_CACHE_PERCENT, do so with extreme caution; first analyze the effect on a wide
variety of queries.

SAP IQ SQL Reference


1772 INTERNAL Database Options
Related Information

HASH_PINNABLE_CACHE_PERCENT Option [page 1860]


SORT_PINNABLE_CACHE_PERCENT Option [page 2013]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.18 BLOCKING Option

Controls the behavior in response to locking conflicts. BLOCKING is not supported on secondary nodes of a
multiplex.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When BLOCKING is off, a transaction receives an error when it attempts a write operation and is blocked by the
read lock of another transaction.

SAP IQ SQL Reference


Database Options INTERNAL 1773
When BLOCKING is on, any transaction attempting to obtain a lock that conflicts with an existing lock held by
another transaction waits until every conflicting lock is released or until the blocking_timeout is reached. If the
lock is not released within blocking_timeout milliseconds, then an error is returned for the waiting transaction.

Related Information

BLOCKING_TIMEOUT Option [page 1774]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.19 BLOCKING_TIMEOUT Option

Controls the length of time a transaction waits to obtain a lock. BLOCKING_TIMEOUT is not supported on
secondary nodes of a multiplex.

Allowed Values

Integer, in milliseconds.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1774 INTERNAL Database Options
Remarks

When the blocking option is on, any transaction attempting to obtain a lock that conflicts with an existing lock
waits for the indicated number of milliseconds for the conflicting lock to be released. If the lock is not released
within blocking_timeout milliseconds, an error is returned for the waiting transaction.

Set the option to 0 to force all transactions attempting to obtain a lock to wait until all conflicting transactions
release their locks.

Related Information

BLOCKING Option [page 1773]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.20 BT_PREFETCH_MAX_MISS Option

Controls the way SAP IQ determines whether to continue prefetching B-tree pages for a given query.

Allowed Values

0 to 1000

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1775
Remarks

Use only if instructed to do so by SAP Technical Support. For queries that use HG (High_Group) indexes, SAP IQ
prefetches B-tree pages sequentially until it determines that prefetching is no longer useful. For some queries,
it might turn off prefetching prematurely. Increasing the value of BT_PREFETCH_MAX_MISS makes it more
likely that SAP IQ continues prefetching, but might also increase I/O unnecessarily.

If queries using HG indexes run more slowly than expected, try gradually increasing the value of
BT_PREFETCH_MAX_MISS.

Experiment with different settings to find the setting that gives the best performance. For most queries, useful
settings are in the range of 1 to 10.

Related Information

BT_PREFETCH_SIZE Option [page 1776]


PREFETCH_BUFFER_LIMIT Option [page 1951]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.21 BT_PREFETCH_SIZE Option

Restricts the size of the read-ahead buffer for the High_Group B-tree.

Allowed Values

0 to 100

Default

10

SAP IQ SQL Reference


1776 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Setting the value to 0 disables B-tree prefetch.

B-tree prefetch is activated by default for any sequential access to the High_Group index such as INSERT, large
DELETE, range predicates, and DBCC (Database Consistency Checker) commands.

BT_PREFETCH_SIZE limits the size of the read-ahead buffer for B-tree pages. Reducing prefetch size frees
buffers, but also degrades performance at some point. Increasing prefetch size might have marginal returns.
This option should be used in conjunction with the options PREFETCH_GARRAY_PERCENT,
GARRAY_INSERT_PREFETCH_SIZE, and GARRAY_RO_PREFETCH_SIZE for non-unique High_Group indexes.

Related Information

GARRAY_INSERT_PREFETCH_SIZE Option [page 1857]


GARRAY_RO_PREFETCH_SIZE Option [page 1859]
PREFETCH_GARRAY_PERCENT Option [page 1954]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.22 BTREE_PAGE_SPLIT_PAD_PERCENT Option

Determines per-page fill factor during page splits for B-tree structures.

Allowed Values

0 to 90

SAP IQ SQL Reference


Database Options INTERNAL 1777
Default

50

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

B-tree structures are used by the HG, DT, TIME, and DTTM indexes. Splits of a B-tree page try to leave the
specified percentage empty to avoid splitting when new keys are inserted into the index.

Indexes reserve storage at the page level that can be allocated to new keys as additional data is inserted.
Reserving space consumes additional disk space, but can help the performance of incremental inserts. If future
plans include incremental inserts, and the new rows do not have values that are already present in the index, a
nonzero value for GARRAY_PAGE_SPLIT_PAD_PERCENT may improve incremental insert performance.

If you do not plan to incrementally update the index, you can reduce the value of this option to save disk space.

Related Information

GARRAY_FILL_FACTOR_PERCENT Option [page 1856]


GARRAY_PAGE_SPLIT_PAD_PERCENT Option [page 1858]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1778 INTERNAL Database Options
10.6.23 CACHE_AFFINITY_PERCENT Option

The maximum percentage of main buffer cache to use for affinity. Non-affinity data can use this area if
insufficient affinity data exists.

Allowed Values

0 to 100 %

Default

75

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. The database server must be
shut down and restarted for the change to take effect

Remarks

This option defines the percentage of the buffer cache used for affinitized data buffers. SAP IQ buffer caches
are organized as a long MRU/LRU chain. Non-affinitized data buffers are put into the chain after affinitized
buffers when this percentage is non-zero, so that affinitized data stay in the cache longer than non-affinitized
data. If there are insufficient affinitized data buffers to fill this entire percentage, non-affinitized data may
consume the remainder.

 Note

Before changing this option, check the value of the WASH_AREA_BUFFERS_PERCENT option.
WASH_AREA_BUFFERS_PERCENT affects the LRU side of the buffer cache and CACHE_AFFINITY_PERCENT
affects the MRU side. The total of these two values cannot exceed 100 percent.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]

SAP IQ SQL Reference


Database Options INTERNAL 1779
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.24 CACHE_PARTITIONS Option

Sets the number of partitions to be used for the main and temporary buffer caches.

Allowed Values

0, 1, 2, 4, 8, 16, 32, 64

● 0 – (default) SAP IQ computes the number of partitions automatically as number_of_cpus/8, rounded to


the nearest power of 2, up to a maximum of 64.
● 1 – one partition only; this value disables partitioning.
● 2 through 64 – number of partitions; must be a power of 2.

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect for the current
database the next time you start the database server.

Remarks

Partitioning the buffer cache can sometimes improve performance on systems with multiple CPUs by reducing
lock contention. Normally, you should rely on the value that SAP IQ calculates automatically, which is based on
the number of CPUs on your system. However, if you find that load or query performance in a multi-CPU
configuration is slower than expected, you might be able to improve it by setting a different value for
CACHE_PARTITIONS.

Both the number of CPUs and the platform can influence the ideal number of partitions. Experiment with
different values to determine the best setting for your configuration.

The value you set for CACHE_PARTITIONS applies to both the main and temp buffer caches. The absolute
maximum number of partitions is 64, for each buffer cache.

SAP IQ SQL Reference


1780 INTERNAL Database Options
The -iqpartition start_iq server option sets the partition limit at the server level. If you specify -
iqpartition at server startup, it overrides the CACHE_PARTITIONS setting.

The number of partitions does not affect other buffer cache settings. It also does not affect statistics collected
by the IQ monitor; statistics for all partitions are rolled up and reported as a single value.

Example

In a system with 100 CPUs, if you do not set CACHE_PARTITIONS, SAP IQ automatically sets the number of
partitions to 16:

100 cpus/8 = 12, rounded to 16.

With this setting, there are 16 partitions for the main buffer cache and 16 partitions for the temp cache.

In the same system with 100 CPUs, to explicitly set the number of partitions to 8, specify:

SET OPTION "PUBLIC".CACHE_PARTITIONS=8

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.25 CHAINED Option [TSQL]

Controls transaction mode in the absence of a BEGIN TRANSACTION statement.

Allowed Values

ON, OFF

Default

● ON
● OFF for Open Client and JDBC connections

SAP IQ SQL Reference


Database Options INTERNAL 1781
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Controls the Transact-SQL transaction mode. In unchained mode (CHAINED = OFF) each statement is
committed individually unless an explicit BEGIN TRANSACTION statement is executed to start a transaction. In
chained mode (CHAINED = ON) a transaction is implicitly started before any data retrieval or modification
statement. For SAP Adaptive Server Enterprise, the default setting is OFF.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.26 CHECKPOINT_TIME Option

Set the maximum length of time, in minutes, that the database server runs without doing a checkpoint.

Allowed Values

Integer

Default

60

SAP IQ SQL Reference


1782 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must shut down and
restart the database server for the change to take effect.

Description

This option is used with the RECOVERY_TIME option to decide when checkpoints should be done.

Related Information

RECOVERY_TIME Option [page 1978]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.27 CIS_ROWSET_SIZE Option

Sets the number of rows that are returned from remote servers for each fetch.

Allowed Values

Integer

Default

50

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


Database Options INTERNAL 1783
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option sets the ODBC FetchArraySize value when you are using ODBC to connect to a remote database
server.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.28 CLOSE_ON_ENDTRANS Option [TSQL]

Controls closing of cursors at the end of a transaction.

Allowed Values

ON

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1784 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When CLOSE_ON_ENDTRANS is set to ON (the default and only value allowed), cursors are closed at the end of
a transaction, which is Transact-SQL compatible behavior.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.29 COLLECT_IQ_PERFORMANCE_STATS option

Enables statement performance monitoring for SAP IQ queries.

Allowed Values

ON, OFF

Default

OFF

Scope

Option can be set at the database (PUBLIC) or user level.

● When set at the database level, the value becomes the default for any new user, but has no impact on
existing users.
● When set at the user level, overrides the PUBLIC value for that user only.

Requires the SET ANY PUBLIC OPTION system privilege to set this option.

SAP IQ SQL Reference


Database Options INTERNAL 1785
● No system privilege is required to set option for self.
● SET ANY PUBLIC OPTION system privilege is required to set at database level or at user level for any user
other than self.

Can be set temporary for an individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Use COLLECT_IQ_PERFORMANCE_STATS to activate the statement performance monitoring feature. Once


you set COLLECT_IQ_PERFORMANCE_STATS to ON, SAP IQ collects Performance Monitor statistics and
statement performance summary statistics for SAP IQ queries.

To control statistics collection based on query execution time, you can use the QUERY_PLAN_MIN_TIME
option. Statistics for any query having an execution time less than the value of QUERY_PLAN_MIN_TIME are
not recorded.

 Example

SET OPTION PUBLIC.Collect_IQ_Performance_Stats='On';

10.6.30 CONTINUE_AFTER_RAISERROR Option [TSQL]

Controls behavior following a RAISERROR statement.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1786 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The RAISERROR statement is used within procedures to generate an error. When


CONTINUE_AFTER_RAISERROR is set to OFF, the execution of the procedure is stopped when the RAISERROR
statement is encountered.

When CONTINUE_AFTER_RAISERROR is ON, the RAISERROR statement no longer signals an execution-ending


error. Instead, the RAISERROR status code and message are stored and the most recent RAISERROR is
returned when the procedure completes. If the procedure that caused the RAISERROR was called from another
procedure, the RAISERROR is not returned until the outermost calling procedure terminates.

Intermediate RAISERROR statuses and codes are 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.

The setting of CONTINUE_AFTER_RAISERROR is used to control behavior following a RAISERROR statement


only if the ON_TSQL_ERROR option is set to CONDITIONAL (the default). If you set the ON_TSQL_ERROR option
to STOP or CONTINUE, the ON_TSQL_ERROR setting takes precedence over the
CONTINUE_AFTER_RAISERROR setting.

Related Information

ON_TSQL_ERROR Option [TSQL] [page 1946]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.31 CONVERSION_ERROR Option [TSQL]

Controls reporting of data type conversion failures on fetching information from the database.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 1787
Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option controls whether data type conversion failures, when data is fetched from the database or inserted
into the database, are reported by the database as errors (CONVERSION_ERROR set to ON), or as warnings
(CONVERSION_ERROR set to OFF).

When CONVERSION_ERROR is set to ON, the SQLE_CONVERSION_ERROR error is generated.

If the option is set to OFF, the warning SQLE_CANNOT_CONVERT is produced. Each thread doing data
conversion for a LOAD statement writes at most one warning message to the .iqmsg file.

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

 Note

SAP IQ does not silently truncate the conversion result of NUMERIC and DATE data types to CHAR and
VARCHAR. A conversion error is generated when the following data types are converted to a string whose
length is less than the column width:

● TINYINT, SMALLINT, [UNSIGNED] { INT | INTEGER }, [ UNSIGNED ] BIGINT


● NUMERIC, DECIMAL
● FLOAT, DOUBLE, REAL
● DATE, DATETIME, SMALLDATETIME, TIME, TIMESTAMP

The CONVERSION_ERROR option controls SAP IQ behavior in cases of conversion error. If you set the
CONVERSION_ERROR option to:

● OFF – SAP IQ inserts a NULL value when possible


● ON – SAP IQ rolls back the insert and logs a conversion error

SAP IQ SQL Reference


1788 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.32 CONVERSION_MODE Option

Restricts implicit conversion between binary data types (BINARY, VARBINARY, and LONG BINARY) and other
non-binary data types (BIT, TINYINT, SMALLINT, INT, UNSIGNED INT, BIGINT, UNSIGNED BIGINT, CHAR,
VARCHAR, and LONG VARCHAR) on various operations. Also allows all explicit conversions to be permitted as
implicit conversions on various operations.

Allowed Values

0, 1, 2

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The default CONVERSION_MODE value of 0 maintains implicit conversion behavior prior to version 12.7.

Setting CONVERSION_MODE to 1 restricts implicit conversion of binary data types to any other non-binary data
type on INSERT, UPDATE, and in queries. The restrict binary conversion mode also applies to LOAD TABLE

SAP IQ SQL Reference


Database Options INTERNAL 1789
default values and CHECK constraint. CONVERSION_MODE 1 prevents implicit data type conversions of
encrypted data that would result in semantically meaningless operations.

Setting CONVERSION_MODE option to allows all explicit conversions to be permitted as implicit conversions on
various operations. If this option is not set, the user must use CAST or CONVERT in queries that require explicit
conversions.

Users must be specifically licensed to use the encrypted column functionality of the SAP IQ Advanced Security
Option.

Implicit Conversion Restrictions

The CONVERSION_MODE option value of 1 (CONVERSION_MODE = 1) restricts implicit conversion for these
operations:

● LOAD TABLE with CHECK constraint or default value


● INSERT...SELECT, INSERT...VALUE, and INSERT...LOCATION
● Certain types of UPDATE
● Certain types of INSERT and UPDATE via updatable cursor
● All aspects of queries in general

In this section:

Restrict Implicit Binary Conversion Mode for LOAD TABLE [page 1791]
The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to LOAD TABLE with
CHECK constraint or default value.

Restrict Implicit Binary Conversion Mode for INSERT [page 1791]


The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to
INSERT...SELECT, INSERT...VALUE, and INSERT...LOCATION.

Restrict Implicit Binary Conversion Mode for UPDATE [page 1792]


The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to certain types of
UPDATE.

Restrict Implicit Binary Conversion Mode for Positioned INSERT and Positioned UPDATE via Updatable
Cursor [page 1793]
The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to certain types of
INSERT and UPDATE via updatable cursor.

Restrict Implicit Binary Conversion Mode for Queries [page 1793]


The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to all aspects of
queries in general.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]

SAP IQ SQL Reference


1790 INTERNAL Database Options
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.32.1 Restrict Implicit Binary Conversion Mode for LOAD


TABLE

The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to LOAD TABLE with CHECK
constraint or default value.

Example

CREATE TABLE t3 (c1 INT,


csi SMALLINT,
cvb VARBINARY(2),
CHECK (csi<cvb));
SET TEMPORARY OPTION CONVERSION_MODE = 1;

The request in this example fails, and returns the following message:

LOAD TABLE t3(c1 ',', csi ',', cvb ',')


FROM '/s1/mydata/t3.inp'
QUOTES OFF ESCAPES OFF
ROW DELIMITED BY '\n'

"Invalid data type comparison in predicate


(t3.csi < t3.cvb), [-1001013] ['QFA13']"

10.6.32.2 Restrict Implicit Binary Conversion Mode for


INSERT

The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to INSERT...SELECT,
INSERT...VALUE, and INSERT...LOCATION.

Example

CREATE TABLE t1 (c1 INT PRIMARY KEY,


cbt BIT NULL,
cti TINYINT,
csi SMALLINT,
cin INTEGER,
cui UNSIGNED INTEGER,
cbi BIGINT,
cub UNSIGNED BIGINT,
cch CHAR(10),

SAP IQ SQL Reference


Database Options INTERNAL 1791
cvc VARCHAR(10),
cbn BINARY(8),
cvb VARBINARY(8),
clb LONG BINARY,
clc LONG VARCHAR);
CREATE TABLE t2 (c1 INT PRIMARY KEY,
cbt BIT NULL,
cti TINYINT,
csi SMALLINT,
cin INTEGER,
cui UNSIGNED INTEGER,
cbi BIGINT,
cub UNSIGNED BIGINT,
cch CHAR(10),
cvc VARCHAR(10),
cbn BINARY(8),
cvb VARBINARY(8),
clb LONG BINARY,
clc LONG VARCHAR);
CREATE TABLE t4 (c1 INT, cin INT DEFAULT 0x31);
SET TEMPORARY OPTION CONVERSION_MODE = 1;

The query in this example fails, and returns the following message:

INSERT INTO t1(c1, cvb) SELECT 99, cin FROM T2


WHERE c1=1

"Unable to convert column 'cvb' to the requested


datatype (varbinary) from datatype (integer).
[-1013043] ['QCA43']"

10.6.32.3 Restrict Implicit Binary Conversion Mode for


UPDATE

The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to certain types of UPDATE.

Restrict implicit binary conversion mode applies to the following:

● UPDATE SET VALUE FROM <expression> (including constant)


● UPDATE SET VALUE FROM <other column>
● UPDATE SET VALUE FROM <host variable>
● JOIN UPDATE SET VALUE FROM <column of other table>

The query in this example fails, and returns the following message:

UPDATE t1 SET cbi=cbn WHERE c1=1

"Unable to implicitly convert column 'cbi' to datatype


(bigint) from datatype (binary). [-1000187] ['QCB87']"

SAP IQ SQL Reference


1792 INTERNAL Database Options
10.6.32.4 Restrict Implicit Binary Conversion Mode for
Positioned INSERT and Positioned UPDATE via
Updatable Cursor

The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to certain types of INSERT
and UPDATE via updatable cursor.

Restrict implicit binary conversion mode applies to:

● PUT <cursor-name> USING … <host-variable>


● Positioned UPDATE from another column
● Positioned UPDATE from a constant
● Positioned UPDATE from a host variable

10.6.32.5 Restrict Implicit Binary Conversion Mode for


Queries

The restrict implicit binary conversion mode (CONVERSION_MODE set to 1) applies to all aspects of queries in
general.

Comparison Operators

When CONVERSION_MODE is set to 1, the restriction applies to these operators:

● =, !=, <, <=, >=, <>, !>, !<


● BETWEEN … AND
● IN

The restriction is used in a search condition for these clauses:

● WHERE clause
● HAVING clause
● CHECK clause
● ON phrase in a join
● IF CASE expression

The query in this example fails, and returns the following message:

SELECT COUNT(*) FROM T1


WHERE cvb IN (SELECT csi FROM T2)

"Invalid data type comparison in predicate


(t1.cvb IN (SELECT t1.csi ...)), [-1001013]
['QFA13']"

SAP IQ SQL Reference


Database Options INTERNAL 1793
String Functions

When CONVERSION_MODE = 1, the restriction applies to these string functions:

● CHAR
● CHAR_LENGTH
● DIFFERENCE
● LCASE
● LEFT
● LOWER
● LTRIM
● PATINDEX
● RIGHT
● RTRIM
● SIMILAR
● SORTKEY
● SOUNDEX
● SPACE
● STR
● TRIM
● UCASE
● UPPER

The query in this example fails, and returns the following message:

SELECT ASCII(cvb) FROM t1 WHERE c1=1

"Data exception - data type conversion is not


possible. Argument to ASCII must be string,
[-1009145] ['QFA2E']"

The following functions allow either a string argument or a binary argument. When CONVERSION_MODE = 1, the
restriction applies to mixed type arguments, that is, one argument is string and the other argument is binary.

● INSERTSTR
● LOCATE
● REPLACE
● STRING
● STUFF

In this query, the column cvb is defined as VARBINARY and the column cvc is defined as VARCHAR. When
executed, the query fails, and returns the following message:

SELECT STRING(cvb, cvc) FROM t1 WHERE c1=1

"Data exception - data type conversion is not


possible. Arguments to STRING must be all binary
or all string, [-1009145] ['QFA2E']"

The restriction does not apply to these string functions:

● BIT_LENGTH

SAP IQ SQL Reference


1794 INTERNAL Database Options
● BYTE_LENGTH
● CHARINDEX
● LENGTH
● OCTET_LENGTH
● REPEAT
● REPLICATE
● SUBSTRING

Arithmetic Operations and Functions

When CONVERSION_MODE = 1, the restriction applies to these operators used in arithmetic operations: +, -, *, /

The restriction applies to these bitwise operators used in bitwise expressions: & (AND), | (OR), ^ (XOR)

The restriction also applies to integer arguments of these functions:

● ROUND
● “TRUNCATE”
● TRUNCNUM

The query in this example fails, and returns the following message:

SELECT ROUND(4.4, cvb) FROM t1 WHERE C1=1

"Data exception - data type conversion is not


possible. Second Argument to ROUND cannot be
converted into an integer, [-1009145] ['QFA2E']"

Integer Argument to Various Functions

When CONVERSION_MODE = 1, the restriction applies to integer argument of these functions:

● ARGN
● SUBSTRING
● DATEADD
● YMD

The query in this example fails, and returns the following message:

SELECT ARGN(cvb, csi, cti) FROM t1 WHERE c1=1

"Data exception - data type conversion is not


possible. First Argument to ARGN cannot be converted
to an integer, [-1009145] ['QFA2E']"

SAP IQ SQL Reference


Database Options INTERNAL 1795
Analytical Functions, Aggregate Functions, and Numeric Functions

When CONVERSION_MODE = 1, no further restriction applies to analytical functions, aggregate functions, and
numeric functions that require numeric expressions as arguments.

10.6.33 CONVERT_VARCHAR_TO_1242 Option

Converts pre-version 12.4.2 VARCHAR data to compressed format.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect when you run
sp_iqcheckdb in any mode.

Remarks

Helps further compress data and improve performance, especially for databases with many variable character
strings.

Set this option and then run sp_iqcheckdb only once, and only for VARCHAR columns that were created
before version 12.4.2.

SAP IQ SQL Reference


1796 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.34 COOPERATIVE_COMMIT_TIMEOUT Option

Governs when a COMMIT entry in the transaction log is written to disk.

Allowed Values

Integer, in milliseconds

Default

250

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option only has meaning when COOPERATIVE_COMMITS is set to ON. The database server waits for the
specified number of milliseconds for other connections to fill a page of the log before writing to disk. The
default setting is 250 milliseconds.

SAP IQ SQL Reference


Database Options INTERNAL 1797
Related Information

COOPERATIVE_COMMITS Option [page 1798]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.35 COOPERATIVE_COMMITS Option

Controls when commits are written to disk.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If COOPERATIVE_COMMITS is set to OFF, a COMMIT is written to disk as soon as the database server receives it,
and the application is then allowed to continue.

If CREATE_HG_AND_FORCE_PHYSICAL_DELETE is set to ON, the default, the database server does not
immediately write the COMMIT to the disk. Instead, it requires the application to wait for a maximum length set

SAP IQ SQL Reference


1798 INTERNAL Database Options
by the COOPERATIVE_COMMIT_TIMEOUT option for something else to put on the pages before the commit is
written to disk.

Setting CREATE_HG_AND_FORCE_PHYSICAL_DELETE to ON, and increasing the


COOPERATIVE_COMMIT_TIMEOUT setting increases overall database server throughput by cutting down the
number of disk I/Os, but at the expense of a longer turnaround time for each individual connection.

Related Information

COOPERATIVE_COMMIT_TIMEOUT Option [page 1797]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.36 CREATE_HG_AND_FORCE_PHYSICAL_DELETE
Option

Governs 16.1 tiered HG index delete behavior.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1799
Remarks

CREATE_HG_AND_FORCE_PHYSICAL_DELETE determines whether delete operation physically removes rows


from an HG immediately or defers the removal to a point later in the load:

● Setting CREATE_HG_AND_FORCE_PHYSICAL_DELETE to ON (default) instructs SAP IQ to perform a


physical delete, which increases the performance of some queries (link in .. list and ordered projection, for
example), but can cause delete queries on tables with tiered HG indexes to run more slowly.
● Setting CREATE_HG_AND_FORCE_PHYSICAL_DELETE to OFF instructs SAP IQ to perform a virtual or
deferred delete, which improves delete query performance, but can impact queries on tables with tiered HG
indexes.

Set CREATE_HG_AND_FORCE_PHYSICAL_DELETE before creating a tiered HG column index. It does not affect
preexisting HG indexes. It has no effect on sp_iqrebuildindex. This option persists through the life of the
tiered HG index, and cannot be changed or modified unless the index is dropped and the option toggled before
re-creating the index (sp_iqrebuildindex cannot modify the status of the index).

 Note

sp_iqrebuildindex output includes a Force Physical Delete column that identifies the status of
this option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.37 CREATE_HG_WITH_EXACT_DISTINCTS Option

Determines whether the database engine creates tiered HG or single-tiered HG indexes.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


1800 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

CREATE_HG_WITH_EXACT_DISTINCTS determines whether the database engine creates HG indexes as single


HG or tiered HG:

● If CREATE_HG_WITH_EXACT_DISTINCTS='ON' – all subsequent HG indexes explicitly created with a


CREATE INDEX command or implicitly creating or altering a table with a PRIMARY KEY or a FOREIGN KEY
declaration, will be non-tiered HG indexes.
● If CREATE_HG_WITH_EXACT_DISTINCTS='OFF' – all subsequent HG indexes explicitly created with a
CREATE INDEX command or implicitly creating or altering a table with a PRIMARY KEY or a FOREIGN KEY
declaration, will be tiered HG.

This option is ON by default in all newly created 16.1 databases, and all 16.1 database upgraded from SAP IQ
15.x. To take advantage of the new tiered structure, set this option to OFF. Use sp_iqrebuildindex to
convert non-tiered HG indexes to tiered HG and vice versa.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.38 CURSOR_WINDOW_ROWS Option

Defines the number of cursor rows to buffer.

Allowed Values

20 to 100,000

SAP IQ SQL Reference


Database Options INTERNAL 1801
Default

200

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set only for individual
connections or the PUBLIC role. You must shut down and restart the database server for the change to
take effect.

Remarks

When an application opens a cursor, SAP IQ creates a FIFO (first-in, first-out) buffer to hold the data rows
generated by the query. CURSOR_WINDOW_ROWS defines how many rows can be put in the buffer. If the cursor is
opened in any mode other than NO SCROLL, SAP IQ allows for backward scrolling for up to the total number of
rows allowed in the buffer before it must restart the query. This is not true for NO SCROLL cursors, as they do
not allow backward scrolling.

For example, with the default value for this option, the buffer initially holds rows 1 through 200 of the query
result set. If you fetch the first 300 rows, the buffer holds rows 101 through 300. You can scroll backward or
forward within that buffer with very little overhead cost. If you scroll before row 101, SAP IQ restarts that query
until the required row is back in the buffer. This can be an expensive operation to perform, so your application
should avoid it where possible. An alternative is to increase the value for CURSOR_WINDOW_ROWS to
accommodate a larger possible scrolling area; however, the default setting of 200 is sufficient for most
applications.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1802 INTERNAL Database Options
10.6.39 DATE_FIRST_DAY_OF_WEEK Option

Determines the first day of the week.

Allowed Values

0 to 6

Default

0 (Sunday)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set for an individual
connection or for the PUBLIC role. You must shut down and restart the database server for the change to
take effect.

Remarks

By default, Sunday is day 1, Monday is day 2, Tuesday is day 3, and so on. This option specifies which day is the
first day of the week:

● 0 – Sunday
● 1 – Monday
● 2 – Tuesday
● 3 – Wednesday
● 4 – Thursday
● 5 – Friday
● 6 – Saturday

For example, if you change the value of DATE_FIRST_DAY_OF_WEEK to 3, Wednesday becomes day 1,
Thursday becomes day 2, and so on. This option only affects the DOW and DATEPART functions.

The SAP SQL Anywhere option FIRST_DAY_OF_WEEK performs the same function, but assigns the values 1
through 7 instead of 0 through 6. 1 stands for Monday and 7 for Sunday (the default).

SAP IQ SQL Reference


Database Options INTERNAL 1803
Related Information

DOW Function [Date and Time] [page 348]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.40 DATE_FORMAT Option

Sets the format used for dates retrieved from the database.

Allowed Values

String

Default

'YYYY-MM-DD'. This corresponds to ISO date format specifications.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The format is a string using these symbols:

Symbol Description

yy 2-digit year

SAP IQ SQL Reference


1804 INTERNAL Database Options
Symbol Description

yyyy 4-digit year

mm 2-digit month, or 2-digit minutes if following a colon (as in 'hh:mm')

mmm 3-character name of month

mmmm[m...] Character long form for months—as many characters as there are m's, until the number of m’s
specified exceeds the number of characters in the month’s name

d Single-digit day of week, (0 = Sunday, 6 = Saturday)

dd 2-digit day of month

ddd 3-character name of the day of week

dddd[d...] Character long form for day of the week—as many characters as there are d's, until the number
of d’s specified exceeds the number of characters in the day’s name

jjj Day of the year, from 1 to 366

 Note

Multibyte characters are not supported in date format strings. Only single-byte characters are allowed,
even when the collation order of the database is a multibyte collation order like 932JPN. Use the
concatenation operator to include multibyte characters in date format strings. For example, if '<?>'
represents a multibyte character, use the concatenation operator to move the multibyte character outside
of the date format string:

SELECT DATEFORMAT (StartDate, 'yy') + '?'


FROM Employees;

Each symbol is substituted with the appropriate data for the date being formatted. Any format symbol that
represents character rather than digit output can be put in uppercase which causes the substituted characters
to also be in uppercase. For numbers, using mixed case in the format string suppresses leading zeros.

You can control the padding of numbers by changing the case of the symbols. Same-case values (MM, mm, DD,
or dd) all pad number with zeros. Mixed-case (Mm, mM, Dd, or dD) cause the number to not be zero-padded;
the value takes as much room as required. For example:

SELECT dateformat ( cast ('2011/01/01' as date ), 'yyyy/Mm/Dd' )

returns this value:

2011/1/1

Examples

This table illustrates DATE_FORMAT settings, together with the output from this statement, executed on
Saturday May 21, 2011:

SELECT CURRENT DATE

SAP IQ SQL Reference


Database Options INTERNAL 1805
DATE FORMAT SELECT CURRENT DATE

yyyy/mm/dd/ddd 2011/05/21/sat

jjj 141

mmm yyyy may 2011

mm-yyyy 05-2011

Related Information

RETURN_DATE_TIME_AS_STRING Option [page 1982]


TIME_FORMAT Option [page 2058]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.41 DATE_ORDER Option

Controls the interpretation of date formats.

Allowed Values

'MDY', 'YMD', or 'DMY'

Default

'YMD'. This corresponds to ISO date format specifications.

'MDY' for Open Client and JDBC connections

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1806 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

DATE_ORDER is used to determine whether 10/11/12 is Oct 11 1912, Nov 12 1910, or Nov 10 1912. The option can
have the value 'MDY', 'YMD', or 'DMY'.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.42 DBCC_LOG_PROGRESS Option

Reports the progress of the sp_iqcheckdb system stored procedure.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1807
Remarks

When DBCC_LOG_PROGRESS is ON, the sp_iqcheckdb system stored procedure sends progress messages to
the IQ message file. These messages allow the user to follow the progress of the sp_iqcheckdb operation.

Examples

Sample progress log output of the command sp_iqcheckdb 'check database':

IQ Utility Check Database


Start CHECK STATISTICS table: tloansf
Start CHECK STATISTICS for field: aqsn_dt
Start CHECK STATISTICS processing index:
IQ_IDX_T444_C1_FP
Start CHECK STATISTICS processing index:
tloansf_aqsn_dt_HNG
Done CHECK STATISTICS field: aqsn_dt

Sample progress log output of the command sp_iqcheckdb 'allocation table nation':

Start ALLOCATION table: nation


Start ALLOCATION processing index: nationhg1
Done ALLOCATION table: nation
Done ALLOCATION processing index: nationhg1

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.43 DBCC_PINNABLE_CACHE_PERCENT Option

Controls the percent of the cache used by the sp_iqcheckdb system stored procedure.

Allowed Values

0 to 100

SAP IQ SQL Reference


1808 INTERNAL Database Options
Default

50

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect at the next execution of sp_iqcheckdb.

Remarks

The sp_iqcheckdb system stored procedure works with a fixed number of buffers, as determined by this
option. By default, a large percentage of the cache is reserved to maximize sp_iqcheckdb performance.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.44 DEBUG_MESSAGES Option

Controls whether or not MESSAGE statements that include a DEBUG ONLY clause are executed.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 1809
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option allows you to control the behavior of debugging messages in stored procedures that contain a
MESSAGE statement with the DEBUG ONLY clause specified. By default, this option is set to OFF and debugging
messages do not appear when the MESSAGE statement is executed. By setting DEBUG_MESSAGES to ON, you
can enable the debugging messages in all stored procedures.

 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 might result in a small
performance penalty.

Related Information

MESSAGE Statement [page 1577]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1810 INTERNAL Database Options
10.6.45 DEDICATED_TASK Option

Dedicates a request handling task to handling requests from a single connection.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set as a temporary option only, for an individual connection or for the PUBLIC role, for the
duration of the current connection.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When the DEDICATED_TASK connection option is set to ON, a request handling task is dedicated exclusively to
handling requests for the connection. By pre-establishing a connection with this option enabled, you can gather
information about the state of the database server if it becomes otherwise unresponsive.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1811
10.6.46 DEFAULT_DBSPACE Option

Changes the default dbspace where tables are created.

Allowed Values

String containing a dbspace name

Default

'' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

DEFAULT_DBSPACE allows the administrator to set the default dbspace for a role or user or allows a user to set
the user’s own default dbspace.

IQ_SYSTEM_TEMP is always used for global temporary tables unless a table IN clause is used that specifies
SYSTEM, in which case an SA global temporary table is created.

At database creation, the system dbspace, IQ_SYSTEM_MAIN, is created and is implied when the
PUBLIC.DEFAULT_DBSPACE option setting is empty or explicitly set to IQ_SYSTEM_MAIN. Immediately after
creating the database, create a second main dbspace, revoke CREATE privilege in dbspace IQ_SYSTEM_MAIN
from PUBLIC, grant CREATE in dbspace for the new main dbspace to selected users or PUBLIC, and set
PUBLIC.DEFAULT_DBSPACE to the new main dbspace. For example:

CREATE DBSPACE user_main USING FILE user_main


'user_main1' SIZE 10000;
GRANT CREATE ON user_main TO PUBLIC;
REVOKE CREATE ON IQ_SYSTEM_MAIN FROM PUBLIC;
SET OPTION PUBLIC.DEFAULT_DBSPACE = 'user_main';

SAP IQ SQL Reference


1812 INTERNAL Database Options
Example

In this example, CONNECT and RESOURCE privileges on all dbspaces are granted to users usrA and usrB, and
each of these users is granted CREATE privilege on a particular dbspace:

GRANT CONNECT, RESOURCE TO usrA, usrB


IDENTIFIED BY pwdA, pwdB;
GRANT CREATE ON dbsp1 TO usrA;
GRANT CREATE ON dbsp3 TO usrB;
SET OPTION “usrA”.default_dbspace = ‘dbsp1’;
SET OPTION “usrB”.default_dbspace = ‘dbsp3’;
SET OPTION “PUBLIC”.default_dbspace = dbsp2;
CREATE TABLE “DBA”.t1(c1 int, c2 int);
INSERT INTO t1 VALUES (1, 1);
INSERT INTO t1 VALUES (2, 2);
COMMIT;

UsrA connects:

CREATE TABLE “UsrA”.t1(c1 int, c2 int);


INSERT INTO t1 VALUES (1, 1);
INSERT INTO t1 VALUES (2, 2);
COMMIT;

UsrB connects:

CREATE TABLE “UsrB”.t1(c1 int, c2 int);


INSERT INTO t1 VALUES (1, 1);
INSERT INTO t1 VALUES (2, 2);
COMMIT;

DBA connects:

SELECT Object, DbspaceName, ObjSize


FROM sp_iqindexinfo();

sp_iqindexinfo result:

DBA.t1 dbsp2 200k


DBA.t1.ASIQ_IDX_T730_C1_FP dbsp2 288k
DBA.t1.ASIQ_IDX_T730_C2_FP dbsp2 288k
usrA.t1 dbsp1 200k
usrA.t1.ASIQ_IDX_T731_C1_FP dbsp1 288k
usrA.t1.ASIQ_IDX_T731_C2_FP dbsp1 288k
usrB.t1 dbsp3 200k
usrB.t1.ASIQ_IDX_T732_C1_FP dbsp3 288k
usrB.t1.ASIQ_IDX_T732_C2_FP dbsp3 288k

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1813
10.6.47 DEFAULT_DISK_STRIPING Option

Sets the default disk striping value for all dbspaces.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

By default, disk striping is ON for all dbspaces in the IQ main store. This option is used only by CREATE
DBSPACE and defines the default striping value, if CREATE DBSPACE does not specify striping.

Related Information

CREATE DBSPACE Statement [page 1254]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1814 INTERNAL Database Options
10.6.48 DEFAULT_HAVING_SELECTIVITY_PPM Option

Provides default selectivity estimates to the optimizer for most HAVING clauses in parts per million.

Allowed Values

0 to 1,000,000

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

DEFAULT_HAVING_SELECTIVITY_PPM sets the selectivity for HAVING clauses, overriding optimizer


estimates. A HAVING clause filters the results of a GROUP BY clause or a query with a select list consisting
solely of aggregate functions. When DEFAULT_HAVING_SELECTIVITY_PPM is set to the default of 0, the
optimizer estimates how many rows are filtered by the HAVING clause. Sometimes the IQ optimizer does not
have sufficient information to choose an accurate selectivity, and in these cases chooses a generic estimate of
40%. DEFAULT_HAVING_SELECTIVITY_PPM allows a user to replace the optimizer estimate for all HAVING
predicates in a query.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


Database Options INTERNAL 1815
GRANT System Privilege Statement [page 1511]

10.6.49 DEFAULT_ISQL_ENCODING Option [Interactive SQL]

Specifies the code page used by READ and OUTPUT statements.

Allowed Values

<identifier> or <string>

Default

Use system code page (empty string)

Scope

Can only be set as a temporary option, for the duration of the current connection.

Remarks

DEFAULT_ISQL_ENCODING specifies the code page to use when reading or writing files. It cannot be set
permanently. The default code page is the default code page for the platform you are running on.

Interactive SQL determines the code page that is used for a particular OUTPUT or READ statement as follows,
where code page values occurring earlier in the list take precedence over those occurring later in the list:

● The code page specified in the ENCODING clause of the OUTPUT or READ statement
● The code page specified with the DEFAULT_ISQL_ENCODING option (if this option is set)
● The default code page for the computer on which Interactive SQL is running

Example

Set the encoding to UTF-16 (for reading Unicode files):

SET TEMPORARY OPTION DEFAULT_ISQL_ENCODING = 'UTF-16'

SAP IQ SQL Reference


1816 INTERNAL Database Options
Related Information

OUTPUT Statement [Interactive SQL] [page 1585]


READ Statement [Interactive SQL] [page 1598]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.50 DEFAULT_KB_PER_STRIPE Option

Sets an upper threshold in KB on the amount to write to a stripe before write operations move on to the next
stripe.

This setting is the default size for all dbspaces in the IQ main store.

Allowed Values

1 to maximum integer

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

The default value of 1 KB means that one page is compressed and that the compressed page is written to disk
as a single operation. Whatever the chosen page size, the next operation writes to the next dbfile in that
dbspace.

To write multiple pages to the same stripe before moving to the next stripe, change the
DEFAULT_KB_PER_STRIPE setting. For example, if the page size is 128 KB, and DEFAULT_KB_PER_STRIPE set

SAP IQ SQL Reference


Database Options INTERNAL 1817
to 512 KB, SAP IQ queues up page writes and writes to disk after reaching the minimum of 512 KB of
compressed pages.

This option is used only by CREATE DBSPACE and defines the default disk striping size for dbspaces in the IQ
main store, if CREATE DBSPACE does not specify a stripe size.

Related Information

CREATE DBSPACE Statement [page 1254]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.51 DEFAULT_LIKE_MATCH_SELECTIVITY_PPM Option

Provides default selectivity estimates (in parts per million) to the optimizer for most LIKE predicates.

Allowed Values

0 to 1,000,000

Default

150,000

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1818 INTERNAL Database Options
Remarks

DEFAULT_LIKE_MATCH_SELECTIVITY_PPM sets the default selectivity for generic LIKE predicates, for
example, LIKE '<string%string>' where % is a wildcard character.

The optimizer relies on this option when other selectivity information is not available and the match string does
not start with a set of constant characters followed by a single wildcard.

If the column has or a 1- or 2- or 3-byte FP index, the optimizer can get exact information and does not need to
use this value.

You can also specify selectivity (user-supplied condition hints).

Related Information

DEFAULT_LIKE_RANGE_SELECTIVITY_PPM Option [page 1819]


FP_LOOKUP_SIZE Option [page 1843]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
User-Supplied Condition Hints [page 75]

10.6.52 DEFAULT_LIKE_RANGE_SELECTIVITY_PPM Option

Provides default selectivity estimates (in parts per million) to the optimizer for leading constant LIKE
predicates.

Allowed Values

1 to 1,000,000

Default

150,000

SAP IQ SQL Reference


Database Options INTERNAL 1819
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

DEFAULT_LIKE_RANGE_SELECTIVITY_PPM sets the default selectivity for LIKE predicates, of the form
LIKE '<string%>' where the match string is a set of constant characters followed by a single wildcard
character (%). The optimizer relies on this option when other selectivity information is not available.

If the column has or a 1- or 2- or 3-byte FP index, the optimizer can get exact information and does not need to
use this value.

You can also specify selectivity (user-supplied condition hints) in the query.

Related Information

DEFAULT_LIKE_MATCH_SELECTIVITY_PPM Option [page 1818]


FP_LOOKUP_SIZE Option [page 1843]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
User-Supplied Condition Hints [page 75]

10.6.53 DEFAULT_PROXY_TABLE_ROW_COUNT Option

Enables you to override the default estimate of the number of rows to return from a proxy table.

Allowed Values

0 to 4,294,967,295

SAP IQ SQL Reference


1820 INTERNAL Database Options
Default

200,000

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.54 DEFAULT_TABLE_UDF_ROW_COUNT Option

Enables you to override the default estimate of the number of rows to return from a table UDF (either a C, C++,
or Java table UDF).

Allowed Values

0 to 4,294,967,295

Default

200,000

SAP IQ SQL Reference


Database Options INTERNAL 1821
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

A table UDF or TPF can use the DEFAULT_TABLE_UDF_ROW_COUNT option to give the query processor an
estimate for the number of rows that a table UDF will return. This is the only way a Java table UDF can convey
this information. However, for a C or C++ table UDF, the UDF developer should consider publishing this
information in the describe phase using the EXTFNAPIV4_DESCRIBE_PARM_TABLE_NUM_ROWS describe
parameter to publish the number of rows it expects to return. The value of
EXTFNAPIV4_DESCRIBE_PARM_TABLE_NUM_ROWS always overrides the value of the
DEFAULT_PROXY_TABLE_UDF_ROW_COUNT option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.55 DELAYED_COMMIT_TIMEOUT Option

Determines when the server returns control to an application following a COMMIT.

Allowed Values

Integer, in milliseconds.

Default

500

SAP IQ SQL Reference


1822 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option is ignored by SAP IQ, since DELAYED_COMMITS can only be set OFF.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.56 DELAYED_COMMITS Option

Determines when the server returns control to an application following a COMMIT.

Allowed Values

OFF

Default

OFF. This corresponds to ISO COMMIT behavior.

SAP IQ SQL Reference


Database Options INTERNAL 1823
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When set to OFF (the only value allowed by SAP IQ), the application must wait until the COMMIT is written to
disk. This option must be set to OFF for ANSI/ISO COMMIT behavior.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.57 DISABLE_RI_CHECK Option

Allows load, insert, update, or delete operations to bypass the referential integrity check, improving
performance.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


1824 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Users are responsible for ensuring that no referential integrity violation occurs during requests while
DISABLE_RI_CHECK is set to ON.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.58 DIVIDE_BY_ZERO_ERROR Option [TSQL]

Controls the reporting of division by zero.

Allowed Values

ON, OFF

Default

ON

SAP IQ SQL Reference


Database Options INTERNAL 1825
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

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

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

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.59 DML_OPTIONS90 Option

Controls whether zone maps are used querying to potentially improve performance.

Allowed Values

● 0 – production mode. Zone map predicates are considered for query processing by the optimizer.
● 1 – off. Zone map predicates are not used.
● 2 – diagnostic mode. Zone map predicates are created but are validated only; they are not used in the
computation of the query’s result.

Default

SAP IQ SQL Reference


1826 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Requires SAP IQ SP 03 or later.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.60 DQP_ENABLED Option

Temporary database option DQP_ENABLED allows you to enable or disable distributed query processing at the
connection level.

Allowed Values

The allowed values differ depending on your DQP scenario:

● Regular DQP – ON, OFF


● DQP for a Logical Server Policy – 1, 2
DQP for a Logical Server Policy. Used when creating a shared-nothing multiplex. Used in conjunction with
the DQP_ENABLED_OVER_NETWORK option.
○ 1 – query processing is distributed using the IQ_SHARED_TEMP shared temporary dbspace.
○ 2 – query processing is distributed over the network using the high-speed TCP interconnect, and does
not use IQ_SHARED_TEMP.

SAP IQ SQL Reference


Database Options INTERNAL 1827
Default

● ON – regular DQP
● 1 – DQP for a Logical Server Policy.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

You can set the temporary database option DQP_ENABLED to OFF to disable DQP for the current connection.
You can set the option to ON (the default value) to enable DQP for the current connection, but only when DQP
is enabled for the user by that user's login policy for the logical server of the current connection.

Setting DQP_ENABLED to ON results in an error if DQP is disabled based upon the user's login policy:
Invalid setting for option 'DQP_ENABLED'

 Note

Any changes you make to a user's login policy options affect new connections only. Login policy option
settings for existing connections are based upon the time the connection was initially established.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1828 INTERNAL Database Options
10.6.61 (Deprecated) DQP_ENABLED_OVER_NETWORK
Option

Temporary database option DQP_ENABLED_OVER_NETWORK allows you to enable or disable distributed query
processing over the network at the connection level.

 Note

This option is deprecated and will be removed from the documentation in a future release.

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option for PUBLIC or for other user or
role. Can be set temporary for an individual or public.

Remarks

You can set the temporary database option DQP_ENABLED_OVER_NETWORK to ON to enable DQP over the
network for the current connection. The OFF (default) setting has no effect, and the setting of the
DQP_ENABLED logical server policy option determines whether or not DQP is used over the network for
queries on the current connection.

LS Policy Option Setting Database Option Setting DQP Query Behavior

DQP_ENABLED 1 DQP_ENABLED_OVER_NETWORK ON Queries on the current connection


execute over network. Other
queries use the shared temporary
store.

DQP_ENABLED 2 DQP_ENABLED_OVER_NETWORK ON All queries execute over network.


When DQP_ENABLED = 2 and
DQP_ENABLED_OVER_NETWOR
K = ON, queries do not use
SHARED_TEMP. The worker
node's temporary store is used to

SAP IQ SQL Reference


Database Options INTERNAL 1829
LS Policy Option Setting Database Option Setting DQP Query Behavior

process the work unit allocated


for that node (such as sorting)
and the results are shipped to the
leader node.

DQP_ENABLED 2 DQP_ENABLED OFF All queries run in SAP IQ server


mode.

 Note

Any changes you make to a logical server policy option affect new connections only. Logical server policy
options for existing connections are based on the time that the connection was initially established.

Related Information

DQP_OPTIONS13 Option [page 1830]


DQP_TCP_TIMEOUT Option [page 1832]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.62 DQP_OPTIONS13 Option

Enables TCP-based remote procedure calls for distributed query processing.

Allowed Values

ON, OFF

Default

ON

SAP IQ SQL Reference


1830 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The DQP_OPTIONS13 option enables the use of remote procedure calls based on TCP/IP. When the option
value is OFF, SAP IQ uses MIPC for DQP communications among worker and leader nodes. This option is only
valid when the temporary database option DQP_ENABLED_OVER_NETWORK is set ON, or when you enable
DQP by setting the logical server policy as follows:

ALTER LS POLICY ROOT DQP_ENABLED = 2;

Remember that changes made to a logical server policy option affect new connections only. Logical server
policy options for existing connections are based on the time that the connection was initially established.

Related Information

ALTER LS POLICY Statement [page 1158]


(Deprecated) DQP_ENABLED_OVER_NETWORK Option [page 1829]
DQP_TCP_TIMEOUT Option [page 1832]
DQP_TCP_TIMEOUT Option [page 1832]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1831
10.6.63 DQP_TCP_TIMEOUT Option

Specifies a timeout value (in seconds) that influences the system-calculated timeout value for individual TCP
remote procedure calls (RPCs) used in multiplex internal communications for distributed query processing.

Allowed Values

1 to 4,294,967,295 (seconds)

Default

60 (seconds)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The supplied value influences the timeout value of an RPC; it does not define the actual system-calculated
timeout value. SAP IQ considers the value of DQP_TCP_TIMEOUT, but also considers the amount of data to be
processed, and the data transfer speed. SAP IQ may override your DQP_TCP_TIMEOUT value based on its
calculation.

If the timeout using the value you supplied in DQP_TCP_TIMEOUT is less than the computed timeout suing the
default value, then SAP IQ chooses the default.

Related Information

DQP_OPTIONS13 Option [page 1830]


(Deprecated) DQP_ENABLED_OVER_NETWORK Option [page 1829]
DQP_OPTIONS13 Option [page 1830]

SAP IQ SQL Reference


1832 INTERNAL Database Options
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.64 EARLY_PREDICATE_EXECUTION Option

Controls whether simple local predicates are executed before query optimization.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If this option is ON (the default), the optimizer finds, prepares, and executes predicates containing only local
columns and constraints before query optimization, including join ordering, join algorithm selection, and
grouping algorithm selection, so that the values of “Estimated Result Rows” in the query plan are more precise.
If this option is OFF, the optimizer finds and prepares the simple predicates, but does not execute them before
query optimization. The resulting values of “Estimated Result Rows” are less precise, if the predicates are not
executed.

In general, EARLY_PREDICATE_EXECUTION should always be left ON, as this results in improved query plans
for many queries.

SAP IQ SQL Reference


Database Options INTERNAL 1833
When EARLY_PREDICATE_EXECUTION is ON, SAP IQ executes the local predicates for all queries before
generating a query plan, even when the NOEXEC option is ON. The generated query plan is the same as the
runtime plan.

This information is included in the query plan for the root node:

● Threads used for executing local invariant predicates – if greater than 1, indicates parallel execution of local
invariant predicates.
● Early_Predicate_Execution – indicates if the option is OFF.
● Time of Cursor Creation – the time of cursor creation.

The simple predicates for which execution is controlled by this option are referred to as invariant predicates in
the query plan. This information is included in the query plan for a leaf node, if there are any local invariant
predicates on the node:

● Generated Post Invariant Predicate Rows – actual result after executing local invariant predicate
● Estimated Post Invariant Predicate Rows – calculated by using estimated local invariant predicates
selectivity
● Time of Condition Start – starting time of the execution of local invariant predicates
● Time of Condition Done – ending time of the execution of local invariant predicates
● Elapsed Condition Time – elapsed time for executing local invariant predicates

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.65 ENABLE_ASYNC_IO Option

Allows a DBA to enable or disable the asynchronous IO used by the RLV persistence log.

Allowed Values

ON, OFF

A change in value requires a database close and re-open, or a server restart.

Default

ON

SAP IQ SQL Reference


1834 INTERNAL Database Options
Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. If permitted, can be set for an arbitrary other user or role, or for all
users via the role. Takes effect immediately.

10.6.66 ENABLE_LOB_VARIABLES Option

Controls the data type conversion of large object variables.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

ENABLE_LOB_VARIABLES controls the data type conversion of large object variables.

When ENABLE_LOB_VARIABLES is OFF, large object variables less than 32 K are implicitly converted; an error
is reported if a large object variable is greater than or equal to 32 K. A LONG VARCHAR variable is implicitly

SAP IQ SQL Reference


Database Options INTERNAL 1835
converted to a VARCHAR data type and truncated at 32 K. A LONG BINARY variable is implicitly converted to a
VARBINARY data type and truncated at 32 K.

When ENABLE_LOB_VARIABLES is ON, large object variables of any size retain their original data type and size.

Example

Retain the data type and size of large object variables greater than 32 K:

SET TEMPORARY OPTION ENABLE_LOB_VARIABLES = ON

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.67 EXTENDED_JOIN_SYNTAX Option

Controls whether queries with an ambiguous syntax for multi-table joins are allowed or are reported as an
error.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


1836 INTERNAL Database Options
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option reports a syntax error for those queries containing outer joins that have ambiguous syntax due to
the presence of duplicate correlation names on a null-supplying table.

This join clause illustrates the kind of query that is reported where C1 is a condition:

( R left outer join T , T join S on ( C1 ) )

If EXTENDED_JOIN_SYNTAX is set to ON, this query is interpreted as follows, where C1 and C2 are conditions:

( R left outer join T on ( C1 ) ) join S on ( C2 )

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.68 FILE_PREALLOCATE_SAMPLING_THRESHOLD
Option

Speeds up dbfile creation time if the underlying file system is slow.

Allowed Values

0 to 10,000 (milliseconds)

Default

10 (milliseconds)

SAP IQ SQL Reference


Database Options INTERNAL 1837
Scope

● You can only set this option at the database (PUBLIC) level.
● You need the DBA privilege to set this option.
● You need the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

If you suspect a slow file system, check the .iqmsg file for messages like these:

I. 03/30 11:31:05. 0000013261 139619391600384 Info: posix_fallocate fd=627


sample time 0.220000 sec.
I. 03/30 11:31:05. 0000013261 139619391600384 Info: posix_fallocate fd=627
second sample time 0.000000 sec.
I. 03/30 11:31:05. 0000013261 139619391600384 Info: posix_fallocate fd=627
sample time 0.000000 sec.
I. 03/30 11:31:05. 0000013261 139619391600384 Info: using posix_fallocate
fd=627. Sampling threshold was 0.050000 sec.

Convert the current value of FILE_PREALLOCATE_SAMPLING_THRESHOLD to seconds and compare it to the


values of sample time and second sample time. If the lower of sample time and second sample time exceeds
the value of FILE_PREALLOCATE_SAMPLING_THRESHOLD, set
FILE_PREALLOCATE_SAMPLING_THRESHOLD to a value greater than the smaller of the sample time and
second sample time values.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.69 FLOATING_POINT_ACCUMULATOR Option

Controls which accumulator to use for SUM or AVG of floating-point numbers.

Allowed Values

1, 2, 3

SAP IQ SQL Reference


1838 INTERNAL Database Options
Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Setting 1 (fast accumulator) is faster and uses less space for floats and doubles than setting 2. This setting
uses a single double precision variable to add double and float numbers, and is subject to the known accuracy
limitations of such an approach.

Setting 2 (default) (medium accumulator) uses multiple double precision variables to accumulate floats and
doubles. It is very accurate for addends in the range of magnitudes 1e-20 to 1e20. While it loses some accuracy
outside of this range, it is still accurate enough for most applications. Setting 2 allows the optimizer to choose
hash for faster performance more easily than setting 3.

Setting 3 (large accumulator) is highly accurate for all floats and doubles, but its size often precludes the use of
hash optimization, which will be a performance limitation for most applications.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1839
10.6.70 FORCE_DROP Option

Causes SAP IQ to leak, rather than reclaim, database disk space during a DROP command.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set as a temporary option only, for an individual connection or for the PUBLIC role, for the
duration of the current connection.
● Requires SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

You must drop a corrupt index, column or table and set the FORCE_DROP option to ON. This prevents the free
list from being incorrectly updated from incorrect or suspect file space allocation information in the object
being dropped. After dropping corrupt objects, you can reclaim the file space using the -iqfrec and -
iqdroplks server switches.

When force dropping objects, you must ensure that only the DBA is connected to the database. The server
must be restarted immediately after a force drop.

 Caution

Do not attempt to force drop objects unless SAP Technical Support has instructed you to do so.

FORCE_DROP procedures for system recovery and database repair are described in SAP IQ Administration:
Backup, Restore, and Data Recovery.

Related Information

Set a Database Option [page 1727]

SAP IQ SQL Reference


1840 INTERNAL Database Options
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.71 FORCE_NO_SCROLL_CURSORS Option

Forces all cursors to be non-scrolling.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

By default, all cursors are scrolling. Scrolling cursors with no host variable declared cause SAP IQ to create a
buffer for temporary storage of results. Each row in the result set is stored to allow for backward scrolling.

Setting FORCE_NO_SCROLL_CURSORS to ON reduces temporary storage requirements. This option can be


useful if you are retrieving very large numbers (millions) of rows. However if your front-end application makes
frequent use of backward-scrolling cursor operations, query response will be faster with this option set to OFF.

If your front-end application rarely performs backward-scrolling, make FORCE_NO_SCROLL_CURSORS = 'ON'


a permanent PUBLIC option, to use less memory and improve query performance.

SAP IQ SQL Reference


Database Options INTERNAL 1841
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.72 FORCE_UPDATABLE_CURSORS Option

Controls whether cursors that have not been declared as updatable can be updated.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When FORCE_UPDATABLE_CURSORS is ON, cursors that have not been declared as updatable can be updated.
This option allows updatable cursors to be used in front-end applications without specifying the FOR UPDATE
clause of the DECLARE CURSOR statement.

 Caution

Do not use FORCE_UPDATABLE_CURSORS unless absolutely necessary.

SAP IQ SQL Reference


1842 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.73 FP_LOOKUP_SIZE Option

Specifies the number of lookup pages and cache memory allocated for Lookup FP indexes in SAP IQ 15.
databases.

Allowed Values

1 to 4096 (MB)

Default

16 (MB)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Dependencies

FP_LOOKUP_SIZE applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is set to ON. If it is


set to OFF, the database engine ignores this option.

Remarks

If IQ UNIQUE is ON, FP_LOOKUP_SIZE controls the maximum number of lookup pages.

SAP IQ SQL Reference


Database Options INTERNAL 1843
FP_LOOKUP_SIZE must be set public, so the allowed syntax is:

SET OPTION public.FP_LOOKUP_SIZE = 1

 Note

The FP_NBIT_IQ15_COMPATIBILITY option provides tokenized FP support similar to that available in


SAP IQ 15, not complete database compatibility. All SAP IQ 15 runtime behavior is available using the SAP
IQ interface. Avoid running a 16.1 database with FP_NBIT_IQ15_COMPATIBILITY set to ON.

Related Information

FP_LOOKUP_SIZE_PPM Option [page 1844]


MINIMIZE_STORAGE Option [page 1925]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.74 FP_LOOKUP_SIZE_PPM Option

Controls the amount of main buffer cache allocated to FP indexes in SAP IQ 15databases.

Allowed Values

1 to 1,000,000

Default

2500

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

SAP IQ SQL Reference


1844 INTERNAL Database Options
Dependencies

FP_LOOKUP_SIZE_PPM applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is set to ON. If


set to OFF, SAP IQ ignores this option.

Remarks

If FP_NBIT_IQ15_COMPATIBILITY is ON, FP_LOOKUP_SIZE_PPM controls the maximum number of lookup


pages and restricts this number to a parts-per-million value of main memory, that is, the value of
FP_LOOKUP_SIZE_PPM * size of main memory / 1,000,000, where the size of main memory is
specified by the -iqmc server startup parameter.

 Note

The FP_NBIT_IQ15_COMPATIBILITY option provides tokenized FP support similar to that available in


SAP IQ 15, not complete database compatibility. All SAP IQ 15 runtime behavior is available using the SAP
IQ interface. Avoid running a 16.1 database with FP_NBIT_IQ15_COMPATIBILITY set to ON.

Related Information

FP_LOOKUP_SIZE Option [page 1843]


MINIMIZE_STORAGE Option [page 1925]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.75 FP_NBIT_AUTOSIZE_LIMIT Option

Limits the number of distinct values in columns that implicitly load as NBit FP.

Allowed Values

0 to 2,147,483,647

SAP IQ SQL Reference


Database Options INTERNAL 1845
Default

1,048,576

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Dependencies

FP_NBIT_AUTOSIZE_LIMIT applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is set to


OFF. If ON, the database engine ignores this option.

Remarks

FP_NBIT_AUTOSIZE_LIMIT limits the number of distinct values in all newly created columns without an
explicit IQ UNIQUE setting. Columns constrained by the FP_NBIT_AUTOSIZE_LIMIT option load with a Flat
FP or NBit FP index:

● If FP_NBIT_AUTOSIZE_LIMIT is greater than 0 and less than 2,147,483,647, columns load with an NBit
FP index
● If FP_NBIT_AUTOSIZE_LIMIT equals 0, columns load with a Flat FP index

FP_NBIT_AUTOSIZE_LIMIT and FP_NBIT_LOOKUP_MB establish a ceiling for sizing NBit columns during
data loads. As long as the number of distinct values is less than FP_NBIT_AUTOSIZE_LIMIT and the total
dictionary size (values and counts) per column is less the FP_NBIT_LOOKUP_MB, the column loads as an NBit.
If the load exceeds the FP_NBIT_AUTOSIZE_LIMIT but is less than FP_NBIT_ROLLOVER_MAX_MB, the column
rolls over to Flat FP.

If FP_ENFORCE_LIMITS is set to ON and DML operations exceed the FP_NBIT_ROLLOVER_MAX_MB, the


operations roll back and report an error. If the FP_NBIT_ENFORCE_LIMITS is set to OFF, the column
transitions to the next NBit level.

sp_iqindexmetadata returns details about Flat FP or NBit FP columns. sp_iqrebuildindex can


change explicit or implicit NBit FP column limits, or reformat the default column index as Flat FP or NBit
FP.

SAP IQ SQL Reference


1846 INTERNAL Database Options
Additional Information

● SAP IQ SQL Reference > System Procedures > Alphabetical List of System Stored Procedures >
sp_iqrebuildindex
● SAP IQ SQL Reference > System Procedures » Alphabetical List of System Stored Procedures >
sp_iqindexmetadata

Related Information

FP_NBIT_ENFORCE_LIMITS Option [page 1847]


FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.76 FP_NBIT_ENFORCE_LIMITS Option

Enforces sizing limits for explicit and implicit NBit columns.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


Database Options INTERNAL 1847
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Dependencies

FP_NBIT_ENFORCE_LIMITS applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is set to


OFF. If set to ON, the database engine ignores this option.

Remarks

DML operations check the FP_NBIT_ENFORCE_LIMITS option when the number of distinct values in a column
exceeds the explicit limit set in an IQ UNIQUE constraint, which is above the FP_NBIT_AUTOSIZE value, or
when the dictionary size for an implicit NBit rollover exceeds the FP_NBIT_ROLLOVER_MAX_MB limit.

If FP_NBIT_ENFORCE_LIMITS is set to:

● ON – the DML operation throws an error and rolls back


● OFF – the DML operation continues and the NBit dictionary limits are ignored

sp_iqindexmetadata returns details about Flat FP or NBit FP columns. sp_iqrebuildindex can


change explicit or implicit NBit FP column limits, or reformat the default column index as Flat FP or NBit
FP.

Using sp_iqrebuildindex to increase the number of distinct values beyond current limits for a Flat FP
column when FP_NBIT_ENFORCE_LIMITS is set to ON, returns an error. If FP_NBIT_ENFORCE_LIMITS is OFF,
sp_iqrebuildindex rebuilds the index to the maximum token, which is the largest distinct value.

Related Information

FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]


FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
sp_iqrebuildindex Procedure [page 737]
sp_iqindexmetadata Procedure [page 679]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1848 INTERNAL Database Options
10.6.77 FP_NBIT_IQ15_COMPATIBILITY Option

Provides support for tokenized FP indexes similar to that available in SAP IQ 15.

Allowed Values

ON, OFF

Default

● OFF in all new 16.1 databases.


● ON in upgraded SAP IQ 15 databases.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The FP_NBIT_IQ15_COMPATIBILITY option provides tokenized FP support similar to that available in SAP IQ
15. All newly created and modified tokenized FP indexes in 16.1 will be NBit. The only 15 style FP(1),FP(2),
and FP(3) byte FP indexes available in 16.1 are those from an upgraded database that have had only Read-Only
activity.

The FP_NBIT_IQ15_COMPATIBILITY ON/OFF setting only pertains to tokenized FP creation and cut-off
behavior:

If FP_NBIT_IQ15_COMPATIBILITY='ON', the database engine:

● Enables the MINIMIZE_STORAGE, FP_LOOKUP_SIZE, FP_LOOKUP_SIZE_PPM options.


● Creates DATE data types as NBit FP, even if IQ UNIQUE(0) is specified.
● Rolls over to Flat FP at the 3 byte FP cutoff (16,777,216 distinct).
● Can tokenize data widths up to 255.

If FP_NBIT_IQ15_COMPATIBILITY is set to OFF:

SAP IQ SQL Reference


Database Options INTERNAL 1849
● MINIMIZE_STORAGE, FP_LOOKUP_SIZE, FP_LOOKUP_SIZE_PPM options are ignored.
● DATE data types are not automatically NBit.
● Data widths up to 32767 may be tokenized.
● NBit FP (tokenized) upper bound limit is NBit 31 (2,147,483,648 distinct values).
● NBit sizing options determine rollover behavior:
○ IQ UNIQUE(0) loads a column as Flat FP
○ Columns without IQ UNIQUE load as NBit up to the auto-size limits
○ Columns where IQ UNIQUE(<n>) is less than the auto-size limit load as NBit

 Note

The FP_NBIT_IQ15_COMPATIBILITY option provides tokenized FP support similar to that available in


SAP IQ 15, not complete database compatibility. All SAP IQ 15 runtime behavior is available using the SAP
IQ interface. Avoid running a 16.1 database with FP_NBIT_IQ15_COMPATIBILITY set to ON.

Related Information

FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]


FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
FP_LOOKUP_SIZE Option [page 1843]
FP_LOOKUP_SIZE_PPM Option [page 1844]
MINIMIZE_STORAGE Option [page 1925]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.78 FP_NBIT_LOOKUP_MB Option

Limits the total dictionary size per column for implicit NBit FP columns.

Allowed Values

1 to 4,294,967,295

SAP IQ SQL Reference


1850 INTERNAL Database Options
Default

64 (MB)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Dependencies

FP_NBIT_LOOKUP_MB applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is set to OFF. If


ON, the database engine ignores this option.

Remarks

FP_NBIT_AUTOSIZE_LIMIT and FP_NBIT_LOOKUP_MB establish a ceiling for sizing implicit NBit columns. As
long as the number of distinct values is less than FP_NBIT_AUTOSIZE_LIMIT and the total dictionary size
(values and counts) per column is less the FP_NBIT_LOOKUP_MB, the column loads with an NBit FP index.
Limits are enforced by the FP_NBIT_ENFORCE_LIMITS option.

DML operations that exceed the FP_NBIT_LOOKUP_MB limit rollover to a Flat FP index.

If an operation exceeds FP_NBIT_LOOKUP_MB and FP_NBIT_ROLLOVER_MAX_MB limits, and


FP_NBIT_ENFORCE_LIMITS is set to OFF, the NBit FP transitions to the next NBit level.

sp_iqindexmetadata returns details about Flat FP or NBit FP columns. sp_iqrebuildindex can


change explicit or implicit NBit FP column limits, or reformat the default column index as Flat FP or NBit
FP.

Additional Information

sp_iqrebuildindex Procedure and sp_iqindexmetadata Procedure in SAP IQ SQL Reference.

SAP IQ SQL Reference


Database Options INTERNAL 1851
Related Information

FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]


FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
sp_iqindexmetadata Procedure [page 679]
sp_iqrebuildindex Procedure [page 737]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.79 FP_NBIT_ROLLOVER_MAX_MB Option

Sets a threshold for the total dictionary size for implicit NBit rollovers to Flat FP.

Allowed Values

1 to 4,294,967,295

Default

16384 KB

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1852 INTERNAL Database Options
Dependencies

FP_NBIT_ROLLOVER_MAX_MB applies to databases running where FP_NBIT_IQ15_COMPATIBILITY is 'OFF.'


If it is set to 'ON,' the database engine ignores this option.

Remarks

FP_NBIT_AUTOSIZE_LIMIT and FP_NBIT_LOOKUP_MB establish a ceiling for sizing implicit NBit FP


columns. DML operations that exceed these values check the FP_NBIT_ROLLOVER_MAX_MB limit, which sets
the dictionary size (values and counts) for implicit NBit rollovers:

● If the total dictionary size per column does not exceed the FP_NBIT_ROLLOVER_MAX_MB, the NBit column
rolls over to a Flat FP.
● If the dictionary size exceeds the FP_NBIT_ROLLOVER_MAX_MB limit and
FP_NBIT_ENFORCE_LIMITS='ON', DML operations throw an error and roll back.
● If the dictionary size exceeds the FP_NBIT_ROLLOVER_MAX_MB limit and
FP_NBIT_ENFORCE_LIMITS='OFF' (default), DML operations keep running, and the NBit dictionary
continues to grow.
● If FP_NBIT_ROLLOVER_MAX_MB='0', the NBit column rolls over to Flat FP.

sp_iqindexmetadata returns details about Flat FP or NBit FP columns. sp_iqrebuildindex can


change explicit or implicit NBit FP column limits, or reformat the default column index as Flat FP or NBit
FP.

Additional Information

sp_iqrebuildindex Procedure and sp_iqindexmetadata Procedure in SAP IQ SQL Reference.

Related Information

FP_NBIT_AUTOSIZE_LIMIT Option [page 1845]


FP_NBIT_ENFORCE_LIMITS Option [page 1847]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
FP_NBIT_LOOKUP_MB Option [page 1850]
FP_NBIT_ROLLOVER_MAX_MB Option [page 1852]
sp_iqrebuildindex Procedure [page 737]
sp_iqindexmetadata Procedure [page 679]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1853
10.6.80 FP_PREDICATE_WORKUNIT_PAGES Option

Specifies degree of parallelism used in the default index.

Allowed Values

Integer

Default

200

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The default index calculates some predicates such as SUM, RANGE, MIN, MAX and COUNT DISTINCT in
parallel. FP_PREDICATE_WORKUNIT_PAGES affects the degree of parallelism used by specifying the number of
pages worked on by each thread. To increase the degree of parallelism, decrease the value of this option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1854 INTERNAL Database Options
10.6.81 FPL_EXPRESSION_MEMORY_KB Option

Controls the use of memory for the optimization of queries involving functional expressions against columns
having enumerated storage.

Allowed Values

0 to 20,000

Default

1024 (KB)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

FPL_EXPRESSION_MEMORY_KB controls the use of memory for the optimization of queries involving functional
expressions against columns having enumerated storage. The option enables the DBA to constrain the
memory used by this optimization and balance it with other SAP IQ memory requirements, such as caches.
Setting this option to 0 switches off optimization.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1855
10.6.82 GARRAY_FILL_FACTOR_PERCENT Option

Specifies the percent of space on each HG garray page to reserve for future incremental inserts into existing
groups.

Allowed Values

0 to 1000

Default

25

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The garray tries to pad out each group to include a pad of empty space set by the value. This space is used for
rows added to existing index groups.

An HG index can reserve some storage on a per-group basis (where group is defined as a group of rows with
equivalent values). Reserving space consumes additional disk space, but can help the performance of
incremental inserts into the HG index.

If you plan to do future incremental inserts into an HG index, and those new rows have values that are already
present in the index, a nonzero value for this option might improve incremental insert performance.

If you do not plan to incrementally update the index, you can reduce the values of this option to save disk
space.

SAP IQ SQL Reference


1856 INTERNAL Database Options
Related Information

GARRAY_PAGE_SPLIT_PAD_PERCENT Option [page 1858]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.83 GARRAY_INSERT_PREFETCH_SIZE Option

Specifies number of pages used for prefetch.

Allowed Values

0 to 100

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option defines the number of database pages read ahead during an insert to a column that has an HG
index.

Do not set this option unless advised to do so by Technical Support.

SAP IQ SQL Reference


Database Options INTERNAL 1857
Related Information

GARRAY_FILL_FACTOR_PERCENT Option [page 1856]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.84 GARRAY_PAGE_SPLIT_PAD_PERCENT Option

Determines per-page fill factor during page splits on the garray and specifies the percent of space on each HG
garray page to reserve for future incremental inserts.

Allowed Values

0 to 100

Default

25

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Splits of a garray page try to leave that percentage empty. This space is used for rows added to new index
groups.

SAP IQ SQL Reference


1858 INTERNAL Database Options
An HG index can reserve storage at the page level that can be allocated to new groups when additional rows are
inserted. Reserving space consumes additional disk space, but can help the performance of incremental
inserts into the HG index.

If future plans include incremental inserts into an HG index, and the new rows do not have values that are
already present in the index, a nonzero value for GARRAY_PAGE_SPLIT_PAD_PERCENT could improve
incremental insert performance.

If you do not plan to incrementally update the index, you can reduce the values of this option to save disk
space.

Related Information

GARRAY_FILL_FACTOR_PERCENT Option [page 1856]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.85 GARRAY_RO_PREFETCH_SIZE Option

Specifies number of pages used for prefetch.

Allowed Values

0 to 100

Default

10

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


Database Options INTERNAL 1859
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option defines the number of database pages read ahead during a query to a column that has an HG index.

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.86 HASH_PINNABLE_CACHE_PERCENT Option

Controls the maximum percentage of a user’s temp memory that a hash object can pin.

Allowed Values

0 to 100

Default

20

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1860 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

HASH_PINNABLE_CACHE_PERCENT controls the percentage of a user’s temp memory allocation that any one
hash object can pin in memory. The default is 20%, but you should reduce this number to 10% if you are
running complex queries, or increase this number to 50% if you have simple queries that need a single large
hash object to run, such as a large IN subquery.

HASH_PINNABLE_CACHE_PERCENT is for use by primarily Technical Support. If you change the value of it, do
so with extreme caution; first analyze the effect on a wide variety of queries.

Related Information

BIT_VECTOR_PINNABLE_CACHE_PERCENT Option [page 1772]


SORT_PINNABLE_CACHE_PERCENT Option [page 2013]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.87 HASH_THRASHING_PERCENT Option

Specifies the percent of hard disk I/Os allowed during the execution of a statement that includes a query
involving hash algorithms, before the statement is rolled back and an error message is reported.

Allowed Values

0 to 100

Default

10

SAP IQ SQL Reference


Database Options INTERNAL 1861
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If a query that uses hash algorithms causes an excessive number of hard disk I/Os (paging buffers from
memory to disk), query performance is negatively affected, and server performance might also be affected.
HASH_THRASHING_PERCENT controls the percentage of hard disk I/Os allowed before the statement is rolled
back, and you see one of the following error messages:

● Hash insert thrashing detected.


● Hash find thrashing detected.

The default value of HASH_THRASHING_PERCENT is 10%. Increasing this value permits more paging to disk
before a rollback and decreasing this value permits less paging before a rollback.

Related Information

HASH_PINNABLE_CACHE_PERCENT Option [page 1860]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.88 HG_DELETE_METHOD Option

Specifies the algorithm used during a delete in a HG index.

Allowed Values

0 to 3

SAP IQ SQL Reference


1862 INTERNAL Database Options
Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option chooses the algorithm used by the HG index during a delete operation. The cost model considers
both CPU- and I/O-related in selecting the appropriate delete algorithm. The cost model takes the following
into account:

● Rows deleted
● Index size
● Width of index data type
● Cardinality of index data
● Available temporary cache
● Machine related I/O and CPU characteristics
● Available CPUs and threads
● Referential integrity costs

You can force different methods by setting the following options:

● To force a “small” method, set this option to 1.


● To force the “large” method, set the option to 2.
● To force a “midsize” method, set the option to 3.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1863
10.6.89 HG_SEARCH_RANGE Option

Specifies the maximum number of Btree pages used in evaluating a range predicate in the HG index.

Allowed Values

Integer

Default

10

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The default setting of this option is appropriate for most queries.

This option effectively controls the amount of time the optimizer spends searching for the best index to use for
a range predicate. Setting this option higher may cause a query to spend more time in the optimizer, but as a
result may choose a better index to resolve a range predicate.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1864 INTERNAL Database Options
10.6.90 HTTP_SESSION_TIMEOUT Option

Specifies the amount of time, in minutes, that the client waits for an HTTP session to time out before giving up.

Allowed Values

0 to 525,600

Default

30

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option provides variable session timeout control for Web service applications. A Web service application
can change the timeout value from within any request that owns the HTTP session, but a change to the timeout
value can impact subsequent queued requests if the HTTP session times out. The Web application must
include logic to detect whether a client is attempting to access an HTTP session that no longer exists. This can
be done by examining the value of the SessionCreateTime connection property to determine whether a
timestamp is valid: if the HTTP request is not associated with the current HTTP session, the
SessionCreateTime connection property contains an empty string.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1865
10.6.91 IDENTITY_ENFORCE_UNIQUENESS Option

Creates a unique HG index on each IDENTITY/AUTOINCREMENT column, if the column is not already a primary
key.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When option is set ON, HG indexes are created on future identity columns. The index can only be deleted if the
deleting user is the only one using the table and the table is not a local temporary table.

Related Information

QUERY_PLAN Option [page 1964]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1866 INTERNAL Database Options
10.6.92 IDENTITY_INSERT Option

Enables users to insert values into or to update an IDENTITY or AUTOINCREMENT column.

Allowed Values

= '<tablename>'

Default

Option not set.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

 Note

If you set a user level option for the current option, the corresponding temporary option is also set. See
Scope and Duration of Database Options.

Remarks

When IDENTITY_INSERT is set, insert/update is enabled. A table name must be specified to identify the
column to insert or update. If you are not the table owner, qualify the table name with the owner name.

To drop a table with an IDENTITY column, IDENTITY_INSERT must not be set to that table.

Examples

If you use the table Employees to run explicit inserts:

SET TEMPORARY OPTION IDENTITY_INSERT = 'DBA.Employees'

SAP IQ SQL Reference


Database Options INTERNAL 1867
To turn the option off, specify the equals sign and an empty string:

SET TEMPORARY OPTION IDENTITY_INSERT = ''

Illustrates the effect of user level options on temporary options (see Note), if you are connected to the
database as DBA and enter:

SET OPTION IDENTITY_INSERT = 'Customers'

The value for the option is set to Customers for the user DBA and temporary for the current connection. Other
users who subsequently connect to the database as DBA find their option value for IDENTITY_INSERT is
Customers also.

Related Information

Scope and Duration of Database Options [page 1723]


QUERY_PLAN Option [page 1964]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.93 IN_SUBQUERY_PREFERENCE Option

Controls the choice of algorithms for processing an IN subquery.

Allowed Values

-3 to 3

● -3 – avoids hash-based IN subquery


● -2 – avoids vertical IN subquery
● -1 – avoids sort-based IN subquery
● 0 – lets the optimizer choose
● 1 – prefers sort-based IN subquery
● 2 – prefers vertical IN subquery (where a subquery is a child of a leaf node in the query plan)
● 3 – prefers hash-based IN subquery

SAP IQ SQL Reference


1868 INTERNAL Database Options
Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The IQ optimizer has a choice of several algorithms for processing IN subqueries. This option allows you to
override the optimizer's costing decision when choosing the algorithm to use. It does not override internal rules
that determine whether an algorithm is legal within the query engine.

IN_SUBQUERY_PREFERENCE is normally used for internal testing and for manually tuning queries that the
optimizer does not handle well. Only experienced DBAs should use it. The only reason to use this option is if the
optimizer seriously underestimates the number of rows produced by a subquery, and the hash object is
thrashing. Before setting this option, try to improve the mistaken estimate by looking for missing indexes and
dependent predicates.

Inform Technical Support if you need to set IN_SUBQUERY_PREFERENCE, as setting this option might mean
that a change to the optimizer is appropriate.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1869
10.6.94 INDEX_ADVISOR Option

Generates messages suggesting additional column indexes that may improve performance of one or more
queries.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When set ON, the index advisor prints index recommendations as part of the query plan or as a separate
message in the message log file, if query plans are not enabled. These messages begin with the string “Index
Advisor:” and you can use that string to search and filter them from a message file. The output is in
OWNER.TABLE.COLUMN format.

Set both INDEX_ADVISOR and INDEX_ADVISOR_MAX_ROWS to accumulate index advice.

 Note

When INDEX_ADVISOR_MAX_ROWS is set ON, index advice will not be written to the message file as
separate messages. Advice will, however, continue to be displayed on query plans in the message file.

SAP IQ SQL Reference


1870 INTERNAL Database Options
Situation Recommendation

Local predicates on a single column where an HG, HNG, DATE, TIME Add an <index-type> index to column col.
or DATETIME index would be desirable, as appropriate.

Single column join keys where an HG index would be useful. Add an HG index to join key col.

Single column candidate key indexes where an HG exists, but could be Change join key col to a unique HG index.
changed to a unique HG index.

Join keys have mismatched data types, and regenerating one column Make join keys col1 and col2 identical data types
with a matched data type would be beneficial.

Subquery predicate columns where an HG index would be useful. Add an HG index to subquery column col

Grouping columns where an HG index would be useful. Create an HG index on grouping column col

Single-table intercolumn comparisons where the two columns are Create a CMP index on col1, col2
identical data types, a CMP index are recommended.

Columns where an HG index exists, and the number of distinct values Use the sp_iqrebuildindex stored procedure
allows, suggest converting the FP to a 1 or 2-byte FP index. to rebuild col as Nbit.

Very large tables joined with an expensive join algorithm. Consider either hash partitioning table
<tablename>, or tables <tablename1> and
<tablename2>

It is up to you to decide how many queries benefit from the additional index and whether it is worth the expense
to create and maintain the indexes. In some cases, you cannot determine how much, if any, performance
improvement results from adding the recommended index.

For example, consider columns used as a join key. SAP IQ uses metadata provided by HG indexes extensively to
generate better/faster query plans to execute the query. Putting an HG index on a join column without one
makes the IQ optimizer far more likely to choose a faster join plan, but without adding the index and running
the query again, it is very hard to determine whether query performance stays the same or improves with the
new index.

Examples

Index advisor output with query plan set OFF:

I. 03/30 14:18:45. 0000000002 Advice: Add HG index


on DBA.ta.c1 Predicate: (ta2.c1 < BV(1))

Index advisor output with query plan set ON:

I. 03/30 14:53:24. 0000000008 [20535]: 6 ...#03: Leaf


I. 03/30 14:53:24. 0000000008 [20535]: Table Name: tb
I. 03/30 14:53:24. 0000000008 [20535]: Condition 1 (Invariant):
(tb.c3 =tb.c4)

SAP IQ SQL Reference


Database Options INTERNAL 1871
I. 03/30 14:53:24. 0000000008 [20535]: Condition 1 Index Advisor:
Add a CMP index on DBA.tb (c3,c4)

 Note

This method accumulates index advisor information for multiple queries, so that advice for several queries
can be tracked over time in a central location.

Related Information

FP_LOOKUP_SIZE Option [page 1843]


INDEX_ADVISOR_MAX_ROWS Option [page 1872]
QUERY_PLAN Option [page 1964]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.95 INDEX_ADVISOR_MAX_ROWS Option

Sets the maximum number of unique advice messages stored by the index advisor to max_rows.

Allowed Values

0 to 4,294,967,295

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1872 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Setting the option to 0 (the default) disables the collection of index advice.

INDEX_ADVISOR_MAX_ROWS limits the number of messages stored by the index advisor. Once the specified
limit has been reached, the INDEX_ADVISOR will not store new advice. It will, however, continue to update
counts and timestamps for existing advice messages.

SET OPTION public.Index_Advisor_Max_Rows = max_rows;

Related Information

FP_LOOKUP_SIZE Option [page 1843]


INDEX_ADVISOR Option [page 1870]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.96 INDEX_PREFERENCE Option

Controls the choice of indexes to use for queries.

Allowed Values

The values control the following:

● -10 – avoid DTTM indexes


● -9 – avoid TIME indexes
● -8 – avoid DATE indexes
● -6 – avoid WD indexes
● -5 – avoid the default index
● -4 – avoid CMP indexes
● -3 – avoid HNG indexes
● -2 – avoid HG indexes

SAP IQ SQL Reference


Database Options INTERNAL 1873
● -1 – avoid LF indexes
● 0 – (default) let the optimizer choose
● 1 – prefer LF indexes
● 2 – prefer HG indexes
● 3 – prefer HNG indexes
● 4 – prefer CMP indexes
● 5 – prefer the default index
● 6 – prefer WD indexes
● 8 – prefer DATE indexes
● 9 – prefer TIME indexes
● 10 – prefer DTTM indexes

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The SAP IQ optimizer normally chooses the best index available to process local WHERE clause predicates and
other operations that can be done within an IQ index. INDEX_PREFERENCE is used to override the optimizer
choice for testing purposes; under most circumstances, it should not be changed.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1874 INTERNAL Database Options
10.6.97 INFER_SUBQUERY_PREDICATES Option

Controls the optimizer’s inference of additional subquery predicates.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

INFER_SUBQUERY_PREDICATES controls whether the optimizer is allowed to infer additional subquery


predicates from an existing subquery predicate through transitive closure across a simple equality join
predicate. In most cases in which the optimizer chooses to make this inference, the query runs faster. There are
some exceptions to this performance improvement, so you may need to experiment to be sure that this option
is appropriate for your environment.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1875
10.6.98 IQ_LOG_MAX_SIZE Option

Sets the maximum size of the point-in-time recovery archive in megabytes.

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

The point-in-time recovery archive increases in size with each update sequence. The default setting of 0 allows
the archive to increase without limit. Setting IQ_LOG_MAX_SIZE to a specific value limits the size of the
archive:

SET OPTION PUBLIC.IQ_LOG_MAX_SIZE = '1000' //sets the max size of the archive
to 1000 MB

If the archive exceeds the size limit, the server creates a new archive in the point-in-time recovery archive
directory. Size limits are expressed in megabytes.

Related Information

IQ_POINT_IN_TIME_RECOVERY_LOGGING Option [page 1879]


IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL Option [page 1878]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1876 INTERNAL Database Options
10.6.99 IQ_LOG_THRESHOLD_SIZE Option

Configures the log file threshold for point-in-time recovery.

Default

The default value differs depending on database size:

● Databases smaller than 1 TB – the default threshold size is to 10 percent of dbspace size or 2 GB,
whichever is greater.
● Larger databases – the threshold size is 1 percent of dbspace size.

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

To turn off threshold processing, set threshold size to 1 MB (the minimum reserved dbspace size is 200 MB).

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1877
10.6.100 IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTE
RVAL Option

Sets a time interval between automatic backups of the point in time recovery logs.

Allowed Values

0 to <num> minutes

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

The IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL option sets a time interval between automatic


backups of the point-in-time recovery log:

SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL='30' // backups


at 30 min intervals

The minimum supported backup interval is 5 minutes. Setting the


IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL to 0 (default) disables automatic backups.

Related Information

IQ_LOG_MAX_SIZE Option [page 1876]


IQ_POINT_IN_TIME_RECOVERY_LOGGING Option [page 1879]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1878 INTERNAL Database Options
10.6.101 IQ_POINT_IN_TIME_RECOVERY_LOGGING Option

Enables point-in-time recovery logging.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) level only.


● The DBA privilege is required to set this option.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

To enable point-in-time recovery logging:

1. Set IQ_POINT_IN_TIME_RECOVERY_LOGGING to 'ON':

SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'ON'

2. Use ALTER DBSPACE to identify the directory where you want to archive the recovery logs:

ALTER DBSPACE IQ_SYSTEM_LOG RENAME <new-directory-specification>/<file-prefix>

SAP IQ.db file by default. This command saves the log in another directory. The saves the point-in-time
recovery log in the same directory as the new-directory-specification must point to an existing
directory. For multiplex servers, the IQ_SYSTEM_LOG directory must reside on a shared file system and be
writable by all multiplex nodes. For other constraints, see Redirecting Log Output.
3. Perform the backup:

BACKUP DATABASE ...


TO <archive_device>

Point-in-time recovery logging only becomes fully enabled when the data backup begins. On multiplex servers,
all writers must be shut down during first data backup to enable PITR logging on the coordinator. After the
backup is complete, the administrator must synchronize all writers before starting them up.

SAP IQ SQL Reference


Database Options INTERNAL 1879
To disable point-in-time recovery logging, set the IQ_POINT_IN_TIME_RECOVERY_LOGGING option to OFF:

SET OPTION PUBLIC.IQ_POINT_IN_TIME_RECOVERY_LOGGING = 'OFF'

Setting this option to OFF disables point-in-time recovery immediately. To re-enable point-in-time recovery, you
must complete all steps in this procedure, including a FULL, INCREMENTAL, or INCREMENTAL SINCE FULL
backup.

Point-in-time recovery logging will be disabled during the following multiplex configuration changes:

● Multiplex failover
● Simplex to multiplex conversion
● Multiplex to simplex conversion

To re-enable point-in-time recovery after multiplex configuration changes, shut down all secondary nodes.
Allow some time to let the coordinator release all global free list allocations, then shut down the coordinator.
Restart the coordinator or new failover coordinator, then use the ALTER DBSPACE IQ_SYSTEM_LOG RENAME
command to rename the point-in-time recovery log. Perform a full data backup. Synchronize and restart all
secondary nodes.

Related Information

ALTER DBSPACE Statement [page 1136]


IQ_LOG_MAX_SIZE Option [page 1876]
IQ_POINT_IN_TIME_RECOVERY_LOG_BACKUP_INTERVAL Option [page 1878]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.102 IQ_SYSTEM_MAIN_ALLOCATION_RATIO Option

Controls the divisor for allocation of space from IQ_SYSTEM_MAIN dbspace for use by a multiplex writer.

Allowed Values

1 to 99

Default

16

SAP IQ SQL Reference


1880 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) level only.


● The DBA privilege is required to set this option.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

IQ_SYSTEM_MAIN_ALLOCATION_RATIO is a divisor for adjusting the requests from multiplex writers to the
multiplex coordinator when allocating IQ_SYSTEM_MAIN space for use by a writer. The default is 16, meaning
that if the requested amount of space from the writer is <B> blocks, then SAP IQ allocates SAP IQ blocks. This
behavior contrasts with requests for other main store dbspaces, where SAP IQ allocates the full <B> blocks.
The option lets you conserve IQ_SYSTEM_MAIN space, because the space is a critical resource and the default
allocation suitable for other dbspaces would be too large.

Related Information

IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD Option [page 1881]


IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD Option [page 1881]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.103 IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD Option

Controls the amount of space reserved in IQ_SYSTEM_MAIN that is kept free for recovery operations.

Allowed Values

0 to 99 (percent of IQ_SYSTEM_MAIN dbspace size)

Default

1 percent

SAP IQ SQL Reference


Database Options INTERNAL 1881
Scope

● Option can be set at the database (PUBLIC) level only.


● The DBA privilege is required to set this option.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option.

Remarks

SAP IQ reserves the percentage of the IQ_SYSTEM_MAIN dbspace specified by the


IQ_SYSTEM_MAIN_RECOVERY_THRESHOLD to use during database recovery after a server failure.

Related Information

IQ_SYSTEM_MAIN_ALLOCATION_RATIO Option [page 1880]


IQ_SYSTEM_MAIN_ALLOCATION_RATIO Option [page 1880]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.104 IQGOVERN_MAX_PRIORITY Option

Limits the allowed IQGOVERN_PRIORITY setting.

Allowed Values

1 to 3

Default

SAP IQ SQL Reference


1882 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Limits the allowed IQGOVERN_PRIORITY setting, which affects the order in which a user’s queries are queued
for execution. In the range of allowed values, 1 indicates high priority, 2 (the default) medium priority, and 3 low
priority. SAP IQ returns an error if a user sets IQGOVERN_PRIORITY higher than IQGOVERN_MAX_PRIORITY.

Related Information

IQGOVERN_PRIORITY Option [page 1883]


IQGOVERN_PRIORITY_TIME Option [page 1884]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.105 IQGOVERN_PRIORITY Option

Assigns a priority to each query waiting in the -iqgovern queue.

Allowed Values

1 to 3

Default

SAP IQ SQL Reference


Database Options INTERNAL 1883
Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Assigns a value that determines the order in which a user’s queries are queued for execution. In the range of
allowed values, 1 indicates high priority, 2 (the default) medium priority, and 3 low priority. This switch can be
set temporary per user or public by any user. Queries with a lower priority will not run until all higher priority
queries have executed.

This option is limited by the per user or per group value of the option IQGOVERN_MAX_PRIORITY. It cannot be
set to a value higher than the current user's IQGOVERN_MAX_PRIORITY value. For example, if the
IQGOVERN_MAX_PRIORITY for the current user (userA) is 2, userA cannot set the IQGOVERN_PRIORITY value
for userB to 1, since that is higher than 2. UserA can only complete this task, if IQGOVERN_MAX_PRIORITY
value for userA is first increased to 1.

Related Information

IQGOVERN_MAX_PRIORITY Option [page 1882]


IQGOVERN_PRIORITY_TIME Option [page 1884]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.106 IQGOVERN_PRIORITY_TIME Option

Limits the time a high priority query waits in the queue before starting.

Allowed Values

0 to 1,000,000 (seconds)

SAP IQ SQL Reference


1884 INTERNAL Database Options
Default

0 (disabled)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

Must be lower than IQGOVERN_MAX_PRIORITY.

Limits the time a high priority (priority 1) query waits in the queue before starting. When the limit is reached,
the query is started even if it exceeds the number of queries allowed by the -iqgovern setting. The range is
from 1 to 1,000,000 seconds. The default (0) disables this feature. IQGOVERN_PRIORITY_TIME must be set
PUBLIC.

Related Information

IQGOVERN_MAX_PRIORITY Option [page 1882]


IQGOVERN_PRIORITY Option [page 1883]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.107 ISOLATION_LEVEL Option

Controls the locking isolation level for catalog store tables.

Allowed Values

● 0 – Allow dirty reads, nonrepeatable reads, and phantom rows.


● 1 – Prevent dirty reads. Allow nonrepeatable reads and phantom rows.
● 2 – Prevent dirty reads and guarantee repeatable reads. Allow phantom rows.

SAP IQ SQL Reference


Database Options INTERNAL 1885
● 3 – Serializable. Do not allow dirty reads, guarantee repeatable reads, and do not allow phantom rows.

Default

● 0
● 1 for Open Client and JDBC connections

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

ISOLATION_LEVEL determines the isolation level for tables in the catalog store. SAP IQ always enforces level 3
for tables in the IQ store. Level 3 is equivalent to ANSI level 4.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.108 JAVA_LOCATION Option

Specifies the path of the Java VM for the database.

Allowed Values

String

SAP IQ SQL Reference


1886 INTERNAL Database Options
Default

Empty string

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

By default, this option contains an empty string. In this case, the database server searches the JAVA_HOME
environment variable, the path, and other locations for the Java VM.

Related Information

JAVA_VM_OPTIONS Option [page 1887]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.109 JAVA_VM_OPTIONS Option

Specifies command line options that the database server uses when it launches the Java VM.

Allowed Values

String

Default

Empty string

SAP IQ SQL Reference


Database Options INTERNAL 1887
Scope

● Option can be set at the database (PUBLIC) level only.


Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

JAVA_VM_OPTIONS specifies options that the database server uses when launching the Java VM specified by
the JAVA_LOCATION option. These additional options can be used to set up the Java VM for debugging
purposes or to run as a service on UNIX platforms. In some cases, additional options are required to use the
Java VM in 64-bit mode instead of 32-bit mode.

Related Information

JAVA_LOCATION Option [page 1886]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.110 JOIN_EXPANSION_FACTOR Option

Controls how conservative the optimizer’s join result estimates are in unusually complex situations.

Allowed Values

1 to 100

Default

30

SAP IQ SQL Reference


1888 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option controls how conservative the join optimizer’s result size estimates are in situations where an input
to a specific join has already passed through at least one intermediate join that can result in multiple copies of
rows projected from the table being joined.

A level of zero indicates that the optimizer should use the same estimation method above intermediate
expanding joins as it would if there were no intermediate expanding joins.

This results in the most aggressive (small) join result size estimates.

A level of 100 indicates that the optimizer should be much more conservative in its estimates whenever there
are intermediate expanding joins, and this results in the most conservative (large) join result size estimates.

Normally, you should not need to change this value. If you do, set JOIN_EXPANSION_FACTOR as a temporary
or user option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.111 JOIN_OPTIMIZATION Option

Enables or disables the optimization of the join order.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 1889
Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When JOIN_OPTIMIZATION is ON, SAP IQ optimizes the join order to reduce the size of intermediate results
and sorts, and to balance the system load. When the option is OFF, the join order is determined by the order of
the tables in the FROM clause of the SELECT statement.

JOIN_OPTIMIZATION should always be set ON.

JOIN_OPTIMIZATION controls the order of the joins, but not the order of the tables. To show the distinction,
consider this example FROM clause with four tables:

FROM A, B, C, D

By default, this FROM clause creates a left deep plan of joins that could also be explicitly represented as:

FROM (((A, B), C), D)

If JOIN_OPTIMIZATION is turned OFF, then the order of these joins on the sets of tables is kept precisely as
specified in the FROM clause. Thus A and B must be joined first, then that result must be joined to table C, and
then finally joined to table D. This option does not control the left/right orientation at each join. Even with
JOIN_OPTIMIZATION turned OFF, the optimizer, when given the above FROM clause, can produce a join plan
that looks like one of the following:

FROM ((C, (A, B)), D)

FROM (((B, A), C), D)

FROM (D, ((A, B), C))

In all of these cases, A and B are joined first, then that result is joined to C, and finally that result is joined to
table D. The order of the joins remains the same, but the order of the tables appears different.

SAP IQ SQL Reference


1890 INTERNAL Database Options
In general, if JOIN_OPTIMIZATION is turned OFF, you probably should use parentheses in the FROM clause, as
in the above examples, to make sure that you get the join order you want. If you want to join A and B to the join
of C and D, you can specify this join by using parentheses:

FROM ((A, B), (C, D))

Note that the above FROM clause is a different join order than the original example FROM clause, even though
all the tables appear in the same order.

JOIN_OPTIMIZATION should be set to OFF only to diagnose obscure join performance issues or to manually
optimize a small number of predefined queries. With JOIN_OPTIMIZATION turned OFF, queries can join up to
128 tables, but might also suffer serious performance degradation.

 Caution

If you turn off JOIN_OPTIMIZATION, SAP IQ has no way to ensure optimal performance for queries
containing joins. You assume full responsibility for performance aspects of your queries.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.112 JOIN_PREFERENCE Option

Controls the choice of algorithms when processing joins.

Allowed Values

● 0 – lets the optimizer choose


● 1 – prefers sort-merge
● 2 – prefers nested-loop
● 3 – prefers nested-loop push-down
● 4 – prefers hash
● 5 – prefers hash push-down
● 6 – prefers asymmetric sort-merge join
● 7 – prefers sort-merge push-down
● 8 – prefers asymmetric sort-merge push-down join
● 9 – prefers partitioned hash join if the join keys include all the partition keys of a hash partitioned table

SAP IQ SQL Reference


Database Options INTERNAL 1891
● 10 – prefers partitioned hash-push down join if the join keys include all the partition keys of a hash
partitioned table
● 11 – prefers partitioned sort-merge join if the join keys include all the partition keys of a hash partitioned
table
● 12 – prefers partitioned sort-merge push-down join if the join keys include all the partition keys of a hash
partitioned table
● -1 – avoids sort-merge
● -2 – avoids nested-loop
● -3 – avoids nested-loop push-down
● -4 – avoids hash
● -5 – avoids hash push-down
● -6 – avoids asymmetric sort-merge join
● -7 – avoids sort-merge push-down
● -8 – avoids asymmetric sort-merge push-down join
● -9 – avoids partitioned hash join if the join keys include all the partition keys of a hash partitioned table
● -10 – avoids partitioned hash-push down join if the join keys include all the partition keys of a hash
partitioned table
● -11 – avoids partitioned sort-merge join if the join keys include all the partition keys of a hash partitioned
table
● -12 – avoids partitioned sort-merge push-down join if the join keys include all the partition keys of a hash
partitioned table

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For joins within a query, the SAP IQ optimizer has a choice of several algorithms for processing the join.
JOIN_PREFERENCE allows you to override the optimizer’s cost-based decision when choosing the algorithm to
use. It does not override internal rules that determine whether an algorithm is legal within the query engine. If

SAP IQ SQL Reference


1892 INTERNAL Database Options
you set it to any nonzero value, every join in a query is affected; you cannot use it to selectively modify one join
out of several in a query, but join condition hint strings can do so.

This option is normally used for internal testing or tuning of report queries, and only experienced DBAs should
use it.

Simple equality join predicates can be tagged with a predicate hint that allows a join preference to be specified
for just that one join. If the same join has more than one join condition with a local join preference, and if those
hints are not the same value, then all local preferences are ignored for that join. Local join preferences do not
affect the join order chosen by the optimizer

This example requests a hash join:

AND (T.X = 10 * R.x, 'J:4')

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.113 JOIN_SIMPLIFICATION_THRESHOLD Option

Controls the minimum number of tables being joined together before any join optimizer simplifications are
applied.

Allowed Values

1 to 24

Default

12

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


Database Options INTERNAL 1893
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The query optimizer simplifies its optimization of join order by separate handling of both lookup tables (that is,
nonselective dimension tables) and tables that are effective Cartesian products. After simplification, it
optimizes the remaining tables for join order, up to the limit set by MAX_JOIN_ENUMERATION.

Setting this option to a value greater than the current value for MAX_JOIN_ENUMERATION has no effect.

Setting this value below the value for MAX_JOIN_ENUMERATION might improve the time required to optimize
queries containing many joins, but may also prevent the optimizer from finding the best possible join plan.

If you change this value, set the JOIN_SIMPLIFICATION_THRESHOLD as a temporary or user option, and to a
value of at least 9.

Related Information

MAX_JOIN_ENUMERATION Option [page 1912]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.114 LF_BITMAP_CACHE_KB Option

Specifies the amount of memory to use for a load into a LF index.

Allowed Values

1 to 8

Default

SAP IQ SQL Reference


1894 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

LF_BITMAP_CACHE_KB defines the amount of heap memory (in KB) per distinct value used during a load into
an LF index. The default allots 4KB. If the sum of the distinct counts for all LF indexes on a particular table is
relatively high (greater than 10,000), then heap memory use might increase to the point of impacting load
performance due to system page faulting. If this is the case, reduce the value of LF_BITMAP_CACHE_KB.

This formula shows how to calculate the heap memory used (in bytes) by a particular LF index during a load:

Heap-memory-used = (lf_bitmap_cache_kb * 1024)


* lf-distinct-count-for-column

Using the default of 4 KB, an LF index with 1000 distinct values can use up to 4 MB of heap memory during a
load.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.115 LOAD_ZEROLENGTH_ASNULL Option

Specifies LOAD statement behavior under certain conditions.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 1895
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option specifies LOAD statement behavior under these conditions:

● Inserting a zero-length data value into a column of data type CHAR, VARCHAR, LONG VARCHAR, BINARY,
VARBINARY, or LONG BINARY, and
● A NULL column-spec; for example, NULL(ZEROS) or NULL(BLANKS) is also given for that same column.

Set LOAD_ZEROLENGTH_ASNULL ON to load a zero-length value as NULL when the above conditions are met.

Set LOAD_ZEROLENGTH_ASNULL OFF to load a zero-length value as zero-length, subject to the setting of option
NON_ANSI_NULL_VARCHAR.

Related Information

NON_ANSI_NULL_VARCHAR Option [page 1940]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1896 INTERNAL Database Options
10.6.116 LOG_CONNECT Option

Controls logging of user connections.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SECURITY OPTION system privilege to set this option. Takes effect immediately.

Remarks

When this option is ON, a message appears in the IQ message log (.iqmsg file) every time a user connects to
or disconnects from the SAP IQ database.

 Note

If this option is set OFF (connection logging disabled) when a user connects, and then turned on before the
user disconnects, the message log shows that user disconnecting but not connecting.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1897
10.6.117 LOG_CURSOR_OPERATIONS Option

Controls logging of cursor operations.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When this option is ON, a message appears in the IQ message log every time you open or close a cursor.
Normally this option should be OFF, which is the default. Turn it ON only if you are having a problem and must
provide debugging data to Technical Support.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1898 INTERNAL Database Options
10.6.118 LOG_DEADLOCKS Option

Controls whether deadlock reporting is turned on or off.

Allowed values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When this option is set to On, the database server logs information about deadlocks in an internal buffer. The
size of the buffer is fixed at 10000 bytes. You can view the deadlock information using the sa_report_deadlocks
stored procedure. The contents of the buffer are retained when this option is set to Off.

When deadlock occurs, information is reported for only those connections involved in the deadlock. The order
in which connections are reported is based on which connection is waiting for which row. For thread deadlocks,
information is reported about all connections.

When you have deadlock reporting turned on, you can also use the Deadlock system event to take action when
a deadlock occurs.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1899
10.6.119 LOGIN_MODE Option

Controls the use of standard, integrated, Kerberos, LDAP, and PAM logins for the database.

Allowed Values

● Standard – the default setting, which does not permit integrated logins. An error occurs if an integrated
login connection is attempted.
● Mixed – allows both integrated logins and standard logins.
● Integrated – all logins to the database must be made using integrated logins.
● Kerberos – all logins to the database must be made using Kerberos logins.
● LDAPUA – all logins to the database must be made using LDAP logins.
● PAMUA – all logins to the database must be made using PAM logins.

 Note

Mixed is equivalent to "Standard,Integrated".

Default

Standard

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SECURITY OPTION system privilege to set this option. Takes effect immediately.

Remarks

Values are case-insensitive. Specify values in a comma-separated list without white space.

 Caution

● Restricting the LOGIN_MODE to a single mode in a mixed environment (for example, integrated only or
LDAPUA only) restricts connections to only those users who have been granted the corresponding
login mapping. Attempting to connect using other methods generates an error. The only exceptions to
this are users with full administrative rights (SYS_AUTH_DBA_ROLE or SYS_AUTH_SSO_ROLE).
● Restricting the LOGIN_MODE to LDAPUA only may result in a configuration where no users can connect
to the server if no user or login policy exists that permits LDAPUA. Use the command line switch -al
<user-id-list> with the start_iq utility to recover from this situation.

SAP IQ SQL Reference


1900 INTERNAL Database Options
● If a database file is not secured and can be copied by unauthorized users, set the LOGIN_MODE as a
TEMPORARY public option for integrated, Kerberos, or PAM user authentication. This ensures that, by
default, integrated, Kerberos, and PAM logins are not supported if the file is copied.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.120 LOGIN_PROCEDURE Option

Specifies a login procedure that sets connection compatibility options at start-up.

Allowed Values

String

Default

sp_login_environment system procedure

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SECURITY OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1901
Remarks

The initial connection compatibility options settings are controlled using the LOGIN_PROCEDURE option, which
is called after all the checks have been performed to verify that the connection is valid. The LOGIN_PROCEDURE
option names a stored procedure to run when users connect. The default setting is to use the
sp_login_environment system stored procedure. You can specify a different stored procedure. The
procedure specified by the LOGIN_PROCEDURE option is not executed for event connections.

The sp_login_environment procedure checks to see if the connection is being made over TDS. If the
connection is made over TDS, sp_login_environment calls the sp_tsql_environment procedure, which
sets several options to new default values for the current connection.

Related Information

Initial Option Settings [page 1726]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.121 MAIN_RESERVED_DBSPACE_MB Option

Controls the amount of space SAP IQ reserves in the IQ main store.

Allowed Values

Integer greater than or equal to 200, in megabytes

Default

200; SAP IQ actually reserves a maximum of 50 percent and a minimum of 1 percent of the last read-write file
in IQ_SYSTEM_MAIN

Scope

● Option can be set at the database (PUBLIC) level only.

SAP IQ SQL Reference


1902 INTERNAL Database Options
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

MAIN_RESERVED_DBSPACE_MB controls the amount of space SAP IQ sets aside in the IQ main store for certain
small but critical data structures used during release savepoint, commit, and checkpoint operations. For a
production database, set this value between 200 MB and 1 GB, or at least 20 percent of IQ_SYSTEM_MAIN size.
The larger your IQ page size and number of concurrent connections, the more reserved space you need.

Reserved space size is calculated as a maximum of 50 percent and a minimum of 1 percent of the last read-
write file in IQ_SYSTEM_MAIN.

SAP IQ ignores the MAIN_RESERVED_DBSPACE_MB option if the actual dbspace size is less than twice the size
of the MAIN_RESERVED_DBSPACE_MB value. In dbspaces less than 100 MB (such as the demo database), half
the usable space may be reserved.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.122 MAX_CARTESIAN_RESULT Option

Limits the number of rows resulting from a Cartesian join.

Allowed Values

Integer

Default

100,000,000

SAP IQ SQL Reference


Database Options INTERNAL 1903
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

MAX_CARTESIAN_RESULT limits the number of result rows from a query containing a Cartesian join (usually
the result of missing one or more join conditions when creating the query). If SAP IQ cannot find a query plan
for the Cartesian join with an estimated result under this limit, it rejects the query and returns an error. Setting
MAX_CARTESIAN_RESULT to 0 disables the check for the number of result rows of a Cartesian join.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.123 MAX_CLIENT_NUMERIC_PRECISION Option

Controls the maximum precision for numeric data sent to the client.

Allowed Values

0 to 126

Default

SAP IQ SQL Reference


1904 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When SAP IQ performs its calculation, it promotes data types to an appropriate size that ensures accuracy. The
promoted data type might be larger in size than Open Client and some ODBC applications can handle correctly.

When MAX_CLIENT_NUMERIC_PRECISION is a nonzero value, SAP IQ checks that numeric result columns do
not exceed this value. If the result column is bigger than MAX_CUBE_RESULT allows, and SAP IQ cannot cast it
to the specified precision, the query returns this error:
Data Exception - data type conversion is not possible %1
SQLCODE = -1001006

 Note

In SAP SQL Anywhere, the maximum value supported for the numeric function is 255. If the precision of
the numeric function exceeds the maximum value supported, you see the error:
The result datatype for function '_funcname' exceeds the maximum
supported numeric precision of 255. Please set the proper value for precision
in numeric function, 'location'

Related Information

MAX_CLIENT_NUMERIC_SCALE Option [page 1906]


PRECISION Option [page 1949]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1905
10.6.124 MAX_CLIENT_NUMERIC_SCALE Option

Controls the maximum scale for numeric data sent to the client.

Allowed Values

0 to 126

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When SAP IQ performs its calculation, it promotes data types to an appropriate scale and size that ensure
accuracy. The promoted data type might be larger than the original defined data size. You can set this option to
the scale you want for numeric results.

Multiplication, division, addition, subtraction, and aggregate functions can all have results that exceed the
maximum precision and scale.

For example, when a DECIMAL(88,2) is multiplied with a DECIMAL(59,2), the result could require a
DECIMAL(147,4). With MAX_CLIENT_NUMERIC_PRECISION of 126, only 126 digits are kept in the result. If
MAX_CLIENT_NUMERIC_SCALE is 4, the results are returned as a DECIMAL(126,4). If
MAX_CLIENT_NUMERIC_SCALE is 2, the results are returned as a DECIMAL(126,2). In both cases, there is a
possibility for overflow.

SAP IQ SQL Reference


1906 INTERNAL Database Options
Related Information

MAX_CLIENT_NUMERIC_PRECISION Option [page 1904]


SCALE Option [page 2008]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.125 MAX_CUBE_RESULT Option

Sets the maximum number of rows that the IQ optimizer considers for a GROUP BY CUBE operation.

Allowed Values

0 to 4,294,967,295

Default

10,000,000

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When generating a query plan, the IQ optimizer estimates the total number of groups generated by the GROUP
BY CUBE hash operation. The IQ optimizer uses a hash algorithm for the GROUP BY CUBE operation. This
option sets an upper boundary for the number of estimated rows the optimizer considers for a hash algorithm
that can be run. If the actual number of rows exceeds the MAX_CUBE_RESULT value, the optimizer stops

SAP IQ SQL Reference


Database Options INTERNAL 1907
processing the query and returns the error Estimate number: <nnn> exceeds the default
MAX_CUBE_RESULT of GROUP BY CUBE or ROLLUP, where <nnn> is the number estimated by the IQ
optimizer.

Set MAX_CUBE_RESULT to zero to override the default value. When this option is set to zero, the IQ optimizer
does not check the row limit and allows the query to run. Setting MAX_CUBE_RESULT to zero is not
recommended, as the query might not succeed.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.126 MAX_CURSOR_COUNT Option

Specifies a resource governor to limit the maximum number of cursors that a connection can use at once.

Allowed Values

Integer

Default

50

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1908 INTERNAL Database Options
Remarks

The specified resource governor allows a DBA to limit the number of cursors per connection that a user can
have. If an operation exceeds the limit for a connection, an error is generated indicating that the limit has been
exceeded.

If a connection executes a stored procedure, the procedure is executed under the permissions of the procedure
owner. However, the resources used by the procedure are assigned to the current connection.

You can remove resource limits by setting MAX_CURSOR_COUNT to 0 (zero).

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.127 MAX_HASH_ROWS Option

Sets the maximum number of rows that the IQ optimizer considers for a hash algorithm.

Allowed Values

Integer from 1 to 4,294,967,295

Default

2,500,000

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1909
Remarks

When generating a query plan, the IQ optimizer might have several algorithms (hash, sort, indexed) to choose
from when processing a particular part of a query. These choices often depend on estimates of the number of
rows to process or generate from that part of the query. This option sets an upper boundary for how many
estimated rows are considered for a hash algorithm.

For example, if there is a join between two tables, and the estimated number of rows entering the join from both
tables exceeds the value of MAX_HASH_ROWS, the optimizer does not consider a hash join. On systems with
more than 50 MB per user of temporary buffer cache space, you might want to consider a higher value for this
option.

Use MAX_HASH_ROWS only as needed for joins; it may negatively affect parallelism. MAX_HASH_ROWS does not
apply to GROUP BY.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.128 MAX_IQ_THREADS_PER_CONNECTION Option

Controls the number of threads for each connection.

Allowed Values

3 to 10000

Default

144

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


1910 INTERNAL Database Options
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Description

Allows you to constrain the number of threads (and thereby the amount of system resources) the commands
executed on a connection use. For most applications, use the default.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.129 MAX_IQ_THREADS_PER_TEAM Option

Controls the number of threads allocated to perform a single operation (such as a LIKE predicate on a column)
executing within a connection.

Allowed Values

1 to 10000

Default

144

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


Database Options INTERNAL 1911
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Allows you to constrain the number of threads (and thereby the amount of system resources) allocated to a
single operation. The total for all simultaneously executing teams for this connection is limited by the related
option, MAX_IQ_THREADS_PER_CONNECTION. For most applications, use the default.

Related Information

MAX_IQ_THREADS_PER_CONNECTION Option [page 1910]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.130 MAX_JOIN_ENUMERATION Option

Controls the maximum number of tables to be optimized for join order after optimizer simplifications have
been applied.

Allowed Values

1 to 32

Default

15

SAP IQ SQL Reference


1912 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Each FROM clause is limited to having at most 64 tables. In practice, however, the effective limit on the number
of tables in a FROM clause is usually much lower, and is based partially on the complexity of the join
relationships among those tables. That effective limit is constrained by the setting for
MAX_JOIN_ENUMERATION. The optimizer will attempt to simplify the set of join relationships within a FROM
clause. If those simplifications fail to reduce the set of the joins that must be simultaneously considered to no
more than the current setting for MAX_JOIN_ENUMERATION, then the query will return an error.

 Caution

Setting MAX_JOIN_ENUMERATION over the default value of 15 should only be done with caution, especially
in the case of queries with bushy join relationships that can cause the amount of time required by the
optimizer increase dramatically. In queries that use only a linear chain of join relationships, a
MAX_JOIN_ENUMERATION setting of 32 can still provide reasonable optimization times.

The query optimizer simplifies its optimization of join order by separate handling of both lookup tables (that is,
nonselective dimension tables) and tables that are effective Cartesian products. After simplification, it
proceeds with optimizing the remaining tables for join order, up to the limit set by MAX_JOIN_ENUMERATION.
If this limit is exceeded, the query is rejected with an error. The user can then either simplify the query or try
increasing the limit.

Normally, you should not need to change this value. If you do, set MAX_JOIN_ENUMERATION as a temporary
or user option.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1913
10.6.131 MAX_PARTITIONED_HASH_MB Option

Sets an upper bound, expressed in megabytes, on the amount of temporary cache space that the optimizer
can assume will be available for hash-partitioned hash-based query operators.

Allowed Values

Integer from 0 to 4,294,967,295

Default

Scope

Can be set temporary for an individual connection, for a user, or for the PUBLIC group. No system privilege
required to set this option. This option takes effect immediately.

Description

When generating a query plan, the IQ optimizer might choose from several algorithms when processing a
particular part of a query. These decisions often depend on estimates of the temp cache space that will be
required to process that part of the query and on the currently available temp cache. This option sets an upper
bound on estimated temporary space usage for operators that can consider a hash-partitioned hash-based
algorithm.

The default value of 0 indicates that there is no hard upper bound, and that therefore optimizer’s choice will be
limited only by the current temp cache availability, the current number of active user connections, and the
HASH_PINNABLE_PERCENT option setting.

Note that this option affects only the optimizer’s algorithm selection decisions, and that the run-time usage
may under some circumstances occasionally exceed this limit.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1914 INTERNAL Database Options
GRANT System Privilege Statement [page 1511]

10.6.132 MAX_PREFIX_PER_CONTAINS_PHRASE Option

Specifies the number of prefix terms allowed in a text search expression.

Allowed Values

0 to 300

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Users must be licensed for the Unstructured Data Analytics Option to use TEXT indexes and perform full text
searches.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1915
10.6.133 MAX_QUERY_PARALLELISM Option

Sets upper bound for parallel execution of GROUP BY operations and for arms of a UNION.

Allowed Values

Integer less than, greater than or equal to number of CPUs.

Default

64

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This parameter sets an upper bound which limits how parallel the optimizer will permit query operators to go.
This can influence the CPU usage for many query join, GROUP BY, UNION, ORDER BY, and other query
operators.

Systems with more than 64 CPU cores often benefit from a larger value, up to the total number of CPU cores on
the system to a maximum of 512; you can experiment to find the best value for this parameter for your system
and queries.

Systems with 64 or fewer CPU cores should not need to reduce this value, unless excessive system time is
seen. In that case, you can try reducing this value to determine if that adjustment can lower the CPU system
time and improve query response times and overall system throughput.

Related Information

Set a Database Option [page 1727]

SAP IQ SQL Reference


1916 INTERNAL Database Options
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.134 MAX_QUERY_TIME Option

Sets a time limit so that the optimizer can disallow very long queries.

Allowed Values

0 to 232 – 1 (minutes)

Default

0 (disabled)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If the query runs longer than the MAX_QUERY_TIME setting, SAP IQ stops the query and sends a message to
the user and the IQ message file. For example:

The operation has been canceled -- Max_Query_Time exceeded.

MAX_QUERY_TIME applies only to queries and not to any SQL statement that is modifying the contents of the
database.

SAP IQ SQL Reference


Database Options INTERNAL 1917
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.135 MAX_RV_REMOTE_TRANSFER_MB Option

Limit the volume of RLV-enabled table data allowed to be transferred from the RLV store when a statement is
executed on another node.

Allowed Values

Any non-negative integer (in megabytes)

Default

1000

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege. Can be set temporary for an individual
connection or for the PUBLIC role. Takes effect immediately.

Remarks

In a Multiplex, all access to RLV-enabled tables is performed on the RLV store node. Queries running on other
nodes need to forward the fragment of the query involving RLV-enabled tables to the RLV store node to retrieve
data. The MAX_RV_REMOTE_TRANSFER_MB option is the mechanism to accomplish this task. When a query
plan estimate of the total volume of data to be transferred for all RLV-enabled tables within the query exceeds
the limit set by this option, the query is rejected with an error before execution begins.

SAP IQ SQL Reference


1918 INTERNAL Database Options
Set the Max_RV_Remote_Transfer_MB option to 0 to disable this RLV data transfer volume check. Queries
exceeding this limit should be executed directly on the RLV store node.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.136 MAX_STATEMENT_COUNT Option

Specifies a resource governor to limit the maximum number of prepared statements that a connection can use
at once.

Allowed Values

Integer

Default

100

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1919
Remarks

The specified resource governor allows a DBA to limit the number of prepared statements per connection that
a user can have. If an operation exceeds the limit for a connection, an error is generated indicating that the limit
has been exceeded.

If a connection executes a stored procedure, the procedure is executed under the permissions of the procedure
owner. However, the resources used by the procedure are assigned to the current connection.

You can remove resource limits by setting MAX_STATEMENT_COUNT to 0 (zero).

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.137 MAX_TEMP_SPACE_PER_CONNECTION Option

Limits temporary store space used per connection.

Allowed Values

Integer (number of MB)

Default

0 (no limit on temporary store usage)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1920 INTERNAL Database Options
Remarks

By controlling space per connection, this option enables DBAs to manage the space for both loads and queries.
If the connection exceeds the run time quota specified by MAX_TEMP_SPACE_PER_CONNECTION, SAP IQ rolls
back the current statement and returns this message to the IQ message file or client user:
The current operation has been canceled: Max_Temp_Space_Per_Connection exceeded

Conditions that may fill the buffer cache include read or write errors, lack of main or temp space, or being out
of memory. SAP IQ may return the first error encountered in these situations and the DBA must determine the
appropriate solution.

In a distributed query processing transaction, SAP IQ uses the values set for the QUERY_TEMP_SPACE_LIMIT
and MAX_TEMP_SPACE_PER_CONNECTION options for the shared temporary store by limiting the total shared
and local temporary space used by all nodes participating in the distributed query. This means that any single
query cannot exceed the total temporary space limit (from IQ_SYSTEM_TEMP and IQ_SHARED_TEMP
dbspaces), no matter how many nodes participate.

For example, if the limit is 100 and four nodes use 25 units of temporary space each, the query is within limits.
If the sum of the total space used by any of the nodes exceeds 100, however, the query rolls back.

Examples

Example 1
Set a 500 GB limit for all connections:

SET OPTION
PUBLIC.MAX_TEMP_SPACE_PER_CONNECTION = 512000

Example 2
Set a 10 TB limit for all connections:

SET OPTION
PUBLIC.MAX_TEMP_SPACE_PER_CONNECTION = 10485760

Example 3
Set a 5000 MB limit for user wilson:

SET OPTION
wilson.MAX_TEMP_SPACE_PER_CONNECTION = 5000

Related Information

QUERY_TEMP_SPACE_LIMIT Option [page 1975]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


Database Options INTERNAL 1921
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.138 MIN_NUMERIC_DIVISION_SCALE Option

Controls the number of decimal places displayed for division operations on constant numeric values.

Allowed Values

0 to 125

Default

Scope

Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

By default, queries on IQ main store tables use a six digit scale for division operations on constant numbers.
Since IQ catalog store uses the same scale, there is minimal impact when comparing the values between
stores, particularly when results are passed to numeric functions like POWER(), EXP(), etc.

10.6.139 min_password_length option

Sets the minimum length for new passwords in the database.

Allowed values

Integer

SAP IQ SQL Reference


1922 INTERNAL Database Options
The value is in bytes. For single-byte character sets, this value is the same as the number of characters.

Default

Scope

PUBLIC role For current user For other users

Allowed to set permanently? Yes, with SET ANY SECURITY No No


OPTION

Allowed to set temporarily? Yes, with SET ANY SECURITY No No


OPTION

Remarks

This option allows the database administrator to impose a minimum length on all new passwords for greater
security. Existing passwords are not affected. Passwords have a maximum length of 255 bytes and are case
sensitive.

 Example

Set the minimum length for new passwords to 6 bytes.

SET OPTION PUBLIC.min_password_length = 6;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1923
10.6.140 MIN_ROLE_ADMINS Option

Configures of the minimum number of required administrators for all roles.

Allowed Values

1 to 10

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SECURITY OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option sets the minimum number of required administrators for all roles. This value applies to the
minimum number of role administrators for each role, not the minimum number or role administrators for the
total number of roles. When dropping roles or users, this value ensures that you never create a scenario where
there are no users and roles left with sufficient system privilege to manage the remaining users and roles.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1924 INTERNAL Database Options
10.6.141 MINIMIZE_STORAGE Option

Minimizes use of disk space for newly created columns in SAP IQ 15 databases.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Dependencies

MINIMIZE_STORAGE applies to databases running with FP_NBIT_IQ15_COMPATIBILITY is set to ON. If it is


set to OFF, the database engine ignores this option.

Remarks

If FP_NBIT_IQ15_COMPATIBILITY is ON, MINIMIZE_STORAGE optimizes storage for new columns by using


as little as one byte of disk space per row wherever appropriate. By default, this option is OFF for the PUBLIC
role, and the specialized storage optimization does not occur for all newly created columns; when
MINIMIZE_STORAGE is OFF for the PUBLIC role but ON as a temporary user option, one-byte storage is used
for new columns created by that user ID.

In SAP IQ 15.x databases, setting MINIMIZE_STORAGE is ON is equivalent to placing an IQ UNIQUE 255


clause on every new column, with the exception of certain data types that are by nature too wide for one-byte

SAP IQ SQL Reference


Database Options INTERNAL 1925
storage. When MINIMIZE_STORAGE is ON, there is no need to specify IQ UNIQUE, except for columns with
more than 65536 unique values.

When the ratio of main memory to the number of columns is large, turning MINIMIZE_STORAGE to ON is
beneficial. Otherwise, storage of new columns generally benefits by turning this option OFF.

 Note

Avoid running a database when FP_NBIT_IQ15_COMPATIBILITY is set to ON. All SAP IQ 15 runtime
behavior is available with the SAP IQ 16.1 interface.

Related Information

FP_LOOKUP_SIZE Option [page 1843]


INDEX_ADVISOR Option [page 1870]
FP_LOOKUP_SIZE_PPM Option [page 1844]
FP_NBIT_IQ15_COMPATIBILITY Option [page 1849]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.142 MONITOR_OUTPUT_DIRECTORY Option

Controls placement of output files for the IQ buffer cache monitor.

Allowed Values

String

Default

Same directory as the database.

SAP IQ SQL Reference


1926 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

MONITOR_OUTPUT_DIRECTORY controls the directory in which the IQ monitor output files are created,
regardless of what is being monitored or what monitor mode is used. The dummy table used to start the
monitor can be either a temporary or a permanent table. The directory can be on any physical machine.

All monitor output files are used for the duration of the monitor runs, which cannot exceed the lifetime of the
connection. The output file still exists after the monitor run stops. A connection can run up to two performance
monitors simultaneously, one for main buffer cache and one for temp buffer cache. A connection can run a
monitor any number of times, successively.

The DBA can use the PUBLIC setting to place all monitor output in the same directory, or set different
directories for individual users.

Example

This example shows how you could declare a temporary table for monitor output, set its location, and then
have the monitor start sending files to that location for the main and temp buffer caches.

In this example, the output directory string is set to both “/tmp” and “tmp/”. The trailing slash (“/”) is correct
and is supported by the interface. The example illustrates that the buffer cache monitor does not require a
permanent table; a temporary table can be used.

declare local temporary table dummy_monitor (dummy_column integer)

set option Monitor_Output_Directory = "/tmp"


iq utilities main into dummy_monitor start monitor '-debug -interval 2'

set option Monitor_Output_Directory = "tmp/"

iq utilities private into dummy_monitor start monitor '-debug -interval 2'

Related Information

Set a Database Option [page 1727]

SAP IQ SQL Reference


Database Options INTERNAL 1927
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.143 MPX_AUTOEXCLUDE_TIMEOUT Option

Timeout for autoexcluding a secondary node on the coordinator node. This option does not apply to the
designated failover node.

Allowed Values

0 to 10080 (1 week), in minutes.

Default

60 (minutes)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Setting takes effect
immediately and persists across server restarts.

Remarks

0 indicates that the nodes are not autoexcluded. Values must be exactly divisible by the
MPX_HEARTBEAT_FREQUENCY setting in minutes. For example, if the MPX_HEARTBEAT_FREQUENCY setting is
120 (2 minutes), MPX_AUTOEXCLUDE_TIMEOUT must be divisible by 2.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1928 INTERNAL Database Options
GRANT System Privilege Statement [page 1511]

10.6.144 MPX_DAS_COMMUNICATION_ENABLED Option

Controls the state of initialization of the network interface during SAP IQ server startup. This option is set on a
MPX-coordinator or Simplex node.

Allowed Values

OFF

Default

OFF

 Note

SAP IQ returns an error if this option is set to ON.

Scope

● To set this option, you require DBA permissions. It can be set only for the PUBLIC group.
● Once set, the option takes effect after a server reboot (secondary servers need to be synced and restarted
as well).

Remarks

Support for Shared-Nothing multiplex has been removed in this release. For details, see Shared-Nothing
Multiplex (Removed).

SAP IQ SQL Reference


Database Options INTERNAL 1929
10.6.145 MPX_GTR_ENABLED Option

Enables global transaction resiliency functionality on the coordinator. Global transaction resiliency allows DML
read-write transactions on writers to survive temporary communication failures between coordinator and
writer and temporary failure of coordinator due to server failure, shutdown, or failover.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires DBA permissions. Takes effect after restart.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1930 INTERNAL Database Options
10.6.146 MPX_HEARTBEAT_FREQUENCY Option

Interval until the heartbeat thread wakes and performs periodic operations, such as checking for coordinator
connectivity and cleaning up the connection pool on the secondary node. The heartbeat thread maintains a
dedicated internal connection from secondary server to coordinator.

Allowed Values

2 to 3600 (seconds)

Default

60 (seconds)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must restart the server for
the change to take effect.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.147 MPX_IDLE_CONNECTION_TIMEOUT Option

Time after which an unused connection in the connection pool on a secondary node will be closed.

Allowed Values

0 – no limit (seconds)

SAP IQ SQL Reference


Database Options INTERNAL 1931
Default

600 (seconds)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Setting takes effect
immediately and persists across server restarts.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.148 MPX_LIVENESS_TIMEOUT Option

Time, in seconds, before a heartbeat on a secondary server declares the coordinator offline if the heartbeat
fails to reconnect to the coordinator after the first disconnect. This option also determines how long the
coordinator keeps a global transaction in a suspended state.

Allowed Values

0 to 604,800 (1 week), in seconds

Default

3600 seconds (1 hour)

SAP IQ SQL Reference


1932 INTERNAL Database Options
Scope

● This option affects all multiplex nodes and has no node-specific or connection-specific value. Option can
be set at the database (PUBLIC) level only.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. If you change the value of
MPX_LIVENESS_TIMEOUT on a running server, the new value takes effect immediately for connections that
might suspend in the future. The changed value also immediately affects the remaining timeout period for
all current suspended transactions.

Remarks

If a writer fails to resume a suspended transaction within the MPX_LIVENESS_TIMEOUT period, the transaction
can no longer commit, and the user should roll back the transaction. The coordinator keeps a global
transaction in a suspended state for a period of 2 * MPX_LIVENESS_TIMEOUT. If the corresponding writer fails
to resume the transaction before the 2 * MPX_LIVENESS_TIMEOUT period, the coordinator rolls back the
suspended transaction.

Always specify an MPX_LIVENESS_TIMEOUT value that is a multiple of the current


MPX_HEARTBEAT_FREQUENCY value, which controls the aliveness check period. The coordinator internally
doubles the value of MPX_LIVENESS_TIMEOUT.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.149 MPX_MAX_CONNECTION_POOL_SIZE Option

Maximum number of connections allowed in the connection pool on a secondary node.

Allowed Values

1 to 1000

SAP IQ SQL Reference


Database Options INTERNAL 1933
Default

10

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Setting takes effect
immediately and persists across server restarts.

Remarks

INC connections are inter-server connections between secondary nodes and the coordinator node. An INC
connection is associated with each user connection on a secondary server doing a DDL or read-write
operation. The connection is active until that command commits or rolls back; it then returns to the pool. If
these transactions are short lived, then the default setting of MPX_MAX_CONNECTION_POOL_SIZE suffices for
many user connections running DDL or RW operations. If many concurrent connections run DDL or read-write
operations, or the transactions take a long time, increase the value of MPX_MAX_CONNECTION_POOL_SIZE. For
example, increase the value when many user connections do concurrent loads without committing.

Exceeding MPX_MAX_CONNECTION_POOL_SIZE returns the following message:


SQL Anywhere Error -1004000: The number of connections in
the connection pool have exceeded the upper limit
.

To estimate the pool size required, consider the setting of the -gm server option. The -gm setting indicates how
many users can connect to the secondary server; the INC connections are not included, but will add to this
number. Use application requirements to assess how many read-write or DDL operations are likely to occur per
user, and increase the pool size accordingly.

Each connection (INC or user) carries a memory overhead depending on -gn setting and number of cores. The
burden of memory and thread contention may affect SAP IQ server response times.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1934 INTERNAL Database Options
10.6.150 MPX_MAX_UNUSED_POOL_SIZE Option

Maximum number of unused connections in the connection pool on a secondary node.

Allowed Values

0 to maximum pool size

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Setting takes effect
immediately and persists across server restarts.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.151 MPX_MIPC_TIMEOUT Option

Specifies the timeout, in seconds, for MIPC (multiplex interprocess communication) calls.

Allowed Values

0 to 4,294,967,296 (seconds)

SAP IQ SQL Reference


Database Options INTERNAL 1935
Default

180 (seconds)

Scope

Option can be set at the database (PUBLIC) level only. Requires the SET ANY PUBLIC OPTION privilege to set
this option. Takes effect immediately.

Remarks

During a multiplex query, a node sends an MIPC request to another node and waits for results. The
MPX_MIPC_TIMEOUT prevents indefinite waiting in the event of a network failure or target node deadlock.
MIPC requests that exceed the timeout threshold will cancel the query with an error.

Do not adjust MPX_MIPC_TIMEOUT unless advised by troubleshooting documentation, or instructed by


Technical Support.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.152 MPX_WORK_UNIT_TIMEOUT Option

Time, in seconds, before a multiplex DQP leader reassigns incomplete distributed work to another DQP worker
node.

Allowed Values

0 to 4,294,967,296 (seconds)

SAP IQ SQL Reference


1936 INTERNAL Database Options
Default

600 (seconds)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Pending DQP work units are monitored by the leader node to prevent indefinite waiting in the event of a node
failure or network failure. In many cases, queries will silently reassign work units that exceed the timeout value
to the leader. However, some plans do not support this reassignment and will cancel the query with an error.

Typically you do not need to change this option from its default value. However, increase this option in rare
cases where a query has very large intermediate results that cause individual work units to time out.

Decrease this option if unreliable networks or servers cause distributed work to be lost and the timeout interval
is unacceptably long. Note that setting this option too low can cause unnecessary early timeouts.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1937
10.6.153 NEAREST_CENTURY Option [TSQL]

Controls the interpretation of two-digit years, in string-to-date conversions.

Allowed Values

0 to 100

Default

50

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

NEAREST_CENTURY controls the handling of two-digit years, when converting from strings to dates or
timestamps.

The NEAREST_CENTURY setting is a numeric value that acts as a rollover point. Two-digit years less than the
value are converted to 20<yy>, whereas years greater than or equal to the value are converted to 19<yy>.

SAP Adaptive Server Enterprise and SAP IQ behavior is to use the nearest century, so that if the year value
<yy> is less than 50, then the year is set to 20<yy>.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


1938 INTERNAL Database Options
GRANT System Privilege Statement [page 1511]

10.6.154 NOEXEC Option

Generates the optimizer query plans instead of executing the plan.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When determining how to process a query, the IQ optimizer generates a query plan to map how it plans to have
the query engine process the query. If this option is set ON, the optimizer sends the plan for the query to the IQ
message file rather than submitting it to the query engine. NOEXEC affects queries and commands that include
a query.

Setting NOEXEC ON also prevents the execution of INSERT...VALUES, INSERT...SELECT,


INSERT...LOCATION, SELECT...INTO, LOAD TABLE, UPDATE, TRUNCATE TABLE, DELETE, and updatable
cursor operations.

When the EARLY_PREDICATE_EXECUTION option is ON, SAP IQ executes the local predicates for all queries
before generating a query plan, even when the NOEXEC option is ON. The generated query plan is the same as
the runtime plan.

SAP IQ SQL Reference


Database Options INTERNAL 1939
Related Information

EARLY_PREDICATE_EXECUTION Option [page 1833]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.155 NON_ANSI_NULL_VARCHAR Option

Controls whether zero-length VARCHAR data is treated as NULLs for insert, load, and update operations.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

NON_ANSI_NULL_VARCHAR lets you revert to non-ANSI (Version 12.03.1) behavior for treating zero-length
VARCHAR data during load or update operations. When this option is set to OFF, zero-length VARCHAR data is
stored as zero-length during load, insert, or update. When this option is set to ON, zero-length VARCHAR data is
stored as NULLs on load, insert, or update.

SAP IQ SQL Reference


1940 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.156 NON_KEYWORDS Option [TSQL]

Turns off individual keywords, allowing their use as identifiers.

Allowed Values

String

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

NON_KEYWORDS turns off individual keywords. If you have an identifier in your database that is now a keyword,
you can either add double quotes around the identifier in all applications or scripts, or you can turn off the
keyword using the NON_KEYWORDS option.

This statement prevents TRUNCATE and SYNCHRONIZE from being recognized as keywords:

SET OPTION NON_KEYWORDS = 'TRUNCATE, SYNCHRONIZE'

SAP IQ SQL Reference


Database Options INTERNAL 1941
Each new setting of this option replaces the previous setting. This statement clears all previous settings:

SET OPTION NON_KEYWORDS =

A side effect of the options is that SQL statements using a turned-off keyword cannot be used; they produce a
syntax error.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.157 NOTIFY_MODULUS Option

Controls the default frequency of notify messages issued by certain commands.

Allowed Values

Any integer

Default

● 0 – for new SAP IQ 16.0 or later databases.


● 100000 – for pre-16.0 upgraded databases.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1942 INTERNAL Database Options
Remarks

This option sets the default number of notify messages SAP IQ issued for certain commands that produce
them. The NOTIFY clause for some of the commands (such as CREATE INDEX, LOAD TABLE, and DELETE)
override this value. Other commands that do not support the NOTIFY clause always use this value. The default
does not restrict the number of messages you can receive.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.158 ODBC_DISTINGUISH_CHAR_AND_VARCHAR Option

Controls how the SAP IQ ODBC driver describes CHAR columns.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1943
Remarks

When a connection is opened, the SAP IQ ODBC driver uses the setting of this option to determine how CHAR
columns are described. If ODBC_DISTINGUISH_CHAR_AND_VARCHAR is set to OFF (the default), then CHAR
columns are described as SQL_VARCHAR. If this option is set to ON, then CHAR columns are described as
SQL_CHAR. VARCHAR columns are always described as SQL_VARCHAR.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.159 ON_CHARSET_CONVERSION_FAILURE Option

Controls the action taken, if an error is encountered during character conversion.

Allowed Values

● IGNORE – errors and warnings do not appear.


● WARNING – substitutions and illegal characters are reported as warnings. Illegal characters are not
translated.
● ERROR – substitutions and illegal characters are reported as errors.

Default

IGNORE

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1944 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

ON_CHARSET_CONVERSION_FAILURE controls the action taken, if an error is encountered during character


conversion.

Single-byte to single-byte converters are not able to report substitutions and illegal characters, and must be
set to IGNORE.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.160 ON_ERROR Option [Interactive SQL]

Controls the action taken if an error is encountered while executing statements in Interactive SQL.

Allowed Values

● STOP – Interactive SQL stops executing statements from the file and returns to the statement window for
input.
● PROMPT – Interactive SQL prompts the user whether to continue.
● CONTINUE – errors appear in the Messages pane, and Interactive SQL continues executing statements.
● EXIT – Interactive SQL terminates.
● NOTIFY_CONTINUE – the error is reported, and the user is prompted to continue.
● NOTIFY_STOP – the error is reported, and the user is prompted to stop executing statements.
● NOTIFY_EXIT – the error is reported, and the user is prompted to terminate Interactive SQL.

Default

PROMPT

SAP IQ SQL Reference


Database Options INTERNAL 1945
Remarks

Controls the action taken, if an error is encountered while executing statements. When you are executing
a .SQL file, the values STOP and EXIT are equivalent.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.161 ON_TSQL_ERROR Option [TSQL]

Controls error handling in stored procedures.

Allowed Values

● STOP – stops execution immediately upon finding an error.


● CONDITIONAL – if the procedure uses ON EXCEPTION RESUME, and the statement following the error
handles the error, continue; otherwise, exit.
● CONTINUE – continue execution, regardless of the following statement. If there are multiple errors, the
first error encountered in the stored procedure is returned. This option most closely mirrors SAP Adaptive
Server Enterprise behavior.

Default

CONDITIONAL

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


1946 INTERNAL Database Options
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

ON_TSQL_ERROR controls error handling in stored procedures.

Both CONDITIONAL and CONTINUE settings for ON_TSQL_ERROR are used for SAP ASE compatibility, with
CONTINUE most closely simulating SAP ASE behavior. The CONDITIONAL setting is recommended,
particularly when developing new Transact-SQL stored procedures, as CONDITIONAL allows errors to be
reported earlier.

When this option is set to STOP or CONTINUE, it supersedes the setting of the CONTINUE_AFTER_RAISERROR
option. However, when this option is set to CONDITIONAL (the default), behavior following a RAISERROR
statement is determined by the setting of the CONTINUE_AFTER_RAISERROR option.

Related Information

CREATE PROCEDURE Statement [page 1321]


CREATE PROCEDURE Statement [T-SQL] [page 1329]
RAISERROR Statement [T-SQL] [page 1597]
CONTINUE_AFTER_RAISERROR Option [TSQL] [page 1786]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
Differences and Shared Functionality Between SAP ASE and SAP IQ [page 191]

10.6.162 POST_LOGIN_PROCEDURE Option

Specifies a login procedure whose result set contains messages that are displayed by the client application
immediately after a user successfully logs in.

Allowed Values

String

SAP IQ SQL Reference


Database Options INTERNAL 1947
Default

dbo.sa_post_login_procedure

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SECURITY OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The default post login procedure, dbo.sa_post_login_procedure, executes immediately after a user
successfully logs in.

If you have the SET ANY SECURITY OPTION system privilege, you can customize the post login actions by
creating a new procedure and setting POST_LOGIN_PROCEDURE to call the new procedure. Do not edit
dbo.sa_post_login_procedure. The customized post login procedure must be created in every database
you use.

The post login procedure supports the client applications Interactive SQL, and Interactive SQL Classic.

Related Information

LOGIN_PROCEDURE Option [page 1901]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1948 INTERNAL Database Options
10.6.163 PRECISION Option

Specifies the maximum number of digits in the result of any decimal arithmetic, for queries on the catalog
store only.

Allowed Values

1 to 127

Default

126

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect immediately.

Remarks

Precision is the total number of digits to the left and right of the decimal point. The default PRECISION value is
fixed at 126. The SCALE option specifies the minimum number of digits after the decimal point, when an
arithmetic result is truncated to the maximum specified by PRECISION, for queries on the catalog store.

 Note

For IQ catalog store tables, the maximum value supported for the numeric function is 255. If the precision
of the numeric function exceeds the maximum value supported, you see the following error message:
The result datatype for function '_funcname' exceeds the maximum
supported numeric precision of 255. Please set the proper value for
precision in numeric function, 'location'

Related Information

SCALE Option [page 2008]

SAP IQ SQL Reference


Database Options INTERNAL 1949
MAX_CLIENT_NUMERIC_PRECISION Option [page 1904]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.164 PREFETCH Option

Allows you to turn fetching on or off or to use the ALWAYS value to prefetch the cursor results, even for
SENSITIVE cursor types and for cursors that involve a proxy table.

Allowed Values

ON, OFF, ALWAYS

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For the catalog store only, PREFETCH controls whether rows are fetched to the client side before being made
available to the client application. Fetching a number of rows at a time, even when the client application
requests rows one at a time (for example, when looping over the rows of a cursor) minimizes response time and
improves overall throughput by limiting the number of requests to the database.

The setting of PREFETCH is ignored by Open Client and JDBC connections, and for the IQ store.

SAP IQ SQL Reference


1950 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.165 PREFETCH_BUFFER_LIMIT Option

Specifies the amount of memory used for prefetching.

Allowed Values

Integer

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must shut down the
database and restart it for the change to take effect.

Remarks

PREFETCH_BUFFER_LIMIT defines the number of cache pages available to SAP IQ for use in prefetching (the
read-ahead of database pages).

Do not set this option unless advised to do so by Technical Support.

Related Information

PREFETCH_BUFFER_PERCENT Option [page 1952]

SAP IQ SQL Reference


Database Options INTERNAL 1951
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.166 PREFETCH_BUFFER_PERCENT Option

Specifies the percent of memory used for prefetching.

Allowed Values

0 to 100

Default

40

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must shut down the
database and restart it for the change to take effect.

Remarks

PREFETCH_BUFFER_PERCENT is an alternative to PREFETCH_BUFFER_LIMIT, as it specifies the percentage of


cache available for use in prefetching.

Do not set this option unless advised to do so by Technical Support.

Related Information

PREFETCH_BUFFER_LIMIT Option [page 1951]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


1952 INTERNAL Database Options
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.167 PREFETCH_FP_PERCENT Option

Specifies the percent of prefetch resources for column data in all DML operations (insert, update, delete,
query).

Allowed Values

0 – 100

Default

50

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1953
SET OPTION Statement [page 1677]

10.6.168 PREFETCH_GARRAY_PERCENT Option

Specifies the percent of prefetch resources designated for performing all DML operations (insert, update,
delete, query) on HG indexes.

Allowed Values

0 – 100

Default

60

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1954 INTERNAL Database Options
10.6.169 PREFETCH_HASH_PERCENT Option

Specifies the percent of prefetch resources in queries involving hash-based algorithms.

Allowed Values

0 – 100

Default

20

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


Database Options INTERNAL 1955
10.6.170 PREFETCH_LOB_PERCENT Option

Specifies the percent of prefetch resources in queries involving the character large object data type or the
binary large object data type.

Allowed Values

0 – 100

Default

50

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


1956 INTERNAL Database Options
10.6.171 PREFETCH_SORT_PERCENT Option

Specifies the percent of prefetch resources designated for sorting objects.

Allowed Values

0 to 100

Default

20

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

PREFETCH_SORT_PERCENT designates a percentage of prefetch resources for use by a single sort object.
Increasing this value can improve the single-user performance of inserts and deletes, but may have detrimental
effects on multiuser operations.

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1957
10.6.172 PREFETCH_TEXTPOST_PERCENT Option

Specifies the percent of prefetch resources in queries that use CONTAINS on columns with text indexes.

Allowed Values

0 – 100

Default

50

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Do not set this option unless advised to do so by Technical Support.

Related Information

Set a Database Option [page 1727]


REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SET OPTION Statement [page 1677]

SAP IQ SQL Reference


1958 INTERNAL Database Options
10.6.173 PRESERVE_SOURCE_FORMAT Option [Database]

Controls whether the original source definition of procedures, views, and event handlers is saved in system
files. If saved, the formatted source is saved in the column source in SYSTABLE, SYSPROCEDURE, and
SYSEVENT.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When PRESERVE_SOURCE_FORMAT is ON, the server saves the formatted source from CREATE and ALTER
statements on procedures, views, and events, and puts original source definition in the source column of the
appropriate system table.

Unformatted source text is stored in the same system tables, in the columns proc_defn, and view_defn. The
formatted source column allows you to view the definitions with the spacing, comments, and case that you
want.

This option can be turned off to reduce space used to save object definitions in the database. The option can be
set only for the PUBLIC role.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


Database Options INTERNAL 1959
GRANT System Privilege Statement [page 1511]

10.6.174 PROGRESS_MESSAGES Option

Controls whether progress messages are sent from the database server to the client.

Allowed Values

OFF, RAW, FORMATTED

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Value Description

OFF Progress messages are not sent to the client.

SAP IQ SQL Reference


1960 INTERNAL Database Options
Value Description

RAW Uses the following format progress messages:

43;9728;22230;pages;5025;6138

Raw progress messages have six fields separated by semicolons that are defined as follows:

● Field 1 – percentage of statement executed.t


● Field 2 – number of completed pages, rows, or bytes.
● Field 3 – number of pages, rows, or bytes to be processed.
● Field 4 – what is being processed: pages, rows, or bytes.
● Field 5 – current elapsed time displayed in milliseconds.
● Field 6 – estimated time in milliseconds remaining to complete the execution of the statement

FORMATTED When selected, progress messages use the following format:

43% (9728 of 22230 pages) complete after 00:00:05; estimated


00:00:06
remaining

Formatted progress messages are localized, and the time format is HH:MM:SS. Units less than 100 KB are
displayed in bytes, units less than 100 MB are displayed in KB, and units greater than 100 MB are displayed in
MB.

Progress messages are sent at intervals that are 5% of the total estimated duration of the statement. Typically,
the estimate is completed and the first progress message is sent within 10 seconds. Additional progress
messages are sent in intervals of 30 seconds to 5 minutes. If the percentage complete is identical to the value
sent in a previous message, an updated progress message is not sent until more than 5 minutes have elapsed
since the last message was sent. Progress messages are not sent for statements that take less than 30
seconds to execute.

Estimates are recalculated continually; the accuracy of the remaining time estimate increases as the operation
progresses. During events such as backups, the total number of pages may be adjusted during statement
execution, so the percent complete and remaining time estimates change. With statements such as
BACKUP...WITH CHECKPOINT COPY or UNLOAD SELECT the total number of affected pages or rows is
unknown and it is possible for the percentage complete value to be greater than 100%. As a result, the
estimated remaining time cannot be calculated and it is not included in the progress message.

The following statements and procedures support progress messages on the IQ catalog row-store portion:

● BACKUP DATABASE (both image and archive)


● LOAD TABLE (USING FILE and USING CLIENT FILE only)
● MESSAGE
● RESTORE DATABASE
● UNLOAD (all types)
● sa_table_page_usage system procedure

You can set the PROGRESS_MESSAGES option when you are connected to the utility database using the SET
OPTION statement.

SAP IQ SQL Reference


Database Options INTERNAL 1961
You can also set the PROGRESS_MESSAGES option in Interactive SQL by clicking Tools Options SAP IQ
Execution , and then clicking Show progress messages. When Show Progress Messages is enabled, the
progress_messages option is set to Formatted.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.175 QUERY_DETAIL Option

Specifies whether or not to include additional query information in the Query Detail section of the query plan.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1962 INTERNAL Database Options
Remarks

When QUERY_DETAIL and QUERY_PLAN (or QUERY_PLAN_AS_HTML) are both turned on, SAP IQ displays
additional information about the query when producing its query plan. When QUERY_PLAN and
QUERY_PLAN_AS_HTML are OFF, this option is ignored.

When QUERY_PLAN is ON (the default), especially if QUERY_DETAIL is also ON, you might want to enable
message log wrapping or message log archiving to avoid filling up your message log file.

Related Information

QUERY_PLAN Option [page 1964]


QUERY_PLAN_AS_HTML Option [page 1966]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.176 QUERY_NAME Option

Gives a name to an executed query in its query plan.

Allowed Values

Quote-delimited string of up to 80 characters.

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


Database Options INTERNAL 1963
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

You can assign the QUERY_NAME option any quote-delimited string value, up to 80 characters. For example:

set temporary option Query_Name = 'my third query'

When this option is set, query plans that are sent to the .iqmsg file or .html file include a line near the top of
the plan that looks like:

Query_Name: 'my third query'

If you set the option to a different value before each query in a script, it is much easier to identify the correct
query plan for a particular query. The query name is also added to the file name for HTML query plans. This
option has no other effect on the query.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.177 QUERY_PLAN Option

Specifies whether or not additional query plans are printed to the SAP IQ message file.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


1964 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When this option is turned ON, SAP IQ produces textual query plans in the IQ message file. These query plans
display the query tree topography, as well as details about optimization and execution. When this option is
turned OFF, those messages are suppressed. The information is sent to the <dbname>.iqmsg file.

Related Information

QUERY_DETAIL Option [page 1962]


QUERY_PLAN_AFTER_RUN Option [page 1965]
QUERY_PLAN_AS_HTML Option [page 1966]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.178 QUERY_PLAN_AFTER_RUN Option

Prints the entire query plan after query execution is complete.

Allowed Values

ON, OFF

Default

ON

SAP IQ SQL Reference


Database Options INTERNAL 1965
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When QUERY_PLAN_AFTER_RUN is turned ON, the query plan is printed after the query has finished running.
This allows the query plan to include additional information, such as the actual number of rows passed on from
each node of the query.

For this option to work, the QUERY_PLAN option must be set to ON. You can use this option in conjunction with
QUERY_DETAIL to generate additional information in the query plan report.

Related Information

QUERY_DETAIL Option [page 1962]


QUERY_PLAN Option [page 1964]
QUERY_PLAN_AS_HTML Option [page 1966]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.179 QUERY_PLAN_AS_HTML Option

Generates graphical query plans in HTML format for viewing in a Web browser.

Allowed Values

ON, OFF

SAP IQ SQL Reference


1966 INTERNAL Database Options
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When you set this option, also set the QUERY_NAME option for each query, so you know which query is
associated with the query plan.

SAP IQ writes the plans in the same directory as the .iqmsg file. Query plan file names follow these
conventions: <user-name>_<query-name>_<server-type>_<server-
number>_<YYYYMMDD_HHMMSS>_<query-number>_<fragment-number>.html

For example, if the user DBA sets the temporary option QUERY_NAME to 'Query_1123', a file created on
November 8, 2012, at exactly 8:30 a.m. is called DBA_QUERY_1123_L_0__20121108_083000_4.html. The
date, time, and unique <query-number> appended to the file name ensure that existing files are not
overwritten. The <server-type> parameter indicates whether the plan originates from a leader (L) or worker
(W) node. The <server-number> identifies the server where the plan originated when all html files are routed
to a single directory.

On multiplex servers, worker nodes generate an html file for each fragment executed by the worker, which can
result in multiple html files from a single query. These files are identified by <fragment-number>.

 Note

If you use this feature, monitor your disk space usage so you leave enough room for your .iqmsg and log
files to grow. Enable IQ message log wrapping or message log archiving to avoid filling up your message log
file.

QUERY_PLAN_AS_HTML acts independently of the setting for the QUERY_PLAN option. In other words, if
QUERY_PLAN_AS_HTML is ON, you get an HTML format query plan whether or not QUERY_PLAN is ON.

This feature is supported with newer versions of many commonly used browsers. Some browsers might
experience problems with plans generated for very complicated queries.

SAP IQ SQL Reference


Database Options INTERNAL 1967
Examples

Simplex Output Example


Output generated from a query plan named Q1123 on a simplex server:

DBA_QUERY_Q1123_L_0__20121108_083000_4.html

Simplex servers always return a <server-type> parameter that indicates that the plan originated on a leader
(L) with a <query-number> equal to 0. Simplex output never includes a <fragment-number>.

Multiplex Output Example


Output generated from a query plan named Q101 executed on a multiplex server. The leader node (L) <query-
number> is 1; worker (W) nodes are numbered 2 and 3. Notice the <fragment-number> that appears after the
query number in the worker output.

Output generated from the leader node:

DBA_L_1_Q101_20121108_083000_94.html

Output from one of the worker nodes:

DBA_W_2_Q101_20121108_083000_94_2.html
DBA_W_2_Q101_20121108_083000_94_1.html

Corresponding output from another worker:

DBA_W_3_Q101_20121113-054928_94_2.html
DBA_W_3_Q101_20121113-054933_94_1.html

Related Information

QUERY_NAME Option [page 1963]


QUERY_PLAN Option [page 1964]
QUERY_PLAN_AFTER_RUN Option [page 1965]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1968 INTERNAL Database Options
10.6.180 QUERY_PLAN_AS_HTML_DIRECTORY Option

Specifies the directory into which SAP IQ writes the HTML query plans.

Allowed Values

String containing a directory path name

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When the QUERY_PLAN_AS_HTML option is turned ON and a directory is specified with the
QUERY_PLAN_AS_HTML_DIRECTORY option, SAP IQ writes the HTML query plans in the directory specified.
This option provides additional security by allowing HTML query plans to be produced outside of the server
directory. When the QUERY_PLAN_AS_HTML_DIRECTORY option is not used, the query plans are sent to the
default directory (the .iqmsg file directory).

If the QUERY_PLAN_AS_HTML option is ON and QUERY_PLAN_AS_HTML_DIRECTORY is set to a directory that


does not exist, SAP IQ does not save the HTML query plan and no error is generated. In this case, the query
continues to run and a message is logged to the IQ message file, so the DBA knows that the HTML query plan
was not written. If the specified directory path or permissions on the directory are not correct, the message
Error opening HTML Query plan: <file-name> is written in the .iqmsg file.

SAP IQ SQL Reference


Database Options INTERNAL 1969
Example

This example creates the example directory /system1/users/DBA/html_plans and sets the correct
permissions on the directory by setting the options and running the query:

SET TEMPORARY OPTION QUERY_PLAN_AS_HTML = 'ON';


SET TEMPORARY OPTION QUERY_PLAN_AS_HTML_DIRECTORY = '/system1/users/DBA/
html_plans';
SELECT col1 FROM tab1;

The HTML query plan is written to a file in the specified directory /system1/users/DBA/html_plans.

Related Information

QUERY_PLAN_AS_HTML Option [page 1966]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.181 QUERY_PLAN_MIN_TIME Option

Specifies a threshold for query execution. The post-query plan is generated only if query execution time
exceeds the threshold.

Allowed Values

Integer, in milliseconds.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


1970 INTERNAL Database Options
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

A query with a very short execution time (a micro query) executes faster if a query plan is not generated.
Setting this option avoids the generation of query plans, and the associated query plan generation costs for
these queries. The QUERY_PLAN_MIN_TIME option is ignored unless the following options are also set:

● QUERY_PLAN = ON or QUERY_PLAN_AS_HTML = ON
● QUERY_PLAN_AFTER_RUN = ON
● QUERY_TIMING = ON

When these options are set, setting a QUERY_PLAN_MIN_TIME query execution threshold prevents the
generation of query plans for queries with execution times that do not exceed the specified threshold.

If using the statement performance monitoring feature (that is, you set the COLLECT_IQ_PERFORMANCE
option to ON), QUERY_PLAN_MIN_TIME specifies the reporting threshold for query execution times. Only
those SQL statements with execution times exceeding this threshold will be reported.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
COLLECT_IQ_PERFORMANCE_STATS option [page 1785]

10.6.182 QUERY_PLAN_TEXT_ACCESS Option

Enables or prevents users from accessing query plans from the Interactive SQL client or from using SQL
functions to get plans.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 1971
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When QUERY_PLAN_TEXT_ACCESS option is ON, users can view, save, and print query plans from the
Interactive SQL client. When the option is OFF, query plans are not cached, and other query plan-related
database options have no effect on the query plan that is shown from the Interactive SQL client. This error
message appears:
No plan available. The database option QUERY_PLAN_TEXT_ACCESS is OFF.

Related Information

QUERY_DETAIL Option [page 1962]


QUERY_PLAN_AFTER_RUN Option [page 1965]
QUERY_PLAN_AS_HTML Option [page 1966]
QUERY_PLAN_TEXT_CACHING Option [page 1973]
OUTPUT Statement [Interactive SQL] [page 1585]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1972 INTERNAL Database Options
10.6.183 QUERY_PLAN_TEXT_CACHING Option

Allows you to specify whether or not SAP IQ generates and caches IQ plans for queries executed by the user.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

IQ query plans vary in size and can become very large for complex queries. Caching plans for display on the
Interactive SQL client can have high resource requirements. The QUERY_PLAN_TEXT_CACHING option gives
users a mechanism to control resources for caching plans. With this option turned OFF (the default), the query
plan is not cached for that user connection.

 Note

If QUERY_PLAN_TEXT_ACCESS is turned OFF, the query plan is not cached for the connections from that
user, no matter how QUERY_PLAN_TEXT_CACHING is set.

Related Information

QUERY_DETAIL Option [page 1962]


QUERY_PLAN_AFTER_RUN Option [page 1965]

SAP IQ SQL Reference


Database Options INTERNAL 1973
QUERY_PLAN_AS_HTML Option [page 1966]
QUERY_PLAN_TEXT_ACCESS Option [page 1971]
OUTPUT Statement [Interactive SQL] [page 1585]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.184 QUERY_ROWS_RETURNED_LIMIT Option

Sets the row threshold for rejecting queries based on estimated size of result set.

Allowed Values

Any integer

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If SAP IQ receives a query that has an estimated number of result rows greater than the value of
QUERY_ROWS_RETURNED_LIMIT, it rejects the query with this message:
Query rejected because it exceeds resource: Query_Rows_Returned_Limit

If you set this option to 0 (the default), there is no limit, and no queries are rejected based on the number of
rows in their output.

SAP IQ SQL Reference


1974 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.185 QUERY_TEMP_SPACE_LIMIT Option

Specifies the maximum estimated amount of temp space before a query is rejected.

Allowed Values

Any integer

Default

0 (no limit)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If SAP IQ receives a query that is estimated to require a temporary result space larger than value of this option,
it rejects the query with this message:
Query rejected because it exceeds total space resource limit

When set to 0 (the default), there is no limit on temporary store usage by queries.

Users may override this option in their own environments to run queries that can potentially fill up the entire
temporary store. To prevent runaway queries from filling up the temporary store, a user with the SET ANY

SAP IQ SQL Reference


Database Options INTERNAL 1975
SYSTEM OPTION system privilege can set the option MAX_TEMP_SPACE_PER_CONNECTION. The
MAX_TEMP_SPACE_PER_CONNECTION option monitors and limits actual temporary store usage for all DML
statements, not just queries.

In a distributed query processing transaction, SAP IQ uses the values set for the QUERY_TEMP_SPACE_LIMIT
and MAX_TEMP_SPACE_PER_CONNECTION options for the shared temporary store by limiting the total shared
and local temporary space used by all nodes participating in the distributed query. This means that any single
query cannot exceed the total temp space limit (from IQ_SYSTEM_TEMP and IQ_SHARED_TEMP dbspaces), no
matter how many nodes participate.

For example, if the limit is 100 and four nodes use 25 units of temporary space each, the query is within limits.
If the sum of the total space used by any of the nodes exceeds 100, however, the query rolls back.

Related Information

MAX_TEMP_SPACE_PER_CONNECTION Option [page 1920]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.186 QUERY_TIMING Option

Determines whether or not to collect specific timing statistics and display them in the query plan.

Allowed Values

ON, OFF

Default

ON

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value

SAP IQ SQL Reference


1976 INTERNAL Database Options
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option controls the collection of timing statistics on subqueries and some other repetitive functions in the
query engine.

Query timing is represented in the query plan detail as a series of timestamps. These timestamps correspond
to query operator phases (Conditions, Prepare, Fetch, Complete). HTML and Interactive SQL query plans
display query timing graphically as a timeline.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.187 QUOTED_IDENTIFIER Option [TSQL]

Controls the interpretation of strings that are enclosed in double quotes.

Allowed Values

ON, OFF

Default

● ON
● OFF – for Open Client connections.

SAP IQ SQL Reference


Database Options INTERNAL 1977
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

QUOTED_IDENTIFIER controls whether strings enclosed in double quotes are interpreted as identifiers (ON)
or as literal strings (OFF). This option is included for Transact-SQL compatibility.

SAP IQ Cockpit and Interactive SQL set QUOTED_IDENTIFIER temporarily to ON, if it is set to OFF. A message
is displayed informing you of this change. The change is in effect only for the SAP IQ Cockpit or Interactive SQL
connection. The JDBC driver also temporarily sets QUOTED_IDENTIFIER to ON.

10.6.188 RECOVERY_TIME Option

Sets the maximum length of time, in minutes, that the database server takes to recover from system failure.

Allowed Values

Integer, in minutes

Default

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must restart the server for
the change to take effect.

SAP IQ SQL Reference


1978 INTERNAL Database Options
Remarks

Use this option with the CHECKPOINT_TIME option to decide when checkpoints should be done.

A heuristic measures the recovery time based on the operations since the last checkpoint. Thus, the recovery
time is not exact.

Related Information

CHECKPOINT_TIME Option [page 1782]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.189 reserved_connections option

Controls the minimum number of concurrent connections that a database must reserve for standard
connections. This option is useful when your database server accepts HTTP/HTTPS connections.

Allowed values

size

This integer specifies the number of concurrent connections that the database must reserve for standard
connections.

For databases running on the network database server, specify a number that fulfills the following
requirements:

● Less than the maximum database server connection limit as allowed by your license.
● Less than the maximum database server connection limit as specified by the -gm database server
option.
● Less than the maximum database connection limit specified by the max_connections database option.

SAP IQ SQL Reference


Database Options INTERNAL 1979
Scope

PUBLIC role For current user For other users

Allowed to set permanently? Yes with SET ANY SYSTEM No No


OPTION

Allowed to set temporarily? Yes with SET ANY SYSTEM No No


OPTION

Remarks

Setting this option ensures that a database can accept standard connections even when its HTTP/HTTPS
connections are queued.

A database server accepts HTTP/HTTPS connections until it reaches its license limit, and then it queues
subsequent HTTP/HTTPS connections and processes them as connections are made available. There is no
opportunity for a standard connection to replace an HTTP/HTTPS connection while there are connection
attempts in the queue. Users wanting to make a standard connection, could wait indefinitely for the HTTP/
HTTPS connection queue to complete. Use the reserved_connections option to specify a minimum number of
database connections that can only accept standard connections.

By default, the network database server does not reserve connections.

You can view the current number of reserved connections for a database by querying the value of the
reserved_connections connection property:

SELECT CONNECTION_PROPERTY ( 'reserved_connections' );

Example

The following example reserves 10 connections for standard connections.

SET OPTION PUBLIC.reserved_connections=10;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1980 INTERNAL Database Options
10.6.190 RESERVED_KEYWORDS Option

Turns on individual keywords that are disabled by default.

Allowed Values

String

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option turns on individual keywords that are disabled by default. Only the LIMIT keyword can be turned on.

Examples

The following statement allows the LIMIT keyword to be recognized as a keyword:

SET OPTION RESERVED_KEYWORDS = 'LIMIT';

You cannot turn on the keywords SET, OPTION, and OPTIONS. The following determine whether a word is
identified as a keyword (in order of precedence):

● It appears in the SAP SQL Anywhere list of reserved words


● It is turned on with the RESERVED_KEYWORDS option
● It is turned off with the NON_KEYWORDS option

Each setting of this option replaces the previous setting. The following statement clears all previous settings:

SET OPTION RESERVED_KEYWORDS = ;

SAP IQ SQL Reference


Database Options INTERNAL 1981
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.191 RETURN_DATE_TIME_AS_STRING Option

Controls how a date, time, or timestamp value is passed to the client application when queried.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set as a temporary option only, for the duration of the current connection or for the PUBLIC
role.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect immediately.

Remarks

RETURN_DATE_TIME_AS_STRING indicates whether date, time, and timestamp values are returned to
applications as a date or time data type or as a string.

When this option is set to ON, the server converts the date, time, or timestamp value to a string before it is sent
to the client in order to preserve the TIMESTAMP_FORMAT, DATE_FORMAT, or TIME_FORMAT option setting.

SAP IQ Cockpit and Interactive SQL automatically turn the RETURN_DATE_TIME_AS_STRING option ON.

SAP IQ SQL Reference


1982 INTERNAL Database Options
Related Information

DATE_FORMAT Option [page 1804]


TIME_FORMAT Option [page 2058]
TIMESTAMP_FORMAT Option [page 2059]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.192 REVERT_TO_V15_OPTIMIZER Option

Setting this option ON forces the query optimizer to mimic SAP IQ 15.x behavior.

Allowed Values

ON, OFF

Default

● ON – in all 16.1 databases upgraded from 15.x


● OFF – in all newly created 16.1 databases

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. If permitted, can be set for an arbitrary other user or role, or
for all users via the role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 1983
Remarks

 Caution

The REVERT_TO_V15_OPTIMIZER option is normally used for internal testing and manually tuning queries.
Only experienced DBAs should use it.

SAP IQ 16.1 supports several new join and grouping algorithms that leverage Hash and Hash-Range partitioned
tables, as well as a few other new algorithms. By default, all of these new algorithms are considered by the
optimizer and will be selected where valid and appropriate. Setting REVERT_TO_V15_OPTIMIZER to ON
disables all 16.1 changes to the optimizer cost models. It also disables all of these new join and grouping
algorithms, unless they are valid and are specifically requested via a positive value for either the
AGGREGATION_PREFERENCE option, the JOIN_PREFERENCE option, or a join condition hint string.

 Note

An error will result if your query references an RLV-enabled table and REVERT_TO_V15_OPTIMIZER='ON'.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.193 ROUND_TO_EVEN Option

Controls behavior of the SQL function ROUND when querying SAP IQ tables.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


1984 INTERNAL Database Options
Scope

Requires the SET ANY SYSTEM OPTION system privilege. Can be set for the PUBLIC role only. Takes effect
immediately.

Remarks

The ROUND function rounds the digits after the decimal to the nearest value using the specified number of
places. When the value of the last digit of the specified number of places is 5 (exactly half way between the two
nearest values), the ROUND_TO_EVEN option determines how the digit is rounded. When set to ON, the digit
rounds to the nearest even number. When set to OFF, the digit rounds to the value with the largest absolute
value.

Examples

Table MyTable contains DOUBLE(10,2) values:

c1

-0.35

-0.25

0.25

0.35

Execute:

select c1, round(c1, 1) from MyTable order by c1;

When ROUND_TO_EVEN is OFF, the query returns:

c1 round(MyTable,c1,1)

-0.35 -0.4

-0.25 -0.3

0.25 0.3

0.35 0.4

When ROUND_TO_EVEN is ON, the query returns:

c1 round(MyTable,c1,1)

-0.35 -0.4

-0.25 -0.2

SAP IQ SQL Reference


Database Options INTERNAL 1985
c1 round(MyTable,c1,1)

0.25 0.2

0.35 0.4

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.194 ROW_COUNT Option

Limits the number of rows returned from a query.

Allowed Values

Integer

Default

0 (no limit on rows returned)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


1986 INTERNAL Database Options
Remarks

When this runtime option is set to a nonzero value, query processing stops after the specified number of rows.

This option affects only statements with the keyword SELECT and does not affect UPDATE and DELETE
statements.

The SELECT statement keywords FIRST and TOP also limit the number of rows returned from a query. Using
FIRST is the same as setting the ROW_COUNT database option to 1. Using TOP is the same as setting
ROW_COUNT to the same number of rows. If both TOP and ROW_COUNT are set, then the value of TOP takes
precedence.

The ROW_COUNT option could produce non-deterministic results when used in a query involving global
variables, system functions or proxy tables. Such queries are partly executed using CIS (Component Integrated
Services). In such cases, use SELECT TOP <n> instead of setting ROW_COUNT, or set the global variable to a
local one and use that local variable in the query.

Related Information

QUERY_ROWS_RETURNED_LIMIT Option [page 1974]


SELECT Statement [page 1659]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.195 RV_AUTO_MERGE Option

This option enables or disables automatic merges of the RLV store into the IQ main store for row-level,
versioning-enabled tables.

Allowed Values

ON, OFF

Default

ON

SAP IQ SQL Reference


Database Options INTERNAL 1987
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

As of SAP IQ 16.0 SP 11, the RV_AUTO_MERGE database option replaces the deprecated
sa_server_option('rlv_auto_merge') system procedure call for enabling and disabling auto merge. To
avoid potential conflicts, replace all calls to set the system procedure using the deprecated option with calls to
set the database option. In the event both options are called, the value used is set by the last option called.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.196 RV_AUTO_MERGE_EVAL_INTERVAL Option

This option configures the evaluation period used to determine when an automated merge of the row-level
versioned (RLV) and IQ main stores should occur.

Allowed Values

1 to MAX_UINT (minutes)

Default

15 (minutes)

SAP IQ SQL Reference


1988 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option is be used to configure the period of wait time, in minutes, between activations of the merge
evaluator. The merge evaluator examines the merge parameters of each row-level versioning (RLV) enabled
table against configured threshold values to determine whether a non-blocking (background) merge of the RLV
table to IQ main stores should occur.

If the interval ends while the evaluator is active, or when a merge is already in progress, the interval re-sets.

Any new value for the interval is used when the merge evaluator is next activated.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.197 RV_BLOCK_SIZE_ALLOCATION_STRATEGY Option

Defines the strategy to use for subsequent array allocation for fixed length datatype columns in the RLV in-
memory store.

Allowed values

1 to 4

Default

SAP IQ SQL Reference


Database Options INTERNAL 1989
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect the next time the
RLV store for the table is destroyed and re-created.

Remarks

Once the RLV store is created using the current allocation strategy, if the strategy is changed, it is not used by a
table until the RLV store for the table is destroyed and re-created as the result of a DDL, an automerge, or the
user explicitly calling the sp_iqmergerlvstore procedure.

ID Name Description

1 Two Block Allocates the first block size as defined by RV_INITIAL_FIX_DATA_BLOCKSIZE.


Each subsequent block size is defined by RV_FIX_DATA_BLOCKSIZE

2 (default) Percent Increase Allocates the first block size as defined by RV_INITIAL_FIX_DATA_BLOCKSIZE.
Each subsequent block size grows by the percentage defined by
RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZE

3 Delta Increase Allocates the first block size as defined by RV_INITIAL_FIX_DATA_BLOCKSIZE.


Each subsequent block size grows by the size defined by
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE

4 Constant Allocates block size as defined by RV_FIX_DATA_BLOCKSIZE

Example

This example sets the allocation strategy to 3 and creates RLV-endabled tables t1 and t2. Data is inserted into
table t1, creating the RLV store for table t1. The RLV store for table t2 has not yet been created:

SET public.RV_Block_Size_Allocation_Strategy=3;
CREATE TABLE t1 ( a int ) ENABLE RLV STORE;
CREATE TABLE t2 ( a int ) ENABLE RLV STORE;
INSERT INTO t1 values(1);
COMMIT;

The allocation strategy is changed to 4. Data is now inserted into table t2. The RLV store for table t2 is created
using the new allocation strategy. t1 continues to use the original allocation strategy:

SET public.RV_Block_Size_Allocation_Strategy=4;
INSERT INTO t2 values(2);
COMMIT;

Column b is added to table t1. This destroys the current RLV store for table t1 (assuming no old transactions
exist) and then re-recreates it using the new allocation strategy:

ALTER TABLE t1 add b int;


INSERT INTO t1 values(3);

SAP IQ SQL Reference


1990 INTERNAL Database Options
COMMIT;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.198 RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE
Option

Defines the delta size increase size (in bytes) for subsequent array allocation for fixed length datatype columns
in the RLV in-memory store. The nth block size is the value of (n-1)th block size +
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE. This is used by the Delta Increase allocation strategy.

Allowed values

100 to 268,435,456 (256 MB)

Default

1024 (1 KB)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect the next time the
RLV store for the table is destroyed and re-created.

SAP IQ SQL Reference


Database Options INTERNAL 1991
Example

This example sets the allocation strategy to 2, creates RLV-enabled table t1, and creates the RLV store by
inserting data into the table. It uses the default values for RV_INITIAL_FIX_DATA_BLOCKSIZE and
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE:

set public.RV_Block_Size_Allocation_Strategy=2;
create table t1 ( a int ) enable rlv store;
insert into t1 values(1);
commit;

The RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE value is changed to 50 percent and data is inserted


into the table:

set public.RV_Percent_Increase_In_Fix_Data_BlockSize=50;
insert into t1 values(2);

Column b is added to table t1 and data inserted. This destroys the current RLV store for table t1 (assuming no
old transactions exist) and then re-creates it using the default value for RV_INITIAL_FIX_DATA_BLOCKSIZE
and the new value for RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE:

ALTER TABLE t1 add b varchar;


INSERT INTO t1 values(3);
COMMIT;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.199 RV_FIX_DATA_BLOCKSIZE Option

Defines the size (in bytes) of every subsequent array allocation for fixed length datatype columns in the RLV in-
memory store. It is used by the Constant allocation strategy.

Allowed values

100 to 16,777,216 (16 MB)

SAP IQ SQL Reference


1992 INTERNAL Database Options
Default

16,777,216 (16 MB)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect the next time the
RLV store for the table is destroyed and re-created.

Example

This example sets the allocation strategy to 4, creates RLV-enabled table t1, and creates the RLV store by
inserting data into the table. It uses the default value for RV_FIX_DATA_BLOCKSIZE:

set public.RV_Block_Size_Allocation_Strategy=4;
create table t1 ( a int ) enable rlv store;
insert into t1 values(1);
commit;

The RV_FIX_DATA_BLOCKSIZE value is changed to 8388608 bytes and data is inserted into table t1:

set public.RV_FIX_DATA_BLOCKSIZE=8388608;
insert into t1 values(2);

Column b is added to table t1 and data inserted. This destroys the current RLV store for table t1 (assuming no
old transactions exist) and then re-creates it using the new value for the RV_FIX_DATA_BLOCKSIZE:

ALTER TABLE t1 add b int;


INSERT INTO t1 values(3);
COMMIT;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1993
10.6.200 RV_INITIAL_FIX_DATA_BLOCKSIZE Option

Defines the size (in bytes) of the first array allocation for fixed length datatype columns in the RLV in-memory
store. It is used as a starting size by all fixed block allocation strategies.

Allowed values

100 to 268,435,456 (256 MB)

Default

4096 (4 KB)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect the next time the
RLV store for the table is destroyed and re-created.

Example

This example sets the allocation strategy to 2, creates RLV-enabled table t1, and creates the RLV store by
inserting data into the table. It uses the default values for RV_INITIAL_FIX_DATA_BLOCKSIZE and
RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE:

set public.RV_Block_Size_Allocation_Strategy=2;
create table t1 ( a int ) enable rlv store;
insert into t1 values(1);
commit;

The RV_INITIAL_FIX_DATA_BLOCKSIZE value is changed to 2048 bytes and data is inserted into t1:

set public.RV_INITIAL_FIX_DATA_BLOCKSIZE=2048;
insert into t1 values(2);

Column b is added to table t1 and data inserted. This destroys the current RLV store for table t1 (assuming no
old transactions exist) and then re-creates it using the new value for RV_INITIAL_FIX_DATA_BLOCKSIZE and
the default value for RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE:

ALTER TABLE t1 add b int;


INSERT INTO t1 values(3);
COMMIT;

SAP IQ SQL Reference


1994 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.201 RV_MAX_ACTIVE_SUBFRAGMENT_COUNT Option

This value maximizes utilization of the number of cores on the machine.

Allowed Values

>=0

Default

 Note

Use of any value other than the default is not recommended as it could negatively impact CPU utilization
and scalability of bulk loads.

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. This option takes effect on a
table with the first write operation on the table. If the value of this option is changed after the first write
operation has occurred, the new value does not take effect on the table until after a restart of the server.

Remarks

If the value is set to anything other than the default, the system uses the specified value or the total number of
cores on the machine, whichever is less.

SAP IQ SQL Reference


Database Options INTERNAL 1995
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.202 RV_MAX_LOOKUP_MB Option

This value limits the total in-memory dictionary size for implicit NBit FP columns.

Allowed Values

1 to 4,294,967,295

Default

64 (MB)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set for the PUBLIC role.
Takes effect when the in-memory portion of a table is first created, as a result of a CREATE TABLE, ALTER
TABLE or merge operation. Changes to this property do not affect existing in-memory tables.

Remarks

RV_MAX_TOKEN and RV_MAX_LOOKUP_MB database options establish a ceiling for sizing in-memory implicit
NBit columns. While the number of distinct values is less than RV_MAX_TOKEN and the total dictionary size
(values and counts) is less than RV_MAX_LOOKUP_MB, the column loads with an in-memory NBit FP index.
When DML operations exceed the RV_MAX_TOKEN or RV_MAX_LOOKUP_MB limits, the in-memory NBit FP index
rolls over to a Flat FP index.

SAP IQ SQL Reference


1996 INTERNAL Database Options
Example

In this example, the dictionary of in-memory store for table FOO can expand to a maximum of 10 MB is size:

SET OPTION PUBLIC.Rv_Max_Lookup_MB = 10;


CREATE TABLE FOO( a INT ) ENABLE RLV STORE;

The existing in-memory store for table FOO remains configured to a maximum directory size of 10 MB; the new
option value has no impact:

SET OPTION PUBLIC.Rv_Max_Lookup_MB = 5;

The ALTER TABLE command merges the existing in-memory data for table FOO to the IQ main store and then
creates a new in-memory store. The new in-memory store uses the current property value of 5, not the original
property value of 10:

ALTER TABLE FOO ADD COLUMN( b INT )

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.203 RV_MAX_TOKEN Option

This value provides an upper bound for the number of NBit tokens used in the in-memory dictionary.

Allowed Values

2 to 2,147,475,456

Default

2,147,475,456

SAP IQ SQL Reference


Database Options INTERNAL 1997
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set for the PUBLIC role.
Takes effect when the in-memory portion of a table is first created, as a result of a CREATE TABLE, ALTER
TABLE or merge operation. Changes to this property do not affect existing in-memory tables.

Remarks

For each distinct data value an NBit token will be created. Once the number of tokens issues exceeds this
property value, the in-memory store rolls over to flat data storage.

Example

In this example, the in-memory store for table FOO can hold a maximum of 100 NBit tokens:

SET OPTION PUBLIC.Rv_Max_Token = 100;


CREATE TABLE FOO( a INT ) ENABLE RLV STORE;

The existing in-memory store for table FOO remains configured to hold 100 NBit tokens; The new option value
has no impact:

SET OPTION PUBLIC.Rv_Max_Token = 50;

The ALTER TABLE command merges the existing in-memory data for table FOO to the IQ main store and then
creates a new in-memory store; the new in-memory store uses the current property value of 50, not the original
property value of 100:

ALTER TABLE FOO ADD COLUMN( b INT )

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


1998 INTERNAL Database Options
10.6.204 RV_MERGE_NODE_MEMSIZE Option

Sets the percentage of total RLV memory size as a merge threshold for the node.

Allowed Values

0 to 100 (percent)

Default

75 (percent)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

If the total RLV memory used surpasses the threshold when compared against the maximum configured RLV
memory size for the node, the merge condition evaluator determines which table(s) to merge.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 1999
10.6.205 RV_MERGE_TABLE_COMMIT_AGE Option

Triggers an RLV merge to occur based on a time interval since the last commit.

Allowed Values

Integer, in minutes

Default

10

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When the merge evaluator starts, it compares the last commit time with the value defined by the
RV_MERGE_TABLE_COMMIT_AGE option. If the elapsed time since the last commit is at least equal to the
value of RV_MERGE_TABLE_COMMIT_AGE, the table is set as a merge candidate.

If the server is shut down after a commit, but prior to a merge, when the server restarts, the elapsed time
between the last commit and the shutdown is reset to the current time at restart.

Example

The following options are defined as follows:

● RV_MERGE_TABLE_COMMIT_AGE – 10 mins
● RV_AUTO_MERGE_EVAL_INTERVAL – 6 mins

Scenario 1
RLV-enabled table T1 is created, data inserted, and a commit executed. Six minutes after the commit, the
merge evaluator starts. Since the elapsed time since the commit is less than the value of
RV_MERGE_TABLE_COMMIT_AGE (6<10), T1 is not considered a candidate for a merge.

SAP IQ SQL Reference


2000 INTERNAL Database Options
Another six minutes pass, and the merge evaluator starts again. Since the elapsed time since the last commit is
now greater than the value of RV_MERGE_TABLE_COMMIT_AGE (12>10), and T1 now qualifies as a merge
candidate.

Scenario 2
Data is inserted into T1 and a commit executed. Two minutes later, the server is shut down and restarted. Six
minutes after restart, the merge evaluator starts. The calculated time since last commit is 6 minutes (elapsed
time since restart). Since the calculated value is less than the value of RV_MERGE_TABLE_COMMIT_AGE, T1 is
not yet considered a candidate for merge.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.206 RV_MERGE_TABLE_DELPERCENT Option

Defines the threshold of deleted and committed table rows to trigger a merge expressed as a percentage. If the
number of deleted rows used surpasses the threshold, a merge occurs.

Allowed Values

0 to 100 (percent)

Default

40 (percent)

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 2001
Remarks

RLV query performance can degrade when a large number of rows has been deleted from tables in the RLV
store, improving once the tables are merged. The automerge algorithm uses the
RV_MERGE_TABLE_DELPERCENT option as one of the factors to determine if a table needs merging. On a per
RLV-enabled table basis, the number of deleted rows is evaluated. If the number exceeds the threshold, the
table is flagged for possible merge.

A merge of a single table is deemed warranted if the system does not contain a large percentage of
uncommitted RLV rows preventing a merge, and the table exceeds any of these thresholds:

● Memory threshold – RV_MERGE_TABLE_MEMPERCENT


● Row threshold – RV_MERGE_TABLE_NUMROWS
● Delete threshold – RV_MERGE_TABLE_DELPERCENT

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.207 RV_MERGE_TABLE_MEMPERCENT Option

Sets the percentage of memory used as a merge threshold for an RLV-enabled table. If the memory used
surpasses the threshold, a merge occurs.

Allowed Values

0 to 100 (percent)

Default

0 (percent)

SAP IQ SQL Reference


2002 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

 Note

When RV_MERGE_TABLE_MEMPERCENT = 0, the system uses a (per-table) threshold of 100% / <N>,


where <N> is the number of RLV-enabled tables that have been loaded.

The automerge algorithm uses the RV_MERGE_TABLE_MEMPERCENT option as one of the factors to determine
if a table needs merging. On a per RLV-enabled table basis, memory usage is evaluated. If the memory used
exceeds the threshold, the table is flagged for possible merge.

A merge of a single table is deemed warranted if the system does not contain a large percentage of
uncommitted RLV rows preventing a merge, and the table exceeds any of these thresholds:

● Memory threshold – RV_MERGE_TABLE_MEMPERCENT


● Row threshold – RV_MERGE_TABLE_NUMROWS
● Delete threshold – RV_MERGE_TABLE_DELPERCENT

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.208 RV_MERGE_TABLE_NUMROWS Option

Sets the number of rows used as a merge threshold for an RLV-enabled table. If the number of rows used
surpasses the threshold, a merge occurs.

Allowed Values

1000 to 100,000,000

SAP IQ SQL Reference


Database Options INTERNAL 2003
Default

10,000,000

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

The automerge algorithm uses the RV_MERGE_TABLE_NUMROWS option as one of the factors to determine if a
table needs merging. On a per RLV-enabled table basis, the number of rows used is evaluated. If usage exceeds
the threshold, the table is flagged for possible merge.

A merge of a single table is deemed warranted if the system does not contain a large percentage of
uncommitted RLV rows preventing a merge, and the table exceeds any of these thresholds:

● Memory threshold – RV_MERGE_TABLE_MEMPERCENT


● Row threshold – RV_MERGE_TABLE_NUMROWS
● Delete threshold – RV_MERGE_TABLE_DELPERCENT

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.209 RV_PERCENT_INCREASE_IN_FIX_DATA_BLOCKSIZ
E Option

Defines the percentage size increase for subsequent array allocation for fixed length datatype columns in the
RLV in-memory store. The nth block size is the value of (n-1)th block size + ((n-1)th block size *

SAP IQ SQL Reference


2004 INTERNAL Database Options
RV_PERCENT_INCREASE_IN_FIX_DTA_BLOCKSIZE / 100). This is used by the Percent Increase allocation
strategy.

Allowed values

10 to 100

Default

100

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.210 RV_RESERVED_DBSPACE_MB Option

A portion of the RLV store must be reserved for memory used by data structures during critical operations.

Allowed Values

Integer greater than or equal to 50 (megabytes)

SAP IQ SQL Reference


Database Options INTERNAL 2005
Default

Lesser of 50 MB or half the size of the RLV dbspace

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately. The
server does not need to be restarted in order to change reserved space size.

Description

This option allows you to control the amount of space set aside in the RLV store for small but critical data
structures used during release savepoint, commit, and rollback operations.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.211 RV_VAR_DATA_BLOCKSIZE Option

Defines the size (in bytes) of every array allocation for variable length datatype columns in the RLV in-memory
store.

Allowed values

131,072 to 268,435,456 (256 MB)

Default

131,072 (128 KB)

SAP IQ SQL Reference


2006 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect the next time the
RLV store for the table is destroyed and re-created.

Example

This example creates RLV-enabled table t1 containing variable length column a, and creates the RLV store by
inserting data into the table. It uses the default values for RV_VAR_DATA_BLOCKSIZE:

create table t1 ( a varcahr ) enable rlv store;


insert into t1 values(1);
commit;

The RV_VAR_DATA_BLOCKSIZE value is changed to 65536 bytes and data is inserted into t1:

set public.RV_VAR_DATA_BLOCKSIZE=65536;
insert into t1 values(2);

Column b is added to table t1 and data inserted. This destroys the current RLV store for table t1 (assuming no
old transactions exist) and then re-creates it using the default value for RV_INITIAL_FIX_DATA_BLOCKSIZE
and the new value for RV_DELTA_INCREASE_IN_FIX_DATA_BLOCKSIZE:

ALTER TABLE t1 add b varchar;


INSERT INTO t1 values(3);
COMMIT;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2007
10.6.212 SCALE Option

Specifies the minimum number of digits after the decimal point when an arithmetic result is truncated to the
maximum PRECISION, for queries on the catalog store only.

Allowed Values

Integer, with a maximum of 126.

Default

38

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option specifies the minimum number of digits after the decimal point when an arithmetic result is
truncated to the maximum PRECISION, for queries on the catalog store.

Multiplication, division, addition, subtraction, and aggregate functions may all have results that exceed the
maximum precision.

Related Information

MAX_CLIENT_NUMERIC_SCALE Option [page 1906]


PRECISION Option [page 1949]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2008 INTERNAL Database Options
10.6.213 SIGNIFICANTDIGITSFORDOUBLEEQUALITY Option

Specifies the number of significant digits to the right of the decimal in exponential notation that are used in
equality tests between two complex arithmetic expressions.

Allowed Values

0 to 15

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Doubles are stored in binary (base 2) instead of decimal (base 10); this means that this setting gives the
approximate number of significant decimal digits used. If set to 0, all digits are used.

For example, when SIGNIFICANTDIGITSFORDOUBLEEQUALITY is set to 12, these numbers compare as equal;
when set to 13, they do not:

● 1.23456789012345
● 1.23456789012389

SIGNIFICANTDIGITSFORDOUBLEEQUALITY affects equality tests between two complex arithmetic


expressions, not those done by the indexes.

Related Information

Set a Database Option [page 1727]

SAP IQ SQL Reference


Database Options INTERNAL 2009
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.214 SNAPSHOT_VERSIONING Option

Controls whether RLV-enabled tables are accessed using single-writer table-level versioning, or multiple writer
row-level versioning. Applies to RLV-enabled tables only.

Allowed Values

row-level, table-level

Default

table-level

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Takes effect immediately.

Remarks

 Note

The allowed values may be restricted by the value defined by the ALLOW_SNAPSHOT_VERSIONING option.

SAP IQ SQL Reference


2010 INTERNAL Database Options
Value Action

row-level Enables concurrent writer access and row-level versioning for RLV-enabled tables.

The first transaction to modify a table row establishes a row write lock that persists until the
end of the transaction.

Subsequent transactions attempting to modify a locked row either fail with a lock/future
version error, or block until the lock is released based on the value of the BLOCKING option.

table-level Enables single-writer access and table-level versioning.

The first transaction to access the table establishes a table write lock, which persists until
the end of the transaction.

Subsequent transactions attempting to write to a locked table either fail with a lock/future
version error, or block until the lock is released based on the value of the BLOCKING option.

Related Information

ALLOW_SNAPSHOT_VERSIONING Option [page 1758]


ALLOW_SNAPSHOT_VERSIONING Option [page 1758]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.215 SORT_COLLATION Option

Allows implicit use of the SORTKEY function on ORDER BY expressions.

Allowed Values

Internal, collation_name, or collation_id

Default

Internal

SAP IQ SQL Reference


Database Options INTERNAL 2011
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When the value of SORT_COLLATION is Internal, the ORDER BY clause remains unchanged.

When the value of this option is set to a valid collation name or collation ID, any string expression in the ORDER
BY clause is treated as if the SORTKEY function has been invoked.

Example

Set the sort collation to binary:

SET TEMPORARY OPTION sort_collation='binary';

Setting the sort collation to binary transforms these queries:

SELECT Name, ID
FROM Products
ORDER BY Name, ID;
SELECT Name, ID
FROM Products
ORDER BY 1, 2;

The queries are transformed into the following:

SELECT Name, ID
FROM Products
ORDER BY SORTKEY(Name, 'binary'), ID;

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]
SORTKEY Function [String] [page 509]

SAP IQ SQL Reference


2012 INTERNAL Database Options
10.6.216 SORT_PINNABLE_CACHE_PERCENT Option

Specifies the maximum percentage of currently available buffers a sort object tries to pin.

Allowed Values

0 to 100

Default

20

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For very large sorts, a larger value might help reduce the number of merge phases required by the sort. A larger
number, however, might impact the sorts and hashes of other users running on the system. If you change this
option, experiment to find the best value to increase performance, as choosing the wrong value might decrease
performance.

 Tip

Use the default value for SORT_PINNABLE_CACHE_PERCENT.

This option is primarily for use by Technical Support. If you change the value of
SORT_PINNABLE_CACHE_PERCENT, do so with extreme caution.

Related Information

Set a Database Option [page 1727]

SAP IQ SQL Reference


Database Options INTERNAL 2013
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.217 SQL_FLAGGER_ERROR_LEVEL Option [TSQL]

Controls the behavior in response to any SQL code that is not part of the specified standard.

Allowed Values

● OFF
● SQL:1992/EntrySQL:1992/Intermediate
● SQL:1992/Full
● SQL:1999/Core
● SQL:1999/Package
● SQL:2003/Core
● SQL:2003/Package

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Flags as an error any SQL code that is not part of a specified standard. For example, specifying SQL:2003/
Package causes the database server to flag syntax that is not full SQL/2003 syntax.

For compatibility with previous SAP IQ versions, the following values are also accepted, and are mapped as
specified. Compatibility values for SQL_FLAGGER_ERROR_LEVEL are:

SAP IQ SQL Reference


2014 INTERNAL Database Options
● E – flag syntax that is not entry-level SQL92 syntax. Corresponds to SQL:1992/Entry.
● I – flag syntax that is not intermediate-level SQL92 syntax. Corresponds to SQL:1992/Intermediate.
● F – flag syntax that is not full-SQL92 syntax. Corresponds to SQL:1992/Full.
● W – allow all supported syntax. Corresponds to OFF.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.218 SQL_FLAGGER_WARNING_LEVEL Option [TSQL]

Controls the response to any SQL that is not part of the specified standard.

Allowed Values

● OFF
● SQL:1992/Entry
● SQL:1992/Intermediate
● SQL:1992/Full
● SQL:1999/Core
● SQL:1999/Package
● SQL:2003/Core
● SQL:2003/Package

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.

SAP IQ SQL Reference


Database Options INTERNAL 2015
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Flags as an error any SQL code that is not part of a specified standard as a warning. For example, specifying
SQL:2003/Package causes the database server to flag syntax that is not full SQL/2003 syntax.

The default behavior, OFF, turns warning flagging off.

For compatibility with previous SAP IQ versions, the following values are also accepted, and are mapped as
specified. Compatibility values for SQL_FLAGGER_WARNING_LEVEL are:

● E – flag syntax that is not entry-level SQL92 syntax. Corresponds to SQL:1992/Entry.


● I – flag syntax that is not intermediate-level SQL92 syntax. Corresponds to SQL:1992/Intermediate.
● F – flag syntax that is not full-SQL92 syntax. Corresponds to SQL:1992/Full.
● W – allow all supported syntax. Corresponds to OFF.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.219 STRING_RTRUNCATION Option [TSQL]

Determines whether an error is raised when an INSERT or UPDATE truncates a CHAR or VARCHAR string.

Allowed Values

ON, OFF

Default

ON

SAP IQ SQL Reference


2016 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If the truncated characters consist only of spaces, no exception is raised. ON corresponds to SQL92 behavior.
When STRING_RTRUNCATION is OFF, the exception is not raised and the character string is silently truncated.
If the option is ON and an error is raised, a ROLLBACK occurs.

This option was OFF by default prior to SAP IQ 15. It can safely be set to OFF for backward compatibility.
However, the ON setting is preferable to identify statements where truncation may cause data loss.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.220 SUBQUERY_CACHING_PREFERENCE Option

Controls which algorithm to use for processing correlated subquery predicates.

Allowed Values

● 1 – use sort-based processing for the first subquery predicate. Other subquery predicates that do not have
the same ordering key are processed using a hash table to cache subquery results.
● 2 – use the hash table to cache results for all subquery predicates when it is legal. If available temp cache
cannot accommodate all of the subquery results, performance may be poor.
● 3 – cache one previous subquery result. Does not use SORT and HASH.
● 0 – let the optimizer choose.
● -1 – avoid using SORT. The IQ optimizer chooses HASH if it is legal.

SAP IQ SQL Reference


Database Options INTERNAL 2017
● -2 – avoid using HASH. The IQ optimizer chooses SORT or cache-one value if it is legal.
● -3 – avoid using cache-one value. The IQ optimizer chooses either HASH or SORT if it is legal.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For correlated subquery predicates, the IQ optimizer offers a choice of caching outer references and subquery
results that reduces subquery execution costs. SUBQUERY_CACHING_PREFERENCE lets you override the
optimizer’s costing decision when choosing which algorithm to use. It does not override internal rules that
determine whether an algorithm is legal within the query engine.

A setting of a non-zero value affects every subquery predicate in the query. A non-zero value cannot be used
selectively for one subquery predicate in a query.

SUBQUERY_CACHING_PREFERENCE is normally used for internal testing by experienced DBAs only. It does not
apply to IN subqueries.

Related Information

IN_SUBQUERY_PREFERENCE Option [page 1868]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2018 INTERNAL Database Options
10.6.221 SUBQUERY_FLATTENING_PERCENT Option

Allows the user to change the threshold at which the optimizer decides to transform scalar subqueries into
joins.

Allowed Values

● 0 – the optimizer cost model decides


● 1 to (232 -1) – the percentage of references at which to flatten

Default

100

Scope

● This option only applies to correlated scalar subqueries. Option can be set at the database (PUBLIC) or
user level. At the database level, the value becomes the default for any new user, but has no impact on
existing users. At the user level, overrides the PUBLIC value for that user only. No system privilege is
required to set option for self. System privilege is required to set at database level or at user level for any
user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately. If you set
SUBUERY_FLATTENING_PERCENT to a non-default value, every scalar subquery predicate in the query is
affected; this option cannot be used selectively for one scalar subquery predicate in a query.

Remarks

The SAP IQ query optimizer can convert a correlated scalar subquery into an equivalent join operation to
improve query performance. The SUBUERY_FLATTENING_PERCENT option allows the user to adjust the
threshold at which this optimization occurs.

SUBUERY_FLATTENING_PERCENT represents a percent of estimated inner distinct values to estimated outer


distinct values in a scalar subquery. As the estimated percent approaches 100 percent, the cost of evaluating
the subquery as a join is likely to be smaller than using individual index probes. The value may be set larger
than 100 percent, since the estimated inners are not guaranteed to be less than estimated outers.

SAP IQ SQL Reference


Database Options INTERNAL 2019
Related Information

SUBQUERY_FLATTENING_PREFERENCE Option [page 2020]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.222 SUBQUERY_FLATTENING_PREFERENCE Option

Allows a user to override the decisions of the optimizer when transforming (flattening) scalar or EXISTS
subqueries into joins.

Allowed Values

Value Action

-3 Avoid flattening both EXISTS and scalar subqueries to a join operation.

-2 Avoid flattening a scalar subquery to a join operation.

-1 Avoid flattening an EXISTS subquery to a join operation.

0 Allow the IQ optimizer to decide to flatten subqueries.

1 Ignore cost flattening EXIST, if possible.

2 Ignore cost flattening scalar, if possible.

3 Ignore cost of both EXISTS and scalar subquery.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately. If you set the option to a non-zero

SAP IQ SQL Reference


2020 INTERNAL Database Options
value, every subquery predicate in the query is affected; this option cannot be used selectively for one
subquery predicate in a query.

Remarks

The SAP IQ optimizer may convert a correlated scalar subquery or an EXISTS or NOT EXISTS subquery into
an equivalent join operation to improve query performance. This optimization is called subquery flattening.
SUBQUERY_FLATTENING_PREFERENCE allows you to override the costing decision of the optimizer when
choosing the algorithm to use.

Setting SUBQUERY_FLATTENING_PREFERENCE to 0 (allow the IQ optimizer to decide to flatten subqueries) is


equivalent to setting the now deprecated FLATTEN_SUBQUERIES option to ON in earlier versions of SAP IQ.

Related Information

SUBQUERY_FLATTENING_PERCENT Option [page 2019]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.223 SUBQUERY_PLACEMENT_PREFERENCE Option

Controls the placement of correlated subquery predicate operators within a query plan.

Allowed Values

● -1 – prefer the lowest possible location in the query plan, thereby placing the execution of the subquery as
early as possible within the query.
● 0 – let the optimizer choose.
● 1 – prefer the highest possible location in the query plan, thereby delaying the execution of the subquery to
as late as possible within the query.

Default

SAP IQ SQL Reference


Database Options INTERNAL 2021
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

For correlated subquery operators within a query, the IQ optimizer may have a choice of several different valid
locations within that query’s plan. SUBQUERY_PLACEMENT_PREFERENCE allows you to override the optimizer’s
cost-based decision when choosing the placement location. It does not override internal rules that determine
whether a location is valid, and in some queries, there might be only one valid choice. If you set this option to a
nonzero value, it affects every correlated subquery predicate in a query; it cannot be used to selectively modify
the placement of one subquery out of several in a query.

This option is normally used for internal testing, and only experienced DBAs should use it.

The default setting of this option is almost always appropriate. Occasionally, Technical Support might ask you
to change this value.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.224 SUPPRESS_TDS_DEBUGGING Option

Determines whether TDS debugging information appears in the server window.

Allowed Values

ON, OFF

SAP IQ SQL Reference


2022 INTERNAL Database Options
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When the server is started with the -z option, debugging information appears in the server window, including
debugging information about the TDS protocol.

SUPPRESS_TDS_DEBUGGING restricts the debugging information about TDS that appears in the server
window. When this option is set to OFF (the default), TDS debugging information appears in the server window.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.225 SWEEPER_THREADS_PERCENT Option

Specifies the percentage of SAP IQ threads used to sweep out buffer caches.

Allowed Values

1 to 40

SAP IQ SQL Reference


Database Options INTERNAL 2023
Default

10

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must shut down the
database and restart it for the change to take effect.

Remarks

SAP IQ uses a small percentage of its processing threads as sweeper threads. These sweeper threads clean out
dirty pages in the main and temp buffer caches.

In the IQ Monitor -cache report, the GDirty column shows the number of times the LRU buffer was grabbed
in a “dirty” (modified) state. If GDirty is greater than 0 for more than a brief time, you might need to increase
SWEEPER_THREADS_PERCENT or WASH_AREA_BUFFERS_PERCENT.

The default setting of this option is almost always appropriate. Occasionally, SAP Technical Support might ask
you to increase this value.

Related Information

WASH_AREA_BUFFERS_PERCENT Option [page 2069]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.226 TABLE_UDF_ROW_BLOCK_CHUNK_SIZE_KB Option

Controls the size, in kilobytes, for server-allocated row blocks. Row blocks are used by Table UDFs and TPFs.

Allowed Values

0 to 4294967295

SAP IQ SQL Reference


2024 INTERNAL Database Options
Default

128

Scope

Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the default
for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value for that
user only. No system privilege is required to set option for self. System privilege is required to set at database
level or at user level for any user other than self.

Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Description

Specifies the row block size, in kilobytes, to fetch from the server.

The server allocates row blocks when you use fetch_into to fetch rows from a table UDF, and when you use
fetch_block to fetch rows from a TPF input table.

The row block contains as many rows as will fit into the specified size. If you specify a row block size smaller
than the size required for a single row, the server allocates the size of one row.

10.6.227 TDS_EMPTY_STRING_IS_NULL Option [Database]

Controls whether empty strings are returned as NULL or a string containing one blank character for TDS
connections.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


Database Options INTERNAL 2025
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

TDS_EMPTY_STRING_IS_NULL is set to OFF by default and empty strings are returned as a string containing
one blank character for TDS connections. When this option is set to ON, empty strings are returned as NULL
strings for TDS connections. Non-TDS connections distinguish empty strings from NULL strings.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.228 TEMP_EXTRACT_APPEND Option

Specifies that any rows extracted by the data extraction facility are added to the end of an output file.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


2026 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option specifies that any rows extracted by the data extraction facility are added to the end of an output
file. You create the output file in a directory where you have WRITE/EXECUTE permissions and you set WRITE
permission on the directory and output file for the user name used to start SAP IQ. You can give permissions on
the output file to other users as appropriate. The name of the output file is specified in the
TEMP_EXTRACT_NAME1 option. The data extraction facility creates the output file, if the file does not already
exist.

TEMP_EXTRACT_APPEND is not compatible with the TEMP_EXTRACT_SIZE<> or TEMP_EXTRAC_COMPRESS


options. If you try to restrict the size of or compress the extract append output file, SAP IQ reports an error.

Related Information

TEMP_EXTRACT_NAMEn Options [page 2040]


TEMP_EXTRACT_NAMEn Options [page 2040]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.229 TEMP_EXTRACT_BINARY Option

In combination with the TEMP_EXTRACT_SWAP option, specifies the type of extraction performed by the data
extraction facility.

Allowed Values

ON, OFF

SAP IQ SQL Reference


Database Options INTERNAL 2027
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Use this option with the TEMP_EXTRACT_SWAP option to specify the type of extraction performed by the data
extraction facility.

Extraction type TEMP_EXTRACT_BINARY TEMP_EXTRACT_SWAP

binary ON OFF

binary/swap ON ON

ASCII OFF OFF

The default extraction type is ASCII.

Related Information

TEMP_EXTRACT_ESCAPE_QUOTES Option [page 2032]


TEMP_EXTRACT_SWAP Option [page 2052]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2028 INTERNAL Database Options
10.6.230 TEMP_EXTRACT_COLUMN_DELIMITER Option

Specifies the delimiter between columns in the output of the data extraction facility for an ASCII extraction.

Allowed Values

String

Default

','

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Use TEMP_EXTRACT_COLUMN_DELIMITER to specify the delimiter between columns in the output of the data
extraction facility. In the case of an ASCII extraction, the default is to separate column values with commas.
Strings are unquoted by default.

The delimiter must occupy 1 – 4 bytes, and must be valid in the collation order you are using, if you are using a
multibyte collation order. Choose a delimiter that does not occur in any of the data output strings themselves.

If you set this option to the empty string '' for ASCII extractions, the extracted data is written in fixed-width
ASCII with no column delimiter. Numeric and binary data types are right-justified on a field of <n> blanks,
where <n> is the maximum number of bytes needed for any value of that type. Character data types are left-
justified on a field of <n> blanks.

 Note

The minimum column width in a fixed-width ASCII extraction is 4 bytes to allow the string “NULL” for a
NULL value. For example, if the extracted column is CHAR(2) and TEMP_EXTRACT_COLUMN_DELIMITER is
set to the empty string '', there are two spaces after the extracted data.

SAP IQ SQL Reference


Database Options INTERNAL 2029
Related Information

TEMP_EXTRACT_QUOTE Option [page 2044]


TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
TEMP_EXTRACT_QUOTE Option [page 2044]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.231 TEMP_EXTRACT_COMPRESS Option

Writes the output file for exports in gzip format. This results in significant savings of disk space when exporting
tables.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


2030 INTERNAL Database Options
Remarks

This option cannot be used with the TEMP_EXTRACT_APPEND, TEMP_EXTRACT_SIZE, or


TEMP_EXTRACT_SIZE<n> options.

In parallel mode, the TEMP_EXTRACT_FILE_EXTENSION option must be set to gz or '' (empty string). In
serial mode, the TEMP_EXTRACT_NAME<n> option must end with .gz.

Related Information

TEMP_EXTRACT_FILE_EXTENSION Option [page 2034]


TEMP_EXTRACT_FILE_EXTENSION Option [page 2034]
TEMP_EXTRACT_GZ_COMPRESSION_LEVEL Option [page 2036]

10.6.232 TEMP_EXTRACT_DIRECTORY Option

Controls whether a user is allowed to use the data extraction facility. Also controls the directory into which
temp extract files are placed and overrides a directory path specified in the TEMP_EXTRACT_NAMEn options.

Allowed Values

String

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 2031
Remarks

If the TEMP_EXTRACT_DIRECTORY option is:

● Set to the string FORBIDDEN (case insensitive) for a user – that user is not allowed to perform data
extracts. An attempt by this user to use the data extraction facility results in the error: You do not have
permission to perform Extracts.
● Set to FORBIDDEN for the PUBLIC role – no one can run data extraction.
● Set to a valid directory path, temp extract files are placed in that directory – overriding a path specified in
the TEMP_EXTRACT_NAMEn options.
● Set to an invalid directory path – an error occurs: Files does not exist File: <invalid path>
● Blank – temporary extract files are placed in directories according to their specification in
TEMP_EXTRACT_NAMEn. If no path is specified as part of TEMP_EXTRACT_NAMEn, the extract files are by
default placed in the server startup directory.

This option provides increased security and helps control disk management by restricting the creation of large
data extraction files to the directories for which a user has write access.

For details on the data extraction facility and using the extraction options, see SAP IQ Administration: Load
Management.

Related Information

TEMP_EXTRACT_NAMEn Options [page 2040]


TEMP_EXTRACT_NAMEn Options [page 2040]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.233 TEMP_EXTRACT_ESCAPE_QUOTES Option

Specifies whether all quotes in fields containing quotes are escaped in the output of the data extraction facility
for an ASCII extraction.

Allowed Values

ON, OFF

SAP IQ SQL Reference


2032 INTERNAL Database Options
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option is ignored unless TEMP_EXTRACT_QUOTE is the default or set to the value of '"' (double quotes), and
TEMP_EXTRACT_BINARY is OFF, and either TEMP_EXTRACT_QUOTES or TEMP_EXTRACT_QUOTES_ALL is ON.

Related Information

TEMP_EXTRACT_BINARY Option [page 2027]


TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2033
10.6.234 TEMP_EXTRACT_FILE_EXTENSION Option

Sets the file name extension for the generated output file of the data parallel extraction facility. When you
specify the TEMP_EXTRACT_FILE_EXTENSION option, each file name generated becomes <prefix>
<thread_ID>_<filecount>.<file extension>.

Allowed Values

String containing a file name extension

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This filename extension is used in parallel temporary extract operations. To enable parallel extract, set
TEMP_EXTRACT_FILE_PREFIX but not TEMP_EXTRACT_NAME<n>. If you set TEMP_EXTRACT_COMPRESS, the
TEMP_EXTRACT_FILE_EXTENSION option must either be set to '' (the default value) or to 'gz'. Other file
extensions report an error.

Related Information

TEMP_EXTRACT_COMPRESS Option [page 2030]


TEMP_EXTRACT_FILE_PREFIX Option [page 2035]
TEMP_EXTRACT_COMPRESS Option [page 2030]
TEMP_EXTRACT_FILE_PREFIX Option [page 2035]

SAP IQ SQL Reference


2034 INTERNAL Database Options
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.235 TEMP_EXTRACT_FILE_PREFIX Option

Sets the prefix of file name for the generated output file of the data parallel extraction facility. <thread_ID>
starts from 1. <filecount> starts from 1 for each thread ID. The<filecount> part increments when the size
of the output file reaches the file size limit specified by the TEMP_EXTRACT_SIZE option.

Allowed Values

String containing a prefix of the output filename.

Default

<prefix><thread_ID>_<filecount>

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The TEMP_EXTRACT_APPEND option is not compatible with the parallel extraction facility. If the output files do
not already exist, parallel extraction facility creates the new files. If the output files already exist, the file
contents are overwritten.

Use the parallel data extraction facility when the data set to extract is large and you need better performance.
When the parallel extract is enabled, multiple output files could be generated depending on the number of
threads used to extract in parallel.

SAP IQ SQL Reference


Database Options INTERNAL 2035
If the TEMP_EXTRACT_DIRECTORY option is set to a valid directory path, parallel temp extract files are placed
in that directory. If TEMP_EXTRACT_DIRECTORY option is blank, then parallel temp extract files are by default
placed in the server startup directory.

To enable parallel extract, set TEMP_EXTRACT_FILE_PREFIX but not TEMP_EXTRACT_NAME1.

Example

For example, the parameters below generate files extract_file1_1.csv, extract_file2_1.csv,


extract_file3_1.csv, and extract_file4_1.csv, and set the parallel degree 4.

SET OPTION PUBLIC.Temp_Extract_File_Prefix = "extract_file";


;

SET OPTION PUBLIC.Temp_Extract_File_Extension = "csv";


;

SET OPTION PUBLIC.Temp_Extract_Max_Parallel_Degree = 4;

Related Information

TEMP_EXTRACT_FILE_EXTENSION Option [page 2034]


TEMP_EXTRACT_FILE_EXTENSION Option [page 2034]
TEMP_EXTRACT_MAX_PARALLEL_DEGREE Option [page 2039]
TEMP_EXTRACT_SIZE Option [page 2049]
TEMP_EXTRACT_MAX_PARALLEL_DEGREE Option [page 2039]
TEMP_EXTRACT_SIZE Option [page 2049]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.236 TEMP_EXTRACT_GZ_COMPRESSION_LEVEL Option

The compression level balances compression with speed when the TEMP_EXTRACT_COMPRESS option is set to
ON.

Allowed Values

1 to 9

SAP IQ SQL Reference


2036 INTERNAL Database Options
Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

A value of 1 results in the best speed, while a value of 9 results in the best compression. The default value
provides a nice compromise between speed and compression.

This option cannot be used with the TEMP_EXTRACT_APPEND, TEMP_EXTRACT_SIZE, or


TEMP_EXTRACT_SIZE<n> options.

In parallel mode, the TEMP_EXTRACT_FILE_EXTENSION option must be set to gz or '' (empty string). In
serial mode, the TEMP_EXTRACT_NAME<n> option must end with .gz.

Related Information

TEMP_EXTRACT_COMPRESS Option [page 2030]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2037
10.6.237 TEMP_EXTRACT_LENGTH_PREFIX Option

Adds a prefix field of specified length (byte) for a varchar or varbinary column in the generated output file. This
PREFIX field in the extract file holds the length of the column data.

Allowed Values

0, 1, 2, 4

Default

0 (zero)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If you do not specify TEMP_EXTRACT_LENGTH_PREFIX, or you specify 0 (the default), the data extraction
facility does not generate a prefix length field.

When you specify any other valid value for TEMP_EXTRACT_LENGTH_PREFIX, the data extraction facility uses
that specified value for the length (byte) of the prefix field that holds the actual data length, adding it before the
actual data for a varchar or varbinary column, including the length for trailing spaces and zeros in the column. If
the TEMP_EXTRACT_VARYING option is not set, however, the total length of the actual column data in the
extracted file is its declared length in a fixed-length format. For example, the data extraction facility always
generates 10 bytes for a varchar(10) column, necessary to make the file format fixed length.

Related Information

TEMP_EXTRACT_VARYING Option [page 2053]

SAP IQ SQL Reference


2038 INTERNAL Database Options
LOAD TABLE Statement [page 1549]
TEMP_EXTRACT_VARYING Option [page 2053]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.238 TEMP_EXTRACT_MAX_PARALLEL_DEGREE Option

Sets the maximum parallel degree for the data extraction facility. The
TEMP_EXTRACT_MAX_PARALLEL_DEGREE option limits the maximum number of threads that run in parallel
to extract data.

Allowed Values

Any non-negative integer.

Default

64

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

To enable parallel extract, set TEMP_EXTRACT_FILE_PREFIX but not TEMP_EXTRACT_NAME1.

SAP IQ SQL Reference


Database Options INTERNAL 2039
Related Information

TEMP_EXTRACT_FILE_PREFIX Option [page 2035]


TEMP_EXTRACT_FILE_PREFIX Option [page 2035]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.239 TEMP_EXTRACT_NAMEn Options

Specifies the names of the output files or named pipes used by the data extraction facility. There are eight
options: TEMP_EXTRACT_NAME1 through TEMP_EXTRACT_NAME8.

Allowed Values

String

Default

' ' (the empty string)

Scope

Requires the SET ANY PUBLIC OPTION system privilege to set this option for PUBLIC or for other user or role.

Description

TEMP_EXTRACT_NAME1 through TEMP_EXTRACT_NAME8 specify the names of the output files used by the data
extraction facility. You must use these options sequentially. For example, TEMP_EXTRACT_NAME3 has no effect
unless both the options TEMP_EXTRACT_NAME1 and TEMP_EXTRACT_NAME2 are already set.

The most important of these options is TEMP_EXTRACT_NAME1. If TEMP_EXTRACT_NAME1 is set to its default
setting (the empty string ''), extraction is disabled and no output is redirected. To enable extraction, set
TEMP_EXTRACT_NAME1 to a path name. Extract starts extracting into a file with that name. Choose a path
name to a file that is not otherwise in use.

SAP IQ SQL Reference


2040 INTERNAL Database Options
 Tip

Set the TEMP_EXTRACT_NAME1 option as TEMPORARY.

You can also use TEMP_EXTRACT_NAME1 to specify the name of the output file, when the
TEMP_EXTRACT_APPEND option is set ON. In this case, before you execute the SELECT statement, set WRITE
permission for the user name used to start SAP IQ (for example, sybase) on the directory or folder containing
the named file and on the named file. In append mode, the data extraction facility adds extracted rows to the
end of the file and does not overwrite the data that is already in the file. If the output file does not already exist,
the data extraction facility creates the file.

 Caution

If you choose the path name of an existing file and the TEMP_EXTRACT_APPEND option is set OFF (the
default), the file contents are overwritten. This might be what you require if the file is for a weekly report, for
example, but not if the file is one of your database files.

The options TEMP_EXTRACT_NAME2 through TEMP_EXTRACT_NAME8 can be used in addition to


TEMP_EXTRACT_NAME1 to specify the names of multiple output files.

If you are extracting to a single disk file or a single named pipe, leave the options TEMP_EXTRACT_NAME2
through TEMP_EXTRACT_NAME8 and TEMP_EXTRACT_SIZE1 through TEMP_EXTRACT_SIZE8 at their default
values.

When TEMP_EXTRACT_NAME1 is set, you cannot perform these operations:

● LOAD, DELETE, INSERT, or INSERT...LOCATION to a table that is the top table in a join
● INSERT...SELECT

Also note these restrictions on the data extraction facility:

● Extract works only with data stored in the IQ store.


● Extract does not work on system tables or cross database joins.
● Extract does not work with queries that use user-defined functions or system functions, except for the
system functions suser_id() and suser_name().
● If you run Interactive SQL with the -q (quiet mode) option and the data extraction commands are in a
command file, first set and make permanent the Interactive SQL option “Show multiple result sets.” The
output file is not created until you set this option.
To set the “Show multiple result sets” option, select Tools Options in the Interactive SQL window,
then select “Show multiple result sets” and click “Make permanent.”

The directory path specified using the TEMP_EXTRACT_NAMEn options can be overridden with the
TEMP_EXTRACT_DIRECTORY option.

Related Information

TEMP_EXTRACT_APPEND Option [page 2026]


TEMP_EXTRACT_DIRECTORY Option [page 2031]
TEMP_EXTRACT_APPEND Option [page 2026]
TEMP_EXTRACT_DIRECTORY Option [page 2031]

SAP IQ SQL Reference


Database Options INTERNAL 2041
TEMP_EXTRACT_SIZEn Options [page 2050]
TEMP_EXTRACT_SIZEn Options [page 2050]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.240 TEMP_EXTRACT_NULL_AS_EMPTY Option

Controls the representation of null values in the output of the data extraction facility for an ASCII extraction.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

TEMP_EXTRACT_NULL_AS_EMPTY controls the representation of null values in the output of the data extraction
facility for ASCII extractions. When the TEMP_EXTRACT_NULL_AS_EMPTY option is set to ON, a null value is
represented as '' (the empty string) for all data types.

The quotes shown above are not present in the extract output file. When the TEMP_EXTRACT_NULL_AS_EMPTY
option is set to OFF, the string 'NULL' is used in all cases to represent a NULL value. OFF is the default value.

SAP IQ SQL Reference


2042 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.241 TEMP_EXTRACT_NULL_AS_ZERO Option

Controls the representation of null values in the output of the data extraction facility for an ASCII extraction.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

TEMP_EXTRACT_NULL_AS_ZERO controls the representation of null values in the output of the data extraction
facility for ASCII extractions. When TEMP_EXTRACT_NULL_AS_ZERO is set to ON, a null value is represented as
follows:

● '0' – arithmetic type


● ' ' (the empty string) – the CHAR and VARCHAR character types

SAP IQ SQL Reference


Database Options INTERNAL 2043
● ' ' (the empty string) – dates
● ' ' (the empty string) – times
● ' ' (the empty string) – timestamps

The quotes shown above are not present in the extract output file. When the TEMP_EXTRACT_NULL_AS_ZERO
option is set to OFF, the string 'NULL' is used in all cases to represent a NULL value. OFF is the default value.

 Note

In SAP IQ 12.5, an ASCII extract from a CHAR or VARCHAR column in a table always returns at least four
characters to the output file. This is required if TEMP_EXTRACT_NULL_AS_ZERO is set to OFF, because SAP
IQ needs to write out the word NULL for any row in a column that has a null value. Reserving four spaces is
not required if TEMP_EXTRACT_NULL_AS_ZERO is set to ON.

In SAP IQ 12.6, if TEMP_EXTRACT_NULL_AS_ZERO is set to ON, the number of characters that an ASCII
extract writes to a file for a CHAR or VARCHAR column equals the number of characters in the column, even
if that number is less than four.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.242 TEMP_EXTRACT_QUOTE Option

Specifies the string to be used as the quote to enclose fields in the output of the data extraction facility for an
ASCII extraction, when either the TEMP_EXTRACT_QUOTES option or the TEMP_EXTRACT_QUOTES_ALL option
is set ON.

Allowed Values

String

Default

' ' (the empty string)

SAP IQ SQL Reference


2044 INTERNAL Database Options
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option specifies the string to be used as the quote to enclose fields in the output of the data extraction
facility for an ASCII extraction, if the default value is not suitable. TEMP_EXTRACT_QUOTE is used with the
TEMP_EXTRACT_QUOTES and TEMP_EXTRACT_QUOTES_ALL options. The quote string specified in the
TEMP_EXTRACT_QUOTE option has the same restrictions as the row and column delimiters. The default for this
option is the empty string, which SAP IQ converts to the single quote mark.

The string specified in the TEMP_EXTRACT_QUOTE option must occupy from 1 to a maximum of 4 bytes and
must be valid in the collation order you are using, if you are using a multibyte collation order. Be sure to choose
a string that does not occur in any of the data output strings themselves.

Related Information

TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]


TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2045
10.6.243 TEMP_EXTRACT_QUOTES Option

Specifies that string fields are enclosed in quotes in the output of the data extraction facility for an ASCII
extraction.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

This option specifies that string fields are enclosed in quotes in the output of the data extraction facility for an
ASCII extraction. The string used as the quote is specified in the TEMP_EXTRACT_QUOTE option, if the default is
not suitable.

Related Information

TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]


TEMP_EXTRACT_ESCAPE_QUOTES Option [page 2032]
TEMP_EXTRACT_QUOTE Option [page 2044]
TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]

SAP IQ SQL Reference


2046 INTERNAL Database Options
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.244 TEMP_EXTRACT_QUOTES_ALL Option

Specifies that all fields are enclosed in quotes in the output of the data extraction facility for an ASCII
extraction.

Allowed Values

ON, OFF

Default

OFF

Scope

Requires the SET ANY PUBLIC OPTION system privilege to set this option for PUBLIC or for other user or role.

Remarks

TEMP_EXTRACT_QUOTES_ALL specifies that all fields are enclosed in quotes in the output of the data
extraction facility for an ASCII extraction. The string used as the quote is specified in TEMP_EXTRACT_QUOTE, if
the default is not suitable.

Related Information

TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]


TEMP_EXTRACT_ESCAPE_QUOTES Option [page 2032]

SAP IQ SQL Reference


Database Options INTERNAL 2047
TEMP_EXTRACT_QUOTE Option [page 2044]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_ROW_DELIMITER Option [page 2048]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.245 TEMP_EXTRACT_ROW_DELIMITER Option

Specifies the delimiter between rows in the output of the data extraction facility for an ASCII extraction.

Allowed Values

String

Default

' ' (the empty string)

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


2048 INTERNAL Database Options
Remarks

TEMP_EXTRACT_ROW_DELIMITER specifies the delimiter between rows in the output of the data extraction
facility. In the case of an ASCII extraction, the default is to end the row with a newline on UNIX platforms and
with a carriage return/newline pair on Windows platforms.

The delimiter must occupy 1 to 4 bytes and must be valid in the collation order you are using, if you are using a
multibyte collation order. Choose a delimiter that does not occur in any of the data output strings. The default
for the TEMP_EXTRACT_ROW_DELIMITER option is the empty string. SAP IQ converts the empty string default
for this option to the newline on UNIX platforms and to the carriage return/newline pair on Windows platforms.

Related Information

TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]


TEMP_EXTRACT_QUOTE Option [page 2044]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
TEMP_EXTRACT_COLUMN_DELIMITER Option [page 2029]
TEMP_EXTRACT_QUOTES Option [page 2046]
TEMP_EXTRACT_QUOTES_ALL Option [page 2047]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.246 TEMP_EXTRACT_SIZE Option

Sets the maximum size (KB) of the corresponding output files generated by the parallel data extraction facility.

Allowed Values

Integer number of kilobytes (KB)

Default

SAP IQ SQL Reference


Database Options INTERNAL 2049
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The default value 0 uses a platform dependent maximum file size for one disk file.

This option is different from TEMP_EXTRACT_SIZE1 through TEMP_EXTRACT_SIZE8, which are used for the
serial data extraction facility.

To enable parallel extract, set TEMP_EXTRACT_FILE_PREFIX but not TEMP_EXTRACT_NAME1.

Related Information

TEMP_EXTRACT_FILE_PREFIX Option [page 2035]


TEMP_EXTRACT_FILE_PREFIX Option [page 2035]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.247 TEMP_EXTRACT_SIZEn Options

Specifies the maximum sizes of the corresponding output files used by the data extraction facility.

Allowed Values

There are eight options: TEMP_EXTRACT_SIZE1 through TEMP_EXTRACT_SIZE8.

SAP IQ SQL Reference


2050 INTERNAL Database Options
Device Type Size

Disk file AIX and HP-UX: 0 – 64 GB

Sun Solaris & Linux: 0 – 512 GB

Windows: 0 – 128 GB

Tape 524288 KB (0.5 GB)

 Note
Tape devices are not currently supported.

Other 9007199254740992 KB (8192 petabytes “unlimited”)

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

TEMP_EXTRACT_SIZE1 through TEMP_EXTRACT_SIZE8 are used to specify the maximum sizes of the
corresponding output files used by the data extraction facility. TEMP_EXTRACT_SIZE1 specifies the maximum
size of the output file specified by TEMP_EXTRACT_NAME1, TEMP_EXTRACT_SIZE2 specifies the maximum size
of the output file specified by TEMP_EXTRACT_NAME2, and so on.

When large file systems, such as JFS2, support file size larger than the default value, set
TEMP_EXTRACT_SIZEn to the value that the file system allows. For example, to support l TB set option:

TEMP_EXTRACT_SIZE1 = 1073741824 KB

If you are extracting to a single disk file or a single named pipe, leave the options TEMP_EXTRACT_NAME2
through TEMP_EXTRACT_NAME8 and TEMP_EXTRACT_SIZE1 through TEMP_EXTRACT_SIZE8 at their default
values.

SAP IQ SQL Reference


Database Options INTERNAL 2051
The TEMP_EXTRACT_SIZE<n> options are not compatible with TEMP_EXTRACT_APPEND. If you try to restrict
the size of the extract append output file, SAP IQ reports an error.

Related Information

TEMP_EXTRACT_NAMEn Options [page 2040]


TEMP_EXTRACT_NAMEn Options [page 2040]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.248 TEMP_EXTRACT_SWAP Option

In combination with the TEMP_EXTRACT_BINARY option, specifies the type of extraction performed by the data
extraction facility.

Allowed values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


2052 INTERNAL Database Options
Remarks

Use this option with the TEMP_EXTRACT_BINARY option to specify the type of extraction performed by the
data extraction facility.

Extraction type TEMP_EXTRACT_BINARY TEMP_EXTRACT_SWAP

binary ON OFF

binary/swap ON ON

ASCII OFF OFF

The default extraction type is ASCII.

Related Information

TEMP_EXTRACT_BINARY Option [page 2027]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.249 TEMP_EXTRACT_VARYING Option

Used in conjunction with TEMP_EXTRACT_LENGTH_PREFIX, the TEMP_EXTRACT_VARYING option outputs


varchar or varbinary column data in a variable-length format in the extracted file. The prefix field specified by
TEMP_EXTRACT_LENGTH_PREFIX option holds the length of column data.

Allowed Values

ON, OFF

Default

OFF

SAP IQ SQL Reference


Database Options INTERNAL 2053
Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

You can only use TEMP_EXTRACT_VARYING for varchar and varbinary columns in a binary mode extraction.

When you set TEMP_EXTRACT_VARYING to ON, the data field in the extracted file becomes variable length
(with a prefix field). The data field occupies only the data length in the extracted file, instead of the declared
length of the varchar or varbinary column, so that there is no trailing padding.

Use this option with TEMP_EXTRACT_LENGTH_PREFIX to indicate the data length in the extracted file; there is
no column delimiter in binary mode extractions.

Related Information

TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]


TEMP_EXTRACT_LENGTH_PREFIX Option [page 2038]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.250 TEMP_RESERVED_DBSPACE_MB Option

Controls the amount of space SAP IQ reserves in the temporary IQ store.

Allowed Values

Integer greater than or equal to 200 MB

SAP IQ SQL Reference


2054 INTERNAL Database Options
Default

200. SAP IQ actually reserves a maximum of 50% and a minimum of 1 percent of the last read-write file in
IQ_SYSTEM_TEMP

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately. The
server does not need to be restarted in order to change reserved space size.

Remarks

TEMP_RESERVED_DBSPACE_MB lets you control the amount of space SAP IQ sets aside in your temporary IQ
store for certain small but critical data structures used during release savepoint, commit, and checkpoint
operations. For a production database, set this value between 200 MB and 1 GB. The larger your IQ page size
and number of concurrent connections, the more reserved space you need.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.251 TEMP_SPACE_LIMIT_CHECK Option

Checks for catalog store temporary space on a per connection basis.

Allowed Values

ON, OFF (no limit checking occurs)

SAP IQ SQL Reference


Database Options INTERNAL 2055
Default

ON

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

When TEMP_SPACE_LIMIT_CHECK is ON, the database server checks the amount of catalog store temporary
file space that a connection uses. If a connection requests more than its quota of temporary file space when
this option is set to OFF, a fatal error can occur. When this option is set to ON, if a connection requests more
than its quota of temporary file space, the request fails and the error “Temporary space limit exceeded”
is returned.

Two factors are used to determine the temporary file quota for a connection: the maximum size of the
temporary file, and the number of active database connections. The maximum size of the temporary file is the
sum of the current size of the file and the amount of disk space available on the partition containing the file.
When limit checking is turned on, the server checks a connection for exceeding its quota when the temporary
file has grown to 80% or more of its maximum size, and the connection requests more temporary file space.
Once this happens, any connection fails that uses more than the maximum temporary file space divided by the
number of active connections.

 Note

This option is unrelated to IQ temporary store space. To constrain the growth of IQ temporary space, use
the QUERY_TEMP_SPACE_LIMIT option and MAX_TEMP_SPACE_PER_CONNECTION option.

You can obtain information about the space available for the temporary file using the sa_disk_free_space
system procedure.

Example

A database is started with the temporary file on a drive with 100 MB free and no other active files on the same
drive. The available temporary file space is 100 MB. The DBA enters:

SET OPTION PUBLIC.TEMP_SPACE_LIMIT_CHECK = 'ON'

As long as the temporary file stays below 80 MB, the server behaves as it did before. Once the file reaches 80
MB, the new behavior might occur. Assume that with 10 queries running, the temporary file needs to grow.
When the server finds that one query is using more than 8 MB of temporary file space that query fails.

SAP IQ SQL Reference


2056 INTERNAL Database Options
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.252 TEXT_DELETE_METHOD Option

Specifies the algorithm used during a delete in a TEXT index.

Allowed Values

0 to 2

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

Users must be licensed for the Unstructured Data Analytics Option to use TEXT indexes.

SAP IQ SQL Reference


Database Options INTERNAL 2057
Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.253 TIME_FORMAT Option

Sets the format used for times retrieved from the database.

Allowed values

A string composed of the symbols HH, NN, MM, SS, separated by colons.

Default

● 'HH:NN:SS.SSS'
● For Open Client and JDBC connections, the default is also set to HH:NN:SS.SSS.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

The format is a string using these symbols:

● hh – two-digit hours (24 hour clock).


● nn – two-digit minutes.
● mm – two-digit minutes if following a colon (as in 'hh:mm').

SAP IQ SQL Reference


2058 INTERNAL Database Options
● ss[.s...s] – two-digit seconds plus optional fraction.

Each symbol is substituted with the appropriate data for the date being formatted. Any format symbol that
represents character rather than digit output can be in uppercase, which causes the substituted characters
also to be in uppercase. For numbers, using mixed case in the format string suppresses leading zeros.

Multibyte characters are not supported in format strings. Only single-byte characters are allowed, even when
the collation order of the database is a multibyte collation order like 932JPN.

Related Information

DATE_FORMAT Option [page 1804]


RETURN_DATE_TIME_AS_STRING Option [page 1982]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.254 TIMESTAMP_FORMAT Option

Sets the format used for timestamps retrieved from the database.

Allowed Values

A string composed of the symbols listed below.

Default

'YYYY-MM-DD HH:NN:SS.SSS'

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

SAP IQ SQL Reference


Database Options INTERNAL 2059
Remarks

The format is a string using these symbols:

Symbol Description

yy 2-digit year.

yyyy 4-digit year.

mm 2-digit month, or two digit minutes if following a colon (as in 'hh:mm').

mmm 3-character short form for name of the month of year.

mmmm[m...] Character long form for month name—as many characters as there are m's, until the number of
m’s specified exceeds the number of characters in the month’s name.

dd 2-digit day of month.

ddd 3-character short form for name of the day of week.

dddd[d...] Character long form for day name—as many characters as there are d's, until the number of d’s
specified exceeds the number of characters in the day’s name.

hh 2-digit hours.

nn 2-digit minutes.

ss.SSS Seconds (ss) and fractions of a second (SSS), up to six decimal places. Not all platforms support
timestamps to a precision of six places.

aa a.m. or p.m. (12-hour clock).

pp p.m. if needed (12-hour clock.)

Each symbol is substituted with the appropriate data for the date being formatted. Any format symbol that
represents character rather than digit output can be in uppercase, which causes the substituted characters
also to be in uppercase. For numbers, using mixed case in the format string suppresses leading zeros.

Multibyte characters are not supported in format strings. Only single-byte characters are allowed, even when
the collation order of the database is a multibyte collation order like 932JPN.

Related Information

DATE_FORMAT Option [page 1804]


RETURN_DATE_TIME_AS_STRING Option [page 1982]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2060 INTERNAL Database Options
10.6.255 TOP_NSORT_CUTOFF_PAGES Option

Sets the result size threshold for TOP N algorithm selection.

Allowed Values

1 to 1000

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

TOP_NSORT_CUTOFF_PAGES sets the threshold, measured in pages, where evaluation of a query that contains
both a TOP clause and ORDER BY clause switches algorithms from ordered list-based processing to sort-based
processing. Ordered list processing performs better in cases where the TOP N value is smaller than the number
of result rows. Sort-based processing performs better for large TOP N values.

In some cases, increasing TOP_NSORT_CUTOFF_PAGES can improve performance by avoiding sort-based


processing.

Related Information

SELECT Statement [page 1659]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


Database Options INTERNAL 2061
GRANT System Privilege Statement [page 1511]

10.6.256 TRIM_PARTIAL_MBC Option

Allows automatic trimming of partial multibyte character data.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. Takes effect immediately.

Remarks

Provides consistent loading of data for collations that contain both single-byte and multibyte characters. When
TRIM_PARTIAL_MBC is ON:

● A partial multibyte character is replaced with a blank when loading into a CHAR column.
● A partial multibyte character is truncated when loading into a VARCHAR column.

When TRIM_PARTIAL_MBC is OFF, normal CONVERSION_ERROR semantics are in effect.

Related Information

CONVERSION_ERROR Option [TSQL] [page 1787]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]

SAP IQ SQL Reference


2062 INTERNAL Database Options
GRANT System Privilege Statement [page 1511]

10.6.257 TRUSTED_CERTIFICATES_FILE Option

Specifies the trust relationship for outbound Transport Layer Security (TLS) connections made by LDAP User
Authentication, INC, DAS INC, and MIPC connections.

Allowed Values

A valid network path to the location of a TXT file containing the list of trusted certificate authorities that sign
server certificates.

Default

NULL, meaning that no outbound TLS connection can be started because there are no trusted certificate
authorities.

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SECURITY OPTION system privilege to set this option. Takes effect immediately.

Remarks

This option identifies the path to the location of the list of trusted certificate authorities. The list must be stored
in a TXT file. The file may be shared in a location in a Windows environment on the local drive to be used by all
SAP applications on that machine.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2063
10.6.258 TSQL_VARIABLES Option [TSQL]

Controls whether the @ sign can be used as a prefix for Embedded SQL host variable names.

Allowed Values

ON, OFF

Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When TSQL_VARIABLES is set to ON, you can use the @ sign instead of the colon as a prefix for host variable
names in Embedded SQL. This is implemented primarily for the Open Server Gateway.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2064 INTERNAL Database Options
10.6.259 USER_RESOURCE_RESERVATION Option

Adjusts memory use for the number of current users.

Allowed Values

Integer

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

SAP IQ tracks the number of open cursors and allocates memory accordingly. In certain circumstances, you
can use this option to adjust the minimum number of current cursors that SAP IQ thinks is currently using the
product, and allocate memory from the temporary cache more sparingly.

Set this option only after careful analysis shows it is actually required. If you need to set this parameter, contact
Technical Support with details.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


Database Options INTERNAL 2065
10.6.260 VERIFY_PASSWORD_FUNCTION Option

Specifies a user-supplied authentication function that can be used to implement password rules.

Allowed Values

String

Default

'' (the empty string). No function is called when a password is set.

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY SECURITY OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

When the VERIFY_PASSWORD_FUNCTION option value is set to a valid string, the statement GRANT CONNECT
TO <user_id> IDENTIFIED BY <password> calls the function specified by the option value.

The option value requires the form <owner.function_name> to prevent users from overriding the function.

The function takes two parameters:

● <user_name> VARCHAR(128)
● <new_pwd> VARCHAR(255)

The return value type is VARCHAR(255).

If VERIFY_PASSWORD_FUNCTION is set, you cannot specify more than one user_id and password with the
GRANT CONNECT statement.

SAP IQ SQL Reference


2066 INTERNAL Database Options
Example

The following sample code defines a table and a function and sets some login policy options. Together they
implement advanced password rules that include requiring certain types of characters in the password,
disallowing password reuse, and expiring passwords. The function is called by the database server with the
VERIFY_PASSWORD_FUNCTION option when a user ID is created or a password is changed. The application can
call the procedure specified by the POST_LOGIN_PROCEDURE option to report that the password should be
changed before it expires.

-- THIS EXAMPLE ONLY WORKS WITH A SINGLE BYTE COLLATION DATABASE.


-- The example checks for alpha-numeric characters in the password.
-- To allow or check for other characters, such as "*" or "%", customize the
example.
--
-- Only the DBA should have privileges on this table.
CREATE TABLE DBA.t_pwd_history(
pk INT DEFAULT AUTOINCREMENT PRIMARY KEY,
user_name CHAR(128), -- the user whose password is set
pwd_hash CHAR(32) ); -- hash of password value to detect
-- duplicate passwords
-- called whenever a non-NULL password is set
-- to verify the password conforms to password rules
CREATE FUNCTION DBA.f_verify_pwd( uid VARCHAR(128),
new_pwd VARCHAR(255) )
RETURNS VARCHAR(255)
BEGIN
-- a table with one row per character in new_pwd
DECLARE local temporary table pwd_chars(
pos INT PRIMARY KEY, -- index of c in new_pwd
c CHAR( 1 ) ); -- USE BYTE-LENGTH SEMANTICS

-- new_pwd with non-alpha characters removed


DECLARE pwd_alpha_only CHAR(255);
DECLARE num_lower_chars INT;
-- enforce minimum length (can also be done with
-- min_password_length option)
IF length( new_pwd ) < 6 THEN
RETURN 'password must be at least 6 characters long';
END IF;
-- break new_pwd into one row per character
INSERT INTO pwd_chars SELECT row_num, substr( new_pwd, row_num, 1 )
FROM dbo.RowGenerator
WHERE row_num <= length( new_pwd );
-- copy of new_pwd containing alpha-only characters
SELECT list( c, '' ORDER BY pos ) INTO pwd_alpha_only
FROM pwd_chars WHERE c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z';
-- number of lowercase characters IN new_pwd
SELECT count(*) INTO num_lower_chars
FROM pwd_chars WHERE CAST( c AS BINARY ) BETWEEN 'a' AND 'z';
-- enforce rules based on characters contained in new_pwd
IF ( SELECT count(*) FROM pwd_chars WHERE c BETWEEN '0' AND '9' )
< 1 THEN
RETURN 'password must contain at least one numeric digit';
ELSEIF length( pwd_alpha_only ) < 2 THEN
RETURN 'password must contain at least two letters';
ELSEIF num_lower_chars = 0
OR length( pwd_alpha_only ) - num_lower_chars = 0 THEN
RETURN 'password must contain both upper- and lowercase characters';
END IF;
-- not the same as any user name
-- (this could be modified to check against a disallowed words table)
IF EXISTS( SELECT * FROM SYS.SYSUSER
WHERE lower( user_name ) IN ( lower( pwd_alpha_only ),
lower( new_pwd ) ) ) THEN

SAP IQ SQL Reference


Database Options INTERNAL 2067
RETURN 'password or only alphabetic characters in password ' ||
'must not match any user name';
END IF;
-- not the same as any previous password for this user
IF EXISTS( SELECT * FROM t_pwd_history
WHERE user_name = uid
AND pwd_hash = hash( uid || new_pwd, 'md5' ) ) THEN
RETURN 'previous passwords cannot be reused';
END IF;
-- save the new password
INSERT INTO t_pwd_history( user_name, pwd_hash )
VALUES( uid, hash( uid || new_pwd, 'md5' ) );
RETURN( NULL );
END;
ALTER FUNCTION DBA.f_verify_pwd SET HIDDEN;
GRANT EXECUTE ON DBA.f_verify_pwd TO PUBLIC;
SET OPTION PUBLIC.verify_password_function = 'DBA.f_verify_pwd';
-- All passwords expire in 180 days. Expired passwords can be changed
-- by the user using the NewPassword connection parameter.
ALTER LOGIN POLICY DEFAULT password_life_time = 180;
-- If an application calls the procedure specified by the
-- post_login_procedure option, then the procedure can be used to
-- warn the user that their password is about to expire. In particular,
-- Interactive SQL calls the post_login_procedure.
ALTER LOGIN POLICY DEFAULT password_grace_time = 30;
-- Five consecutive failed login attempts results in a non-DBA
-- user ID being locked.
ALTER LOGIN POLICY DEFAULT max_failed_login_attempts = 5;

To turn the option off, set it to the empty string:

SET OPTION PUBLIC.VERIFY_PASSWORD_FUNCTION = ''

Related Information

ALTER FUNCTION Statement [page 1144]


GRANT CONNECT Privilege Statement [page 1496]
Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.261 WAIT_FOR_COMMIT Option

Determines when foreign key integrity is checked as data is manipulated.

Allowed Values

ON, OFF

SAP IQ SQL Reference


2068 INTERNAL Database Options
Default

OFF

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

If this option is set to ON, the database does not check foreign key integrity until the next COMMIT statement.
Otherwise, all foreign keys not created with the CHECK ON COMMIT option are checked as they are inserted,
updated, or deleted.

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

10.6.262 WASH_AREA_BUFFERS_PERCENT Option

Specifies the percentage of the buffer caches above the wash marker.

Allowed Values

1 to 100

SAP IQ SQL Reference


Database Options INTERNAL 2069
Default

20

Scope

● Option can be set at the database (PUBLIC) level only.


● Requires the SET ANY SYSTEM OPTION system privilege to set this option. You must shut down the
database and restart it for the change to take effect.

Remarks

SAP IQ buffer caches are organized as a long MRU/LRU chain. The area above the wash marker is used to
sweep out (that is, write) dirty pages to disk.

In the IQ Monitor -cache report, the Gdirty column shows the number of times the LRU buffer was grabbed
in a “dirty” (modified) state. If GDirty is greater than 0 for more than a brief time, you might need to increase
SWEEPER_THREADS_PERCENT or WASH_AREA_BUFFERS_PERCENT.

 Note

Before changing this option, check the value of the CACHE_AFFINITY_PERCENT option.
WASH_AREA_BUFFERS_PERCENT affects the LRU side of the buffer cache and CACHE_AFFINITY_PERCENT
affects the MRU side. The total of these two values cannot exceed 100 percent.

The default setting of this option is almost always appropriate. Occasionally, SAP Technical Support might ask
you to increase this value.

Related Information

SWEEPER_THREADS_PERCENT Option [page 2023]


Set a Database Option [page 1727]
SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2070 INTERNAL Database Options
10.6.263 WD_DELETE_METHOD Option

Specifies the algorithm used during a delete in a WD index.

Allowed Values

● 0 – the delete method is selected by the cost model. The cost model only selects either the mid or large
method for deletion.
● 1 – forces the small method for deletion. Small method is useful when the number of rows being deleted is
a very small percentage of the total number of rows in the table. Small delete can randomly access the
index, causing cache thrashing with large data sets.
● 2 – forces the large method for deletion. This algorithm scans the entire index searching for rows to delete.
The large method is useful when the number of rows being deleted is a high percentage of the total number
of rows in the table.
● 3 – forces the mid method for deletion. Mid method is a variation of the small method that accesses the
index in order and is generally faster than the small method.

Default

Scope

● Option can be set at the database (PUBLIC) or user level. At the database level, the value becomes the
default for any new user, but has no impact on existing users. At the user level, overrides the PUBLIC value
for that user only. No system privilege is required to set option for self. System privilege is required to set at
database level or at user level for any user other than self.
● Requires the SET ANY PUBLIC OPTION system privilege to set this option. Can be set temporary for an
individual connection or for the PUBLIC role. Takes effect immediately.

Remarks

WD_DELETE_METHOD specifies the algorithm used during a delete operation in a WD index. When this option is
not set or is set to 0, the delete method is selected by the cost model. The cost model considers the CPU
related costs as well as I/O related costs in selecting the appropriate delete algorithm. The cost model takes
into account:

● Rows deleted
● Index size

SAP IQ SQL Reference


Database Options INTERNAL 2071
● Width of index data type
● Cardinality of index data
● Available temporary cache
● Machine related I/O and CPU characteristics
● Available CPUs and threads

Example

This example forces the large method for deletion from a WD index:

SET TEMPORARY OPTION WD_DELETE_METHOD = 2

Related Information

Set a Database Option [page 1727]


SET OPTION Statement [page 1677]
REVOKE System Privilege Statement [page 1635]
GRANT System Privilege Statement [page 1511]

SAP IQ SQL Reference


2072 INTERNAL Database Options
Important Disclaimers and Legal Information

Hyperlinks
Some links are classified by an icon and/or a mouseover text. These links provide additional information.
About the icons:

● Links with the icon : You are entering a Web site that is not hosted by SAP. By using such links, you agree (unless expressly stated otherwise in your
agreements with SAP) to this:

● The content of the linked-to site is not SAP documentation. You may not infer any product claims against SAP based on this information.
● SAP does not agree or disagree with the content on the linked-to site, nor does SAP warrant the availability and correctness. SAP shall not be liable for any
damages caused by the use of such content unless damages have been caused by SAP's gross negligence or willful misconduct.

● Links with the icon : You are leaving the documentation for that particular SAP product or service and are entering a SAP-hosted Web site. By using such
links, you agree that (unless expressly stated otherwise in your agreements with SAP) you may not infer any product claims against SAP based on this
information.

Beta and Other Experimental Features


Experimental features are not part of the officially delivered scope that SAP guarantees for future releases. This means that experimental features may be changed by
SAP at any time for any reason without notice. Experimental features are not for productive use. You may not demonstrate, test, examine, evaluate or otherwise use
the experimental features in a live operating environment or with data that has not been sufficiently backed up.
The purpose of experimental features is to get feedback early on, allowing customers and partners to influence the future product accordingly. By providing your
feedback (e.g. in the SAP Community), you accept that intellectual property rights of the contributions or derivative works shall remain the exclusive property of SAP.

Example Code
Any software coding and/or code snippets are examples. They are not for productive use. The example code is only intended to better explain and visualize the syntax
and phrasing rules. SAP does not warrant the correctness and completeness of the example code. SAP shall not be liable for errors or damages caused by the use of
example code unless damages have been caused by SAP's gross negligence or willful misconduct.

Gender-Related Language
We try not to use gender-specific word forms and formulations. As appropriate for context and readability, SAP may use masculine word forms to refer to all genders.

SAP IQ SQL Reference


Important Disclaimers and Legal Information INTERNAL 2073
www.sap.com/contactsap

© 2018 SAP SE or an SAP affiliate company. All rights reserved.

No part of this publication may be reproduced or transmitted in any form


or for any purpose without the express permission of SAP SE or an SAP
affiliate company. The information contained herein may be changed
without prior notice.

Some software products marketed by SAP SE and its distributors


contain proprietary software components of other software vendors.
National product specifications may vary.

These materials are provided by SAP SE or an SAP affiliate company for


informational purposes only, without representation or warranty of any
kind, and SAP or its affiliated companies shall not be liable for errors or
omissions with respect to the materials. The only warranties for SAP or
SAP affiliate company products and services are those that are set forth
in the express warranty statements accompanying such products and
services, if any. Nothing herein should be construed as constituting an
additional warranty.

SAP and other SAP products and services mentioned herein as well as
their respective logos are trademarks or registered trademarks of SAP
SE (or an SAP affiliate company) in Germany and other countries. All
other product and service names mentioned are the trademarks of their
respective companies.

Please see https://www.sap.com/about/legal/trademark.html for


additional trademark information and notices.

THE BEST RUN

You might also like