HP NonStop SQL/MX Reference Manual Abstract This manual describes the syntax of SQL language elements—data types, expressions, functions, identifiers, literals, and predicates—and SQL statements of HP NonStop™ SQL/MX, the NonStop relational database management system based on ANSI SQL:1999. The manual also includes embedded SQL statements and MXCI commands. Product Version NonStop SQL/MX Releases 2.0, 2.1 and 2.2 (SPR identifier for SQL/MX Release 2.2: H22^ACF.
Document History Part Number Product Version Published 523725-002 NonStop SQL/MX Release 2.0 August 2004 523725-003 NonStop SQL/MX Releases 2.0 and 2.1 June 2005 540440-001 NonStop SQL/MX February 2006 540440-002 NonStop SQL/MX May 2006 540440-003 NonStop SQL/MX Release 2.
HP NonStop SQL/MX Reference Manual Index Figures What’s New in This Manual xxxi Manual Information xxxi New and Changed Information Tables xxxii About This Manual xxxv Audience xxxv Organization xxxv Related Documentation xxxvii Notation Conventions xl 1.
1. Introduction (continued) Contents 1.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
Contents 3. Embedded-Only SQL/MX Statements (continued) 3. Embedded-Only SQL/MX Statements (continued) C Examples of BEGIN DECLARE SECTION 3-9 C++ Examples of BEGIN DECLARE SECTION 3-9 COBOL Examples of BEGIN DECLARE SECTION 3-10 CLOSE Statement 3-11 Considerations for CLOSE 3-11 C Examples of CLOSE 3-12 COBOL Examples of CLOSE 3-13 Compound (BEGIN...
Contents 3. Embedded-Only SQL/MX Statements (continued) 3.
3. Embedded-Only SQL/MX Statements (continued) Contents 3.
4. MXCI Commands (continued) Contents 4.
4. MXCI Commands (continued) Contents 4.
4. MXCI Commands (continued) Contents 4. MXCI Commands (continued) Examples of SHOWSHAPE 4-89 5.
5. SQL/MX Utilities (continued) Contents 5.
Contents 6. SQL/MX Language Elements (continued) 6.
6. SQL/MX Language Elements (continued) Contents 6.
7. SQL/MX Clauses Contents 7.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
9. SQL/MX Functions and Expressions (continued) Contents 9.
10. Metadata Tables (continued) Contents 10.
10. Metadata Tables (continued) Contents 10.
A. Quick Reference Contents A. Quick Reference A B C D E F G H I L M O P R S T U V W A-1 A-1 A-1 A-2 A-2 A-3 A-3 A-3 A-3 A-3 A-4 A-4 A-4 A-4 A-4 A-5 A-5 A-5 A-5 B. Reserved Words Reserved SQL/MX and SQL/MP Identifiers SQL/MP Identifiers to Avoid B-5 B-1 C. Limits D.
D. Sample Database (continued) Contents D. Sample Database (continued) SUPPLIER Table D-10 PARTSUPP Table D-11 PARTLOC Table D-13 E. Standard SQL and SQL/MX ANSI SQL Standards E-1 ISO Standards E-2 SQL/MX Compliance E-2 SQL/MX Extensions to Standard SQL Character Set Support E-7 E-6 Index Figures Figure D-1. Sample Database Tables D-2 Tables Table 1-1. Table 1-2. Table 1-3. Table 1-4. Table 1-5. Table 3-1. Table 3-2. Table 3-3. Table 3-4. Table 3-5. Table 6-1. Table 6-2. Table 9-1. Table 9-2.
Contents HP NonStop SQL/MX Reference Manual—540440-003 xxx
What’s New in This Manual Manual Information HP NonStop SQL/MX Reference Manual Abstract This manual describes the syntax of SQL language elements—data types, expressions, functions, identifiers, literals, and predicates—and SQL statements of HP NonStop™ SQL/MX, the NonStop relational database management system based on ANSI SQL:1999. The manual also includes embedded SQL statements and MXCI commands. Product Version NonStop SQL/MX Releases 2.0, 2.1 and 2.2 (SPR identifier for SQL/MX Release 2.2: H22^ACF.
New and Changed Information What’s New in This Manual New and Changed Information Changes to the H06.08 manual Section 1 New or Changed Information MXCI Commands • • • 2 Metadata Tables Updated the MXCI Command on page 4-40. Added an example for MXCI under Examples of MXCI Command on page 4-40. Updated the current Defaults for the SHOWCONTROL command on page 4-65. Updated the SORT_MAX_HEAP_SIZE_MB attribute under: • • Default Attributes on page 10-39.
Changes to the H06.05 Manual What’s New in This Manual Changes to the H06.05 Manual Section New or Changed Information 1 Introduction Updated information in SKIP CONFLICT on page 1-8. 2 SQL/MX Statements Added new Examples of CREATE TRIGGER on page 2-101. Changed information on rowsets in DELETE Statement on page 2-109 and UPDATE Statement on page 2-226. Updated UPDATE STATISTICS Statement on page 2-239. 3 Embedded-Only SQL/MX Statements Updated ALLOCATE CURSOR Statement on page 3-3.
What’s New in This Manual Changes to the H06.
About This Manual This manual describes the syntax of SQL language elements—data types, expressions, functions, identifiers, literals, and predicates—and SQL statements of NonStop SQL/MX, the NonStop relational database management system based on ANSI SQL:1999. The manual also includes embedded SQL statements and MXCI commands. Note. In this manual, SQL language elements, statements, and clauses within statements that are extensions to the ANSI SQL:1999 standard are noted as SQL/MX extensions.
Organization About This Manual Section Description Section 8, SQL/MX File Attributes Describes SQL/MX file attributes. Section 9, SQL/MX Functions and Expressions Describes specific functions and expressions that you can use in SQL/MX statements. Section 10, Metadata Tables Describes the user metadata tables in NonStop SQL/MX, including system defaults. Appendix A, Quick Reference Is a quick reference to commands, statements, and utilities.
Related Documentation About This Manual Related Documentation This manual is part of the HP NonStop SQL/MX library of manuals, which includes: Introductory Guides SQL/MX Comparison Guide for SQL/MP Users SQL/MX Quick Start Reference Manuals SQL/MX Reference Manual SQL/MX Messages Manual Installation Guides SQL/MX Installation and Management Guide NSM/web Installation Guide Connectivity Manuals SQL/MX Connectivity Service Manual Migration Guides SQL/MX Database and Application Migration Guide
Related Documentation About This Manual Introductory Guides SQL/MX Comparison Guide for SQL/MP Users Describes SQL differences between NonStop SQL/MP and NonStop SQL/MX. SQL/MX Quick Start Describes basic techniques for using SQL in the SQL/MX conversational interface (MXCI). Includes information about installing the sample database. Reference Manuals SQL/MX Reference Manual Describes the syntax of SQL/MX statements, MXCI commands, functions, and other SQL/MX language elements.
Related Documentation About This Manual Data Management Guides SQL/MX Data Mining Guide Describes the SQL/MX data structures and operations to carry out the knowledge-discovery process. SQL/MX Report Writer Guide Describes how to produce formatted reports using data from an SQL/MX database. DataLoader/MX Reference Manual Describes the features and functions of the DataLoader/MX product, a tool to load SQL/MX databases.
Notation Conventions About This Manual These manuals are part of the SQL/MP library of manuals and are essential references. For more information about SQL/MP Data Definition Language (DDL) and SQL/MP installation and management: Related SQL/MP Manuals SQL/MP Reference Manual Describes the SQL/MP language elements, expressions, predicates, functions, and statements. SQL/MP Installation and Management Guide Describes how to plan, install, create, and manage an SQL/MP database.
General Syntax Notation About This Manual UPPERCASE LETTERS. Uppercase letters indicate keywords and reserved words. Enter these items exactly as shown. Items not enclosed in brackets are required. For example: MAXATTACH lowercase italic letters. Lowercase italic letters indicate variable items that you supply. Items not enclosed in brackets are required. For example: file-name computer type. Computer type letters within text indicate C and Open System Services (OSS) keywords and reserved words.
General Syntax Notation About This Manual … Ellipsis. An ellipsis immediately following a pair of brackets or braces indicates that you can repeat the enclosed sequence of syntax items any number of times. For example: M address [ , new-value ]… [ - ] {0|1|2|3|4|5|6|7|8|9}… An ellipsis immediately following a single syntax item indicates that you can repeat that syntax item any number of times. For example: "s-char…" Punctuation.
Change Bar Notation About This Manual Change Bar Notation Change bars are used to indicate substantive differences between this manual and its preceding version. Change bars are vertical rules placed in the right margin of changed portions of text, figures, tables, examples, and so on. Change bars highlight new or revised information. For example: The message types specified in the REPORT clause are different in the COBOL85 environment and the Common Run-Time Environment (CRE).
Change Bar Notation About This Manual HP NonStop SQL/MX Reference Manual—540440-003 xliv
1 Introduction NonStop SQL/MX allows you to use SQL/MX DML statements, which comply closely to ANSI SQL:1999, to access SQL/MP and SQL/MX databases.
MXCI SQL/MX Conversational Interface Introduction User metadata tables, such as the SYSTEM_DEFAULTS table, histogram tables, and other tables, contain SQL/MX metadata that the user rather than the system maintains. For more information, see Section 10, Metadata Tables. MXCI SQL/MX Conversational Interface MXCI, the SQL/MX conversational interface, is useful for running ad hoc queries and for comparing the relative efficiency of various queries.
Session Attributes Introduction Session Attributes Within an MXCI session, the tasks you perform are affected by these attributes of the session: Parameters Parameter values set by the SET PARAM command to substitute for parameter names when a statement executes Prepared Statements Statements compiled for execution later in the session Transactions Transaction modes set by the SET TRANSACTION statement for the next transaction in the session NAMETYPE value Attribute value ANSI or NSK that determine
SQL Comments Introduction SQL Comments You can include comments in MXCI input lines. Comments are useful for describing a statement or command. You can also use comments to disable specific statements or commands without removing them from the source code, such as for debugging purposes. To indicate that an MXCI line is a comment, precede the comment with two hyphens (--): -- comment-text All text between two hyphens and the end of the physical line is a comment.
Transactions in MXCI Introduction Transactions in MXCI A transaction can be user-defined or system-defined. If you attempt to exit an MXCI session when either type of transaction is active, MXCI prompts you to specify whether to commit or roll back the work of the transaction as follows: There is an active transaction.
The Super ID Introduction The PUBLIC identifier specifies all users in the node at present and future times and can be used in the GRANT and REVOKE statements. SYSTEM cannot be specified in GRANT and REVOKE statements. The Super ID In SQL:1999, the creator of an object is the owner of the object. In addition, NonStop SQL/MX enables the super ID, corresponding to Guardian user-id (255,255), to act as the owner of any object on a given node. The super ID can create objects in a schema owned by any user.
Data Consistency and Access Options Introduction Data Consistency and Access Options Access options for DML statements affect the consistency of the data that your query accesses. For any DML statement, you specify access options by using the FOR option ACCESS clause and, for a SELECT statement, by using this same clause, you can also specify access options for individual tables referenced in the FROM clause.
READ UNCOMMITTED Introduction READ UNCOMMITTED This option enables you to access locked data. READ UNCOMMITTED is not available for DML statements that modify the database. It is available only for a SELECT statement. READ UNCOMMITTED provides the lowest level of data consistency.
STABLE Introduction STABLE For nonaudited tables, access becomes READ COMMITTED. This option locks all data accessed through the DML statement but releases locks on unmodified data as soon as possible, which enables concurrent use of the database. STABLE access locks modified data in audited tables until the end of the transaction. STABLE is not available for DML statements that modify the database. It is available only for a SELECT statement.
Database Integrity and Locking Introduction Database Integrity and Locking To protect the integrity of the database, NonStop SQL/MX provides locks on data. For example, NonStop SQL/MX locks a row when an executing process (either MXCI or a host program) accesses a row to modify it. The lock ensures that no other process simultaneously modifies the same row. Default locking normally protects data but reduces concurrency.
Lock Mode Introduction You can prevent this by setting the TABLELOCK default to OFF. However, if the number of rows locked reaches the value of MaxLocksPerTCB, that transaction will not be able to obtain any more locks, and may be aborted. Depending on the operation, some updates must be backed out which can seriously affect the application's performance.
Transaction Management Introduction • A process can hold a lock over the duration of one (or more) transactions, or the process can release the lock before the transaction completes. A process releases the locks it holds by issuing statements that affect the locks. Stopping or abnormal termination of a process frees any locks the process holds on nonaudited tables.
Statement Atomicity Introduction • • • • • Rules for DML Statements on page 1-15 Effect of AUTOCOMMIT Option on page 1-15 Concurrency on page 1-15 Transaction Access Modes on page 1-21 Transaction Isolation Levels on page 1-21 Statement Atomicity To maintain database consistency, transactions must be controlled so that they either complete successfully or are aborted. SQL/MX Release 1.8 automatically aborted transactions if an error occurred while performing an SQL statement. SQL/MX Release 2.
User-Defined and System-Defined Transactions Introduction When NonStop SQL/MX attempts to insert, update, or delete multiple rows, it uses savepoints and if it encounters an error during the operation it issues a warning, rolls back that statement, and continues. For more information on the UPD_ABORT_ON_ERROR default, see Statement Atomicity on page 10-64. If the default INSERT_VSBB is set to USER, NonStop SQL/MX will not use statement atomicity.
Rules for DML Statements Introduction Rules for DML Statements • • DML statements executing on audited tables, views of audited tables, and mixed views must be performed within a transaction, except when reading data with READ UNCOMMITED ACCESS. If deadlock occurs, the DML statement is canceled, but the transaction continues. Audited and Nonaudited Tables The TMF product works only on audited tables, so a transaction does not protect operations on nonaudited tables.
Concurrency Introduction These tables describe interactions between SQL/MX operations: Table 1-1 on page 1-16 compares operations with access modes and lists DDL and Utility operations you can start while DML operations are in progress. Table 1-1.
Concurrency Introduction Table 1-2. Concurrent DDL/Utility and DML Operations DML Operation in Progress DDL Operations You Can Start SELECT UNCOMMITTED SELECT SHARE SELECT EXCLUSIVE UPDATE/ INSERT/ DELETE REVOKE Allowed* Allowed Waits Waits UPDATE STATISTICS Allowed Allowed Allowed Allowed** * DDL operation aborts the DML operation ** Allowed except during commit phase *** There are some exceptions. Dropping a partition from a hash partitioned table or index requires exclusive access.
Concurrency Introduction Table 1-4 describes the effect of various DDL and utility operations on table timestamps: Table 1-4.
Concurrency Introduction If you restore with PARTONLY (only one or more partitions are restored) or if you restore the entire partition (that is, the partition did not exist in the target table before restore), the redefinition time stamp of the table is updated. If only data is restored (the partition existed in the target table before the restore), the last open timestamp of partition data fork is updated, and the data modification timestamp of the partition data fork is updated.
Concurrency Introduction Table 1-5. Concurrency Limits on Utility Operations (page 2 of 2) Utility DML operations Other utilities Utilities that update metadata and read and potentially write user data online: MODIFY with SHARED access UPDATE STATISTICS All DML operations are allowed. Utilities that read metadata can only be performed concurrently.*** DDL operations Not allowed. * There are some exceptions. Dropping a partition from a hash partitioned table or index requires exclusive access.
Transaction Access Modes Introduction Transaction Access Modes A transaction has an access mode that is either READ ONLY or READ WRITE. You can set the access mode of a transaction by using a SET TRANSACTION statement. See SET TRANSACTION Statement on page 2-218. READ ONLY If a transaction is executing with the READ ONLY access mode, statements within the transaction can read, but cannot insert, delete, or update, data in tables.
Transaction Isolation Levels Introduction • • • Read data modified by a concurrent transaction (sometimes referred to as dirty reads) Read different committed values for the same item at different times or find that the item no longer exists (sometimes referred to as nonrepeatable reads) Read different sets of committed values satisfying the same predicate at different times (sometimes referred to as phantoms) READ COMMITTED This option allows your transaction to access only committed data.
Partition Management Introduction Partition Management You can create SQL/MX tables with multiple physical files, or partitions. Use the CREATE TABLE Statement on page 2-74 and the CREATE INDEX Statement on page 2-52 to create tables and indexes that include partitions. Use the MODIFY Utility to partition tables after they have been created. For more information, see Partitions on page 6-79 for an overview of partitions in SQL/MX and SQL/MP files.
Naming Objects Introduction The areas of support and the restrictions on access are: Naming Objects on page 1-24 To refer to SQL/MP database objects, use either four-part Guardian Physical Names, three-part Logical Names, or DEFINE Names. To accommodate the use of ANSI names, you must create Alias Mappings from ANSI names to NSK names.
Naming Objects Introduction filename is the name of a Guardian disk file or the name of an SQL/MP table, view, index, partition, collation, or program module. For more information about Guardian name resolution, see Attribute Value NSK for Guardian Names and Guardian Name Resolution on page 10-50. Logical Names To move toward full ANSI SQL:1999 compliance, NonStop SQL/MX provides support for three-part logical object names of the form: [[catalog.]schema.
Delimiting Reserved Words in Guardian Names Introduction statement with the associated Guardian physical name. DEFINE names can be created within MXCI or can be inherited from the TACL process or the OSS shell. For more information about DEFINEs, see DEFINEs on page 6-34. Delimiting Reserved Words in Guardian Names In NonStop SQL/MP, you can use reserved words in Guardian names that identify tables, views, partitions, and collations. NonStop SQL/MX has many more reserved words than NonStop SQL/MP.
Selecting or Changing Data Introduction Standard DATETIME Data Types Certain DATETIME data types map directly to the ANSI standard types—DATE, TIME, and TIMESTAMP. You can retrieve the same value as stored in an SQL/MP column with these data types or store a value with a standard type into these SQL/MP columns without truncation or extension.
Selecting or Changing Data Introduction If you attempt to select data from a FRACTION-only column, the value is returned as the CHAR data type consisting of a string of '#' characters with the same display length as the length of the column. See Selecting DATETIME Columns in SQL/MP Tables on page 6-25. Inserting or Updating Any DATETIME Column NonStop SQL/MX supports inserting into or updating any columns with the DATETIME data type in SQL/MP tables except those consisting of FRACTION only.
Selecting or Changing Data Introduction through SECOND are directly compatible with their corresponding SQL/MX INTERVAL data types. If you attempt to select data from a FRACTION-only column, the value is returned as the CHAR data type consisting of a string of '#' characters with the same display length as the length of the column. See Selecting INTERVAL Columns in SQL/MP Tables on page 6-30.
Accessing Views Introduction Accessing Views The FOR PROTECTION clause of the SQL/MP CREATE VIEW statement specifies a protection view. If you omit this clause, the view is a shorthand view. NonStop SQL/MX provides support for the access of SQL/MP protection views. A protection view is derived from a single table and has associated security values that determine who can read, write to, execute, and purge the view. Security specifically defined on the view overrides the security on the underlying table.
SQL/MP File Organizations Introduction ° Identifiers named after words that are reserved in SQL/MP stored text (see Appendix B, Reserved Words.) NonStop SQL/MX supports SQL/MP double-quoted string literals, which are treated correctly as strings and not as SQL/MX delimited identifiers, in SQL/MP stored text. NonStop SQL/MX supports SQL/MP character string literals that contain a space between the character set qualifier and character string literal, such as _KANJI 'abcd', in SQL/MP stored text.
ANSI Compliance and SQL/MX Extensions Introduction ANSI Compliance and SQL/MX Extensions NonStop SQL/MX complies most closely with Entry Level SQL as described in ANSI X3.135-1992 and ISO/IEC 9075:1992. NonStop SQL/MX also includes some features from Intermediate and Full Level ANSI/ISO SQL in addition to special SQL/MX extensions to the SQL language. Statements and SQL elements in this manual are ANSI compliant unless specified as SQL/MX extensions.
Statements That Are SQL/MX Extensions Introduction • • • • • • • • • • • • • • • • • • • • • • • • • • • • DROP PROCEDURE statement DROP SCHEMA statement DROP TABLE statement DROP TRIGGER statement DROP VIEW statement END DECLARE SECTION declaration EXEC SQL directive EXECUTE statement EXECUTE IMMEDIATE statement FETCH statement GET DESCRIPTOR statement GET DIAGNOSTICS statement GRANT statement INSERT statement OPEN statement PREPARE statement REVOKE statement ROLLBACK WORK statement SELECT statement SET
ANSI-Compliant Functions Introduction • • • • • • • • • • • • • • • • • • • • • • • • DECLARE SCHEMA statement DROP CATALOG statement DROP INDEX statement DROP SQL statement DROP SQLMP ALIAS statement IF statement GRANT EXECUTE statement INITIALIZE SQL statement INVOKE directive LOCK TABLE statement MODULE directive REGISTER CATALOG command REVOKE EXECUTE statement SAMPLE clause SEQUENCE BY clause SET (assignment) statement SET MPLOC statement SET NAMETYPE statement SET TABLE TIMEOUT statement SIGNAL SQL
SQL/MX Error Messages Introduction • • • TRIM UPPER USER All other functions are SQL/MX extensions. SQL/MX Error Messages NonStop SQL/MX reports error messages and exception conditions within the SQL/MX conversational interface, MXCI, and in the standard output of embedded SQL programs. When an error condition occurs, NonStop SQL/MX returns a message number and a brief description of the condition.
SQL/MX Error Messages Introduction HP NonStop SQL/MX Reference Manual—540440-003 1- 36
2 SQL/MX Statements This section describes the syntax and semantics of NonStop SQL/MX statements that you can run in MXCI or embed in programs written in C, C++, COBOL, or Java. For more information on which SQL/MX statements you can embed in a particular language, see the SQL/MX Programming Manual for C and COBOL.
Data Definition Language (DDL) Statements SQL/MX Statements CREATE SQLMP ALIAS Statement on page 2-70 Creates mappings from logical names to physical names for SQL/MP database objects. CREATE TABLE Statement on page 2-74 Creates a table. CREATE TRIGGER Statement on page 2-95 Creates a trigger. CREATE VIEW Statement on page 2-104 Creates a view. DROP CATALOG Statement on page 2-118 Drops an empty catalog. DROP INDEX Statement on page 2-119 Drops an index.
Data Manipulation Language (DML) Statements SQL/MX Statements REVOKE EXECUTE Statement on page 2-169 Revokes access privileges for a procedure to specified users. SET Statement on page 2-207 Controls the action of a BEFORE trigger. SIGNAL SQLSTATE Statement on page 2-222 Enables a trigger execution to raise an exception that causes both the triggered and triggering statements to fail.
Embedded-Only SQL/MX Statements SQL/MX Statements Embedded-Only SQL/MX Statements For more information on SQL/MX statements that you can use only in embedded SQL programs, see Section 3, Embedded-Only SQL/MX Statements.
Object Naming Statements SQL/MX Statements Object Naming Statements Use these statements to set the value of the NAMETYPE attribute, which determines whether the object naming is ANSI or NSK for the current session, and to specify default ANSI names for the catalog and schema or Guardian physical names for the volume and subvolume: SET CATALOG Statement on page 2-208 Sets the default ANSI catalog for unqualified schema names for the current session.
Trigger Statements SQL/MX Statements Trigger Statements Use these statements to create and manipulate triggers on SQL/MX tables: ALTER TRIGGER Statement on page 2-24 Alters a trigger. CREATE TRIGGER Statement on page 2-95 Creates a trigger. DROP TRIGGER Statement on page 2-129 Drops a trigger. SET Statement on page 2-207 Controls the action of a BEFORE trigger.
ALTER INDEX Statement SQL/MX Statements ALTER INDEX Statement Considerations for ALTER INDEX Examples of ALTER INDEX The ALTER INDEX statement modifies an SQL/MX index by changing one or more file attributes of the index. See Database Object Names on page 6-12. ALTER INDEX is an SQL/MX extension. ALTER INDEX [[catalog-name.]schema-name.]index ATTRIBUTE[S] attribute [,attribute ]...
Considerations for ALTER INDEX SQL/MX Statements Considerations for ALTER INDEX You cannot use ALTER INDEX to change a partition’s name. Authorization and Availability Requirements To alter an index, you must own its schema or be the super ID. All partitions of the index must be available when ALTER INDEX executes. The appropriate metadata tables must also be available.
Considerations for ALTER SQLMP ALIAS SQL/MX Statements If you do not specify \node, the default is the Guardian node named in the =_DEFAULTS define. Considerations for ALTER SQLMP ALIAS Usage Restrictions If the specified alias does not exist or the specified Guardian file does not exist, NonStop SQL/MX returns an error. If the ALTER SQLMP ALIAS statement specifies a physical file name that is the same as the current alias mapping, NonStop SQL/MX returns a warning.
ALTER TABLE Statement SQL/MX Statements ALTER TABLE Statement Considerations for ALTER TABLE Examples of ALTER TABLE The ALTER TABLE statement modifies an SQL/MX table by adding a column to the table, by adding or dropping a constraint on the table, or by changing one or more file attributes for the table. See Database Object Names on page 6-12.
ALTER TABLE Statement SQL/MX Statements default is: literal | NULL | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | {CURRENT_USER | USER} column-constraint is: UNIQUE | PRIMARY KEY [ASC[ENDING] | DESC[ENDING]] | CHECK (condition) | REFERENCES ref-spec table-constraint is: UNIQUE (column-list) | PRIMARY KEY (key-column-list) | CHECK (condition) | FOREIGN KEY (column-list) REFERENCES ref-spec column-list is: column-name [,column-name]...
Syntax Description of ALTER TABLE SQL/MX Statements Syntax Description of ALTER TABLE table specifies the name of the table to alter. See Database Object Names on page 6-12. ADD [COLUMN] column-definition adds a column to table. The clauses for the column-definition are specified as: column-name specifies the name for the new column in the table. Column-name is an SQL identifier. column-name must be unique among column names in the table.
Syntax Description of ALTER TABLE SQL/MX Statements HEADING 'heading-string'| NO HEADING specifies a string heading-string of 0 to 128 characters to use as a heading for the column if it is displayed with a SELECT statement in MXCI. The heading-string can contain characters only from the ISO88591 character set. The default heading is column, the column name. If you specify a heading that is identical to the column name, INVOKE and SHOWDDL do not display that heading.
Syntax Description of ALTER TABLE SQL/MX Statements the PRIMARY KEY constraint for the table. Columns you define as unique must be specified as NOT NULL. A UNIQUE constraint is enforced with a unique index. If there is already a user-defined unique index on column-list, NonStop SQL/MX uses this index; if not, the system creates a unique index. The maximum combined length of the columns for a UNIQUE constraint is 255 bytes.
Syntax Description of ALTER TABLE SQL/MX Statements NonStop SQL/MX checks the condition whenever an operation occurs that might affect its value. The operation is allowed if the predicate in the search condition evaluates to TRUE or null, but is prohibited if the predicate evaluates to FALSE. When a check constraint is added, existing data is checked for violations.
Syntax Description of ALTER TABLE SQL/MX Statements update rule specifies what referential action is taken when column-list in referenced-table is updated. If no ON UPDATE clause is specified, a default of ON UPDATE NO ACTION is assumed. delete rule specifies what referential action is taken when a row in referenced-table is deleted. If no ON DELETE clause is specified, a default of ON DELETE NO ACTION is assumed.
Syntax Description of ALTER TABLE SQL/MX Statements If you specify CASCADE and referential constraints are dependent on the constraint, those dependent constraints are dropped in addition to the specified constraint being dropped. If you drop a constraint, NonStop SQL/MX drops its dependent index if SQL/MX originally created the same index. If the constraint uses an existing index, the index is not dropped. The default is RESTRICT. CONSTRAINT constraint specifies a name for the column or table constraint.
Syntax Description of ALTER TABLE SQL/MX Statements specify on a PRIMARY KEY constraint cannot match the set of columns on any UNIQUE constraint for the table. ASCENDING and DESCENDING specify the direction for entries in each column within the key. The default is ASCENDING. The PRIMARY KEY value in each row of the table must be unique within the table. Columns within a PRIMARY KEY cannot contain nulls. A PRIMARY KEY defined for a set of columns implies that the column values are unique and not null.
Syntax Description of ALTER TABLE SQL/MX Statements table can contain only values that match those in a column or set of columns specified in the REFERENCES clause. The two columns or sets of columns must have the same characteristics (data type, length, scale, precision), and there must be a UNIQUE or PRIMARY KEY constraint on the column or set of columns specified in the REFERENCES clause.
Considerations for ALTER TABLE SQL/MX Statements Unlike NonStop SQL/MP’s form of this statement, SQL/MX’s ALTER TABLE statement has no PARTONLY clause. When you supply a new value for attributes, ALTER TABLE modifies the value of the attribute on all partitions of the table. For more detail, see the entry for a specific attribute. Considerations for ALTER TABLE You cannot use ALTER TABLE to change a partition’s name.
Considerations for ALTER TABLE SQL/MX Statements secondary extent size and MAXEXTENTS values as the base table's primary partition.The index is created on the same volume as the base table's primary partition. NonStop SQL/MX then populates the new index. After NonStop SQL/MX populates the index, you should perform a FUP RELOAD on the index and all its partitions, to organize the index structure more efficiently and to reduce index levels.
Examples of ALTER TABLE SQL/MX Statements SQL/MX Extensions to ALTER TABLE These clauses are SQL/MX extensions: • • ATTRIBUTES clause ASCENDING and DESCENDING options on the PRIMARY KEY constraint Examples of ALTER TABLE • This example adds a UNIQUE table constraint: ALTER TABLE persnl.project ADD CONSTRAINT projtimestamp_uc UNIQUE (projcode, ship_timestamp); • This example drops a constraint: ALTER TABLE persnl.
Examples of ALTER TABLE SQL/MX Statements CITY CHAR(15), MGR CHAR(3), UNIQUE (PNUM), FOREIGN KEY (MGR) REFERENCES STAFF_M(EMPNUM)); ALTER TABLE STAFF_M ADD FOREIGN KEY (PRI_WK) REFERENCES PROJ_M (PNUM); Suppose further that you now need to drop the foreign key. Use SHOWDDL to obtain the key’s system identification: >>showddl staff_m; CREATE TABLE NIST_EMB_CAT.SUN.
ALTER TRIGGER Statement SQL/MX Statements ALTER TABLE NIST_EMB_CAT.SUN.STAFF_M ADD CONSTRAINT NIST_EMB_CAT.SUN.STAFF_M_187893997_9541 UNIQUE (EMPNUM) DROPPABLE ; ALTER TABLE NIST_EMB_CAT.SUN.STAFF_M ADD CONSTRAINT NIST_EMB_CAT.SUN.STAFF_M_859182618_9541 FOREIGN KEY (PRI_WK) REFERENCES NIST_EMB_CAT.SUN.PROJ_M(PNUM) DROPPABLE ; --- SQL operation complete.
Considerations for ALTER TRIGGER SQL/MX Statements Considerations for ALTER TRIGGER ENABLE ALL enables all triggers defined on table-name. DISABLE ALL disables all triggers defined on table-name. Authorization and Availability Requirements To alter a trigger, you must own its schema or be the super ID. Only the super ID can use ALTER TRIGGER DISABLE ALL or ALTER TRIGGER ENABLE ALL.
C Examples of BEGIN WORK SQL/MX Statements INSERT INTO sales.odetail VALUES (125, 4102, 25000, 2); --- 1 row(s) inserted. UPDATE invent.partloc SET qty_on_hand = qty_on_hand - 2 WHERE partnum = 4102 AND loc_code = 'G45'; --- 1 row(s) updated. --- This statement ends a transaction. COMMIT WORK; --- SQL operation complete. C Examples of BEGIN WORK • Begin a transaction, execute an UPDATE statement, and test SQLSTATE. If the UPDATE is successful, the database changes are committed.
CALL Statement SQL/MX Statements EXEC SQL COMMIT WORK END-EXEC. ELSE EXEC SQL ROLLBACK WORK END-EXEC. CALL Statement Considerations for CALL Examples of CALL The CALL statement invokes a stored procedure in Java (SPJ) in NonStop SQL/MX. To develop, deploy, and manage SPJs in SQL/MX, see the SQL/MX Guide to Stored Procedures in Java. CALL procedure-ref ([argument-list]) procedure-ref is: [[catalog-name.]schema-name.]procedure-name argument-list is: SQL-expression[{, SQL-expression}...
Considerations for CALL SQL/MX Statements Interval value expressions are disallowed in SPJs. For more information, see Input Parameter Arguments on page 2-28 and Output Parameter Arguments on page 2-28. Considerations for CALL Usage Restrictions You can use the CALL statement only as a stand-alone SQL statement in applications or interfaces that call NonStop SQL/MX. You cannot use the CALL statement inside a compound statement, in a trigger, or with rowsets.
Examples of CALL SQL/MX Statements conversion is from the actual output value, which has the data type of the formal parameter, to the declared type of the host variable or dynamic parameter. Null Input and Output You can pass a null value as input to or output from an SPJ, provided that the corresponding Java data type of the parameter supports nulls. If a null is input or output for a parameter that does not support nulls, NonStop SQL/MX returns an error.
COMMIT WORK Statement SQL/MX Statements COMMIT WORK Statement Considerations for COMMIT WORK MXCI Examples of COMMIT WORK C Examples of COMMIT WORK COBOL Examples of COMMIT WORK The COMMIT WORK statement commits any changes to audited objects made during the current transaction, releases all locks on audited objects held by the transaction, and ends the transaction. See Transaction Management on page 1-12. COMMIT [WORK] WORK is an optional keyword that has no effect.
C Examples of COMMIT WORK SQL/MX Statements The transaction must add the order for terminals to PARTSUPP, add the supplier to the SUPPLIER table, and update QTY_ON_HAND in PARTLOC. After the INSERT and UPDATE statements execute successfully, you commit the transaction, as shown, within MXCI: -- This statement initiates a transaction. BEGIN WORK; --- SQL operation complete. -- This statement inserts a new entry into PARTSUPP. INSERT INTO invent.partsupp VALUES (5100, 17, 800.00, 24); --- 1 row(s) inserted.
COBOL Examples of COMMIT WORK SQL/MX Statements COBOL Examples of COMMIT WORK • Begin a transaction, execute an UPDATE statement, and test SQLSTATE. If the UPDATE is successful, the database changes are committed. Otherwise, the database changes are rolled back. ... 01 SQLSTATE-OK PIC X(5) VALUE "00000". EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 SQLSTATE PIC X(5). ... EXEC SQL END DECLARE SECTION END-EXEC. ... * Start a transaction. EXEC SQL BEGIN WORK END-EXEC. ... * Change the database.
CONTROL QUERY DEFAULT Statement SQL/MX Statements CONTROL QUERY DEFAULT Statement The CONTROL QUERY DEFAULT statement changes the system-level default settings for the current process. Execution of this statement does not change the contents of the SYSTEM_DEFAULTS table. See System Defaults Table on page 10-30. CONTROL QUERY DEFAULT is an SQL/MX extension.
Examples of CONTROL QUERY DEFAULT SQL/MX Statements Relationship to CONTROL TABLE Use the CONTROL QUERY DEFAULT statement to override system-level default settings for various attributes for all tables in the current process. Use the CONTROL TABLE statement to override system-level default settings for the TABLELOCK, TIMEOUT, and SIMILARITY_CHECK attributes per table or for all tables in the current process.
CONTROL QUERY SHAPE Statement SQL/MX Statements CONTROL QUERY SHAPE Statement Considerations for CONTROL QUERY SHAPE Examples of CONTROL QUERY SHAPE The CONTROL QUERY SHAPE statement forces access plans. You can generate the result of the EXPLAIN function for a prepared DML statement, and then modify the operator tree for the statement’s access plan, by using CONTROL QUERY SHAPE. Both the EXPLAIN function and the CONTROL QUERY SHAPE statement use similar identifiers for the nodes of an operator tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements scan-option is: TABLE table | PATH {access-path | ANY} | BLOCKS_PER_ACCESS value | MDAM mdam-option,... | MDAM_COLUMNS mdam-columns-option,... mdam-option is: OFF | SYSTEM | FORCED mdam-columns-option is: n | SYSTEM | ALL | (density,...) | SYSTEM (density,...) | ALL (density,...) density is: SPARSE | DENSE | SYSTEM query-shape-options IMPLICIT { SORT | EXCHANGE | EXCHANGE_AND_SORT } makes SORT, EXCHANGE, or ENFORCER nodes in CONTROL QUERY SHAPE optional.
CONTROL QUERY SHAPE Statement SQL/MX Statements statement can still contain additional enforcer nodes, and the compiler will enforce such nodes. Note that WITHOUT ENFORCERS does not mean that the statement or the generated plans are free of enforcer nodes. shape specifies the operator tree for an access plan for the next query to be executed within the current session. shape defines this operator tree recursively by using a LISP-like expression to represent the nodes of the tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements INDEX_SCAN Replaces a SCAN node in operator tree. JOIN Replaces a JOIN node in operator tree. NESTED_JOIN Replaces a NESTED_JOIN in operator tree. MERGE_JOIN Replaces a MERGE_JOIN in operator tree. HASH_JOIN (cut,cut) or HJ (cut,cut) Replaces a HYBRID_HASH_JOIN or ORDERED_HASH_JOIN in operator tree. HYBRID_HASH_JOIN (cut,cut) or HHJ (cut,cut) Replaces a HYBRID_HASH_JOIN in operator tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements {SCAN | FILE_SCAN | INDEX_SCAN} [(scan-option,...)] specifies the options that you can use with SCAN, FILE_SCAN, or INDEX_SCAN, as follows: TABLE table specifies a table or correlation name. table is a character string literal—for example, 't1'. PATH {access-path | ANY} access-path specifies an index name or the table name table. It is a character string literal—for example, 'ix1' or 't1'.
CONTROL QUERY SHAPE Statement SQL/MX Statements MDAM_COLUMNS mdam-columns-option,... specifies these MDAM_COLUMNS options: n specifies n key columns to be used by MDAM. For example, if MDAM is using key columns specified by an index defined on a table, n specifies that the first n columns listed in the index are used. The enumeration algorithm for each column is determined by the system. This option is the same as ALL if n exceeds the total number of columns that MDAM can use.
Considerations for CONTROL QUERY SHAPE SQL/MX Statements ALL (density,...) forces an enumeration algorithm to be used by MDAM for each key column as determined by the density list. All of the remaining columns are used by MDAM, and their enumeration algorithms are determined by the system. For more information, see the SQL/MX Query Guide.
Examples of CONTROL QUERY SHAPE SQL/MX Statements By using the SET SHOWSHAPE command, you can inspect the default plan generated by the optimizer: SET SHOWSHAPE ON; SELECT * FROM EMPLOYEE, DEPT WHERE EMPLOYEE.DEPTNUM = DEPT.DEPTNUM AND EMPLOYEE.
Examples of CONTROL QUERY SHAPE SQL/MX Statements or SCAN (TABLE 'T1', PATH ANY) ° Scan table T1 using the base table. You want the system to choose whether to use MDAM. SCAN (TABLE 'T1', PATH 'T1') ° Scan table T1 using the index IT1. You want the system to choose whether to use MDAM. SCAN (TABLE 'T1', PATH 'IT1') ° Scan table T1 using the index IT1. You want to disable MDAM. SCAN (TABLE 'T1', PATH 'IT1', MDAM OFF) ° Scan table T1 using MDAM on index IT1.
Examples of CONTROL QUERY SHAPE SQL/MX Statements parser/SqlParser.y regress/compGeneral/EXPECTED018 regress/compGeneral/TEST018 • This example shows how a scan can be forced to use an index: >>prepare xx from +>select * from part where p_partkey = (select max(ps_partkey) from partsupp); --- SQL command prepared. >>display_explain options 'f' xx; LC RC OP OPERATOR OPT DESCRIPTION CARD --- --- --- -------------------- -------- ------------------- ------9 . 10 1.00E+0 5 8 9 1.00E+0 7 . 8 1.00E+0 6 . 7 1.
Examples of CONTROL QUERY SHAPE SQL/MX Statements max(ps_partkey) from partsupp); --- SQL command prepared. >>display_explain options 'f' xx; LC RC OP OPERATOR OPT DESCRIPTION CARD --- --- --- -------------------- -------- ------------------- ------13 . 14 root 1.00E+0 5 12 13 nested_join 1.00E+0 8 11 12 nested_join 1.00E+0 10 . 11 split_top 1.00E+0 9 . 10 partition_access 1.00E+0 . . 9 file_scan_unique fr 1.00E+0 7 . 8 split_top 6.66E+6 6 . 7 partition_access 6.66E+6 . . 6 index_scan fr 6.66E+6 4 .
CONTROL TABLE Statement SQL/MX Statements CONTROL TABLE Statement Considerations for CONTROL TABLE Examples of CONTROL TABLE The CONTROL TABLE statement specifies a performance-related option for DML accesses to a table or view. This statement can also be used as an embedded SQL compiler directive. CONTROL TABLE is an SQL/MX extension.
CONTROL TABLE Statement SQL/MX Statements OFF directs NonStop SQL/MX not to use MDAM. PRIORITY 'priority-value' specifies the priority for subsequent file system requests to the Data Access Manager (DAM). DAM uses the priority to ensure efficient performance within a mixed workload environment. Short-duration OLTP-type requests should specify a higher priority than any concurrent long-duration query requests. 'priority-value' specifies the priority, an integer value from 1 to 9. The default priority is 3.
CONTROL TABLE Statement SQL/MX Statements error. This option is for static operations only. For dynamic operations, see SET TABLE TIMEOUT Statement on page 2-214. 'timeout-value' specifies the time in hundredths of seconds. The range of values is from -1 to 2147483519, expressed in hundredths of seconds. The value -1 directs NonStop SQL/MX not to time out. The value 0 directs NonStop SQL/MX not to wait for a table lock. If the lock cannot be acquired, NonStop SQL/MX immediately returns an error.
Considerations for CONTROL TABLE SQL/MX Statements Considerations for CONTROL TABLE Scope of CONTROL TABLE The result of the execution of a CONTROL TABLE statement stays in effect until the current process terminates or until the execution of another CONTROL TABLE statement for the same control-table-option overrides it. For a detailed list of the precedence of default settings, see System Defaults Table on page 10-30.
CREATE CATALOG Statement SQL/MX Statements CREATE CATALOG Statement Considerations for CREATE CATALOG Examples of CREATE CATALOG The CREATE CATALOG statement creates a new SQL/MX catalog. See Catalogs on page 6-2. CREATE CATALOG is an SQL/MX extension. CREATE CATALOG catalog [LOCATION [\node.]$volume] Syntax Description of CREATE CATALOG catalog is an SQL identifier that specifies the name of the new catalog. catalog must be unique among catalog names on the node. LOCATION [\node.
Examples of CREATE CATALOG SQL/MX Statements Examples of CREATE CATALOG • This example creates a catalog: CREATE CATALOG samdbcat; HP NonStop SQL/MX Reference Manual—540440-003 2- 51
CREATE INDEX Statement SQL/MX Statements CREATE INDEX Statement Considerations for CREATE INDEX Examples of CREATE INDEX The CREATE INDEX statement creates an SQL/MX index based on one or more columns of a table. See Database Object Names on page 6-12. CREATE INDEX is an SQL/MX extension. CREATE [UNIQUE] INDEX index ON table (column-name [ASC[ENDING] | DESC[ENDING]] [,column-name [ASC[ENDING] | DESC[ENDING]]]...) [populate-option] [file-option]...
Syntax Description of CREATE INDEX SQL/MX Statements Syntax Description of CREATE INDEX UNIQUE specifies that the values (including NULL values) in the column or set of columns that make up the index field cannot contain more than one occurrence of the same value or set of values. For indexes with multiple columns, the values of the columns as a group determines uniqueness, not the values of the individual columns. If you omit UNIQUE, duplicate values are allowed.
Syntax Description of CREATE INDEX SQL/MX Statements constraint. You can populate an offline index and remove its offline designation by using the POPULATE INDEX utility. POPULATE Specifies that the index is to be created and populated. If you omit the populate-option, the default is POPULATE LOCATION [\node.]$volume[.subvolume.file-name] [NAME partition-name] specifies a node and volume for the primary partition of the index. node is the name of a node on the Expand network.
Syntax Description of CREATE INDEX SQL/MX Statements partn-file-option is: {[RANGE] PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD range-partn-defn [,ADD range-partn-defn]...)] defines secondary partitions for a range partitioned table. See Partitions on page 6-79 for details about partitions. BY (partitioning-column [,partitioning-column]...) specifies the partitioning columns. The default is the default partitioning key created by the STORE BY clause.
Syntax Description of CREATE INDEX SQL/MX Statements If the index has a system-generated SYSKEY, its column list cannot consist only of column SYSKEY. The SYSKEY must be the last column of the column list, and you cannot specify a FIRST KEY value for the SYSKEY column. This limitation does not apply to a user-created SYSKEY column. ADD partn-defn defines a single secondary hash partition and includes the LOCATION of the partition. partn-defn is: LOCATION [\node.]$volume[.subvolume.
Considerations for CREATE INDEX SQL/MX Statements file-name is an optional Guardian file name. file-name names must be 8 characters in length and must end with the digits “00” (zero zero.) Any Guardian file name you specify must match the designated schema subvolume name for the schema in which the object is being created. Otherwise, NonStop SQL/MX returns an error. partition-name is an SQL identifier for a partition. partn-file-option is an SQL/MX extension. See PARTITION Clause on page 7-5.
Examples of CREATE INDEX SQL/MX Statements After you perform POPULATE INDEX, you should perform a FUP RELOAD on the index and all its partitions, to organize the index structure more efficiently and to reduce index levels. If the MAXEXTENT value that you specified is too small, when you run the POPULATE INDEX utility it automatically increases the value to the largest possible size.
CREATE PROCEDURE Statement SQL/MX Statements ADD FIRST KEY 'O' LOCATION $data2, ADD FIRST KEY 'T' LOCATION $data3); CREATE PROCEDURE Statement Considerations for CREATE PROCEDURE Examples of CREATE PROCEDURE The CREATE PROCEDURE statement registers an existing Java method as a stored procedure in Java (SPJ) within NonStop SQL/MX. To develop, deploy, and manage SPJs in SQL/MX, see the SQL/MX Guide to Stored Procedures in Java.
CREATE PROCEDURE Statement SQL/MX Statements procedure-ref([sql-parameter[{, sql-parameter}...]]) specifies the name of the SPJ and SQL parameters that correspond to the signature of the SPJ method. procedure-ref specifies an ANSI logical name of the form: [[catalog-name.]schema-name.]procedure-name where each part of the name is a valid SQL identifier with a maximum of 128 characters. For more information, see Identifiers on page 6-52.
CREATE PROCEDURE Statement SQL/MX Statements OUT specifies a parameter that accepts data from an SPJ. sql-identifier specifies an SQL identifier that describes the parameter. For more information, see Identifiers on page 6-52. sql-datatype specifies an SQL data type that corresponds to the Java parameter of the SPJ method. sql-datatype can be: Ext Ext SQL/MX Data Type Maps to Java Data Type...
CREATE PROCEDURE Statement SQL/MX Statements Ext This icon indicates an SQL data type that is an SQL/MX extension to the ANSI standard. All other SQL data types in this table conform to the ANSI standard. For more information, see Data Types on page 6-16. EXTERNAL NAME 'java-method-name [java-signature]' java-method-name specifies the case-sensitive name of the SPJ method of the form: [package-name.]class-name.method-name The Java method must exist in a Java class file, class-name.
CREATE PROCEDURE Statement SQL/MX Statements Specify package names in the EXTERNAL NAME clause, not the EXTERNAL PATH clause. LANGUAGE JAVA specifies that the external user-defined routine is written in the Java language. PARAMETER STYLE JAVA specifies that the run-time conventions for arguments passed to the external user-defined routine are those of the Java language. LOCATION procedure-label specifies a Guardian physical name and location for the stored procedure label.
Considerations for CREATE PROCEDURE SQL/MX Statements CONTAINS SQL | MODIFIES SQL DATA | READS SQL DATA specifies that the SPJ can perform SQL operations. Currently, all the options allow an SPJ to read and modify SQL data. If you do not specify an SQL access mode, the default is CONTAINS SQL. DYNAMIC RESULT SETS integer specifies the maximum number of result sets that the SPJ can return. NonStop SQL/MX does not support result sets. If you specify this clause, you must set the value to 0 (zero).
Examples of CREATE PROCEDURE SQL/MX Statements The statement verifies the existence of the SPJ method, lowerprice, in the /usr/mydir/myclasses/Sales.class. Because the procedure name is not qualified by a catalog and schema, NonStop SQL/MX qualifies it according to the current settings of CATALOG and SCHEMA, which are SAMDBCAT and SALES in this case.
CREATE SCHEMA Statement SQL/MX Statements 4 For more examples, see the SQL/MX Guide to Stored Procedures in Java. CREATE SCHEMA Statement Considerations for CREATE SCHEMA Examples of CREATE SCHEMA CREATE SCHEMA creates an SQL/MX schema. See Schemas on page 6-101. CREATE SCHEMA with the optional location clause is an SQL/MX extension. CREATE SCHEMA schema-clause [schema-element [, schema-element] ...
Syntax Description of CREATE SCHEMA SQL/MX Statements Enter an auth-id as a simple name, for example, "sql.user1". Because of the “.” , you must enclose the user name in double quotes, the same as for a delimited identifier. You cannot specify PUBLIC as the auth-id, because a schema can have only one owner. LOCATION subvolume optionally specifies the designated subvolume name for the schema. Ordinarily, NonStop SQL/MX generates a subvolume name for the schema.
Considerations for CREATE SCHEMA SQL/MX Statements schema-element specifies the objects to be defined in the schema being created. The element in the statement must be in the same schema as the schema you are creating. Schema elements must appear in sequence—a schema element that depends on another schema element must be listed after that schema element. table-definition is a CREATE TABLE statement. view-definition is a CREATE VIEW statement. grant-statement is a GRANT statement.
Examples of CREATE SCHEMA SQL/MX Statements Schemas named SYSTEM_SCHEMA, SYSTEM_DEFAULTS_SCHEMA and MXCS_SCHEMA in the system catalog are reserved for metadata. You cannot drop them or create objects in them. Examples of CREATE SCHEMA • This example creates a schema: CREATE SCHEMA mycat.myschema; • This example creates a schema with pubs.jsmith as the owner, located on subvolume ZSDABCDE: CREATE SCHEMA sch2 AUTHORIZATION 'pubs.
CREATE SQLMP ALIAS Statement SQL/MX Statements CREATE SQLMP ALIAS Statement Considerations for CREATE SQLMP ALIAS Examples of CREATE SQLMP ALIAS The CREATE SQLMP ALIAS statement defines mappings from an ANSI name to the physical names of an SQL/MP table or view. CREATE SQLMP ALIAS is an SQL/MX extension. CREATE SQLMP ALIAS catalog.schema.object [\node.]$volume.subvol.filename catalog.schema.object is the alias name of an SQL/MP table or view.
Considerations for CREATE SQLMP ALIAS SQL/MX Statements Considerations for CREATE SQLMP ALIAS Reserved Alias Names Alias names prefixed by the name of a UMD table are reserved. You cannot create aliases with such names. For example, you cannot create an alias named HISTOGRAMS_MYALIAS. Usage Restrictions If the catalog and schema do not exist, NonStop SQL/MX returns an error. If the specified alias name already exists, NonStop SQL/MX returns an error.
Considerations for CREATE SQLMP ALIAS SQL/MX Statements Late Bind If you compile an application that uses an SQL/MP alias and later you change the SQL/MP alias to map to a different SQL/MP table, the SQL/MP table definition is no longer compatible with the definition used at compile time. As a result, you must manually recompile applications that use the alias. If the late bind does not find the SQL/MP table underlying the SQL/MP alias or if the SQL/MP table was moved, NonStop SQL/MX returns an error.
Examples of CREATE SQLMP ALIAS SQL/MX Statements SQL/MP shorthand view and whose OBJECT_UID points to an entry in the MP_PARTITIONS table in the same definition schema. (See MP_PARTITIONS Table on page 10-19. The MPALIAS table which SQL/MX Release 1.8 and earlier versions created in the SQL/MP catalog is no longer used. Instead, the alias information for each schema is kept in the SQL/MX metadata for that schema.
CREATE TABLE Statement SQL/MX Statements CREATE TABLE Statement Considerations for CREATE TABLE Examples of CREATE TABLE The CREATE TABLE statement creates an SQL/MX table. See Database Object Names on page 6-12. CREATE TABLE table { (table-element [,table-element]...) | like-spec } [file-option ]...
CREATE TABLE Statement SQL/MX Statements default is: literal | NULL | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | {CURRENT_USER | USER} column-constraint is: NOT NULL [[NOT] DROPPABLE] | UNIQUE | PRIMARY KEY [ASC[ENDING] | DESC[ENDING]] [[NOT] DROPPABLE] | CHECK (condition) | REFERENCES ref-spec ref-spec is: referenced-table [(column-list)] [referential triggered action] referential triggered action is: update rule [delete rule] | delete rule [update rule] update rule is: ON UPDATE referential actio
Syntax Description of CREATE TABLE SQL/MX Statements store-option is: PRIMARY KEY | (key-column-list) partn-file-option is: { [RANGE] PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD range-partn-defn [,ADD range-partn-defn]...)] | HASH PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD partn-defn [,ADD partn-defn]...)]} range-partn-defn is: FIRST KEY {col-value | (col-value [,col-value ]...)} partn-defn partn-defn is: LOCATION [\node.]$volume[.subvolume.
Syntax Description of CREATE TABLE SQL/MX Statements column is an SQL identifier. column must be unique among column names in the table. If the name is an SQL/MX reserved word, you must delimit it by enclosing it in double quotes. Such delimited parts are case-sensitive. For example: "join". column cannot be SYSKEY if the clustering key contains SYSKEY. data-type is the data type of the values that can be stored in column.
Syntax Description of CREATE TABLE SQL/MX Statements DROPPABLE specifies that you can drop the NOT NULL constraint by using ALTER TABLE at some later time. Dropping NOT NULL requires that you know the name of the constraint, either by using the CONSTRAINT constraint clause when the table is created or by using SHOWDDL to display the constraint name. NOT DROPPABLE specifies that the NOT NULL constraint is permanent.
Syntax Description of CREATE TABLE SQL/MX Statements PRIMARY KEY constraint is permanent. A PRIMARY KEY constraint is implemented more efficiently if the constraint is permanent. A SYSKEY is not generated for a table that has a NOT DROPPABLE PRIMARY KEY. For both a DROPPABLE and NOT DROPPABLE PRIMARY KEY, the maximum combined length of the columns is 255 bytes.
Syntax Description of CREATE TABLE SQL/MX Statements You cannot refer to the CURRENT_DATE, CURRENT_TIME, or CURRENT_TIMESTAMP function in a CHECK constraint, and you cannot use subqueries in a CHECK constraint. CHECK constraints cannot contain non-ISO88591 string literals. REFERENCES ref-spec specifies a references column constraint. The maximum combined length of the columns for a REFERENCES constraint is 255 bytes.
Syntax Description of CREATE TABLE SQL/MX Statements referential action RESTRICT referential action means that the referential check is made for each row. An error is raised when the referential constraint is violated. ANSI SQL-99 standard: NO ACTION referential action means that the referential check is made at the end of the SQL statement. An error is raised when the referential constraint is violated.
Syntax Description of CREATE TABLE SQL/MX Statements store-option is defined as: PRIMARY KEY bases the clustering key on the primary key columns. This store option requires that the primary key is NOT DROPPABLE. If the primary key is defined as DROPPABLE, NonStop SQL/MX returns an error. key-column-list bases the clustering key on the columns in the key-column-list. The key columns in key-column-list must be specified as NOT NULL NOT DROPPABLE and cannot have a combined length of more than 247 bytes.
Syntax Description of CREATE TABLE SQL/MX Statements • The name must be exactly eight characters long. file-name is a Guardian file name. file-name names must be eight characters in length and must end with the digits “00” (zero zero.) Any Guardian file name you specify must match the designated schema subvolume name for the schema in which the object is being created. Otherwise, NonStop SQL/MX returns an error. partition-name is an SQL identifier for a partition.
Syntax Description of CREATE TABLE SQL/MX Statements stored in ascending order and the highest values in the partition for columns stored in descending order. These column values are referred to as the partitioning key. col-value is a literal that specifies the first value allowed in the associated partition for that column of the partitioning key.
Syntax Description of CREATE TABLE SQL/MX Statements subvolume is the name of the schema subvolume for the schema in which the table is being created. Follow these guidelines when using SQL/MX subvolume names: • • The name must begin with the letters ZSD, followed by a letter, not a digit (for example, ZSDa, not ZSD2). The name must be exactly eight characters long. file-name is a Guardian file name. file-name names must be eight characters in length and must end with the digits “00” (zero zero.
Syntax Description of CREATE TABLE SQL/MX Statements For more information, see the entry for a specific attribute. LIKE source-table [include-option]... directs NonStop SQL/MX to create a table like the existing table, source-table, omitting constraints (with the exception of the NOT NULL and NOT DROPPABLE PRIMARY KEY constraints), headings, and partitions unless include-option clauses are specified. The source-table must be the ANSI name of an SQL/MX format table (you cannot specify an SQL/MP table).
Considerations for CREATE TABLE SQL/MX Statements WITH PARTITIONS directs NonStop SQL/MX to use partition definitions from source-table. Each new table partition resides on the same volume as its original sourcetable counterpart. The new table partitions do not inherit partition names from the original table. Instead, NonStop SQL/MX generates new names based on the physical file location. If you specify the LIKE clause and the PARTITION file-option, you cannot specify WITH PARTITIONS.
Considerations for CREATE TABLE SQL/MX Statements Storage Order and the LIKE Specification The STORE BY clause determines the storage order of the records in the new table: STORE BY PRIMARY KEY The new table is ordered by the primary key of the source table. STORE BY key-column-list The new table is ordered by the new key-column-list. No STORE BY clause The new table is ordered by the storage key of the source table.
Considerations for CREATE TABLE SQL/MX Statements For small tables, you need not be concerned about the details of this mechanism. For large tables, however, the indexes used to enforce constraints can require significant amounts of disk space.
SQL/MX Statements • • • Considerations for CREATE TABLE The application that issues the CREATE TABLE DDL statement is an MXCS/JDBC session or an MXCI session. The CREATE TABLE statement does not specify partitioning syntax. The CREATE TABLE statement specifies either the PRIMARY KEY or the STORE BY clause. If you specify the LOCATION clause for the primary partition, that partition will reside on the volume specified in that clause, not in the location specified in POS_LOCATIONS.
Examples of CREATE TABLE SQL/MX Statements SQL/MX cannot partition the table. If you attempt to use POS with such a table, you will not receive an error. POS creates a nonpartitioned table in the same way that NonStop SQL/MX creates a nonpartitioned table without the LOCATION clause as part of the CREATE TABLE statement. The location of this table is not based on POS_LOCATIONS or automatic disk location.
Examples of CREATE TABLE SQL/MX Statements • This example creates a table like the JOB table with the same constraints: CREATE TABLE SAMDBCAT.PERSNL.JOB_CORPORATE LIKE SAMDBCAT.PERSNL.JOB WITH CONSTRAINTS; • This example creates table tab1 with partitions named partition1 and partition2. It then creates table tab2 like tab1 with partitions. tab2’s partitions have different names than the partitions on tab1.
Examples of CREATE TABLE SQL/MX Statements ; --- SQL operation complete. • Perform SHOWDDL to display tab2’s properties. Note that the partitions are now named CARNAG_HIJO_ZSDCL87P_PT245W00 and CARNAG_CHINA_ZSDCL87P_S1645W00: >>showddl tab2; CREATE TABLE J1.SCH1.TAB2 ( A INT NO DEFAULT -- NOT NULL NOT DROPPABLE , B INT DEFAULT NULL , CONSTRAINT J1.SCH1.TAB2_378461764_1268 PRIMARY KEY (A ASC) NOT DROPPABLE , CONSTRAINT J1.SCH1.TAB2_753441764_1268 CHECK (J1.SCH1.TAB2.
SQL/MX Statements Examples of CREATE TABLE ; create unique index mytable_idx1 on mytable(col2, col1) LOCATION $vol1 hash partition by (col2) ( add location $VOL2 , add location $VOL3 , add location $VOL4 , add location $VOL5) ; • This example creates a table stored by primary key. These defaults are in effect: POS_LOCATIONS is set to $VOL1, $VOL2, $VOL3 and POS_NUM_OF_PARTNS is set to 3. CREATE TABLE SALES.
CREATE TRIGGER Statement SQL/MX Statements NonStop SQL/MX will place the primary partition on $DATA1, the second partition on $VOL1, the third partition on $VOL2, and the fourth partition on $VOL3. CREATE TRIGGER Statement Considerations for CREATE TRIGGER Examples of CREATE TRIGGER The CREATE TRIGGER statement is used to create triggers on SQL/MX tables. A trigger is a mechanism that sets up the database system to perform certain actions automatically in response to the occurrence of specified events.
Syntax Description of CREATE TRIGGER SQL/MX Statements column-name specifies the ANSI logical name of the column to be inserted, deleted, or updated when the trigger is activated, of the form: [[catalog-name.]schema-name.]column-name where each part of the name is a valid SQL identifier with a maximum of 128 characters. table-name specifies the ANSI logical name of the table this trigger is defined on, of the form: [[catalog-name.]schema-name.
Considerations for CREATE TRIGGER SQL/MX Statements insert-statement is an insert statement to be performed when this trigger is activated. signal-statement is a statement to be sent to the SIGNAL statement. set-new-statement is an assignment statement that can be used as a BEFORE-trigger action to assign values to transition variables representing columns in the subject table modified by the triggering action. quoted-sqlstate is the five-digit SQLSTATE to be passed to SIGNAL.
Considerations for CREATE TRIGGER SQL/MX Statements Authorization and Availability Requirements To create a trigger, you must own the schema where the trigger is defined and the schema where the subject table of the schema resides and you must have REFERENCES privileges on the columns used on the referenced table. Otherwise, you must be the super ID. Trigger Types You can configure triggers as BEFORE or AFTER types. When a triggering statement occurs, this is the order of execution: 1. 2. 3. 4.
Considerations for CREATE TRIGGER SQL/MX Statements • To massage data prior to the insert or update operation that caused the trigger to be activated (using the SET statement as an action.) BEFORE-type trigger operations are exercised as tentative executions. The triggering statement is executed but assigns values to the NEW ROW transition variables rather than to the subject table. That table appears not to be affected by the tentative execution.
Considerations for CREATE TRIGGER SQL/MX Statements • You cannot define triggers on SQL/MP objects. SQL/MP objects cannot be referenced in a trigger. Recompilation and Triggers User applications that change (INSERT, UPDATE, or DELETE) information in a table are automatically recompiled when a trigger with a matching event is added or dropped. User applications that use a SELECT on the subject table do not require recompilation.
Examples of CREATE TRIGGER SQL/MX Statements Keep this limit in mind when you create tables. If you plan to create triggers on a table, its primary key length cannot exceed 239 bytes. A table which will not have triggers can have a primary key of 255 bytes. Rowsets SQL/MX rowsets are allowed in UPDATE and DELETE statements that are trigger events. UPDATE and DELETE statements that use rowset arrays perform multiple executions of UPDATE or DELETE statements.
Examples of CREATE TRIGGER SQL/MX Statements ATTRIBUTES EXTENT (1024,1024) MAXEXTENTS 700 LOCATION $D00001.ZSDDEMO1.PRSCR000; You can create a BEFORE trigger on prescription so that when a prescription is entered, if the prescribed drug is found in generic_drugs, a generic drug is substituted for the brand-name drug, and the instructions for the drugs are updated: CREATE TRIGGER alternate_drug BEFORE INSERT ON prescription REFERENCING NEW AS newdrug FOR EACH ROW WHEN (upshift(newdrug.
SQL/MX Statements Examples of CREATE TRIGGER This embedded DML statement inserts ten rows into table tab1. EXEC SQL insert into cat.sch.tab1 values (:ArrayA); If trigger trg1 is defined as an insert statement trigger on tab1,and trg2 is defined as an insert row trigger on tab1, when the DML statement is executed, the two triggers are fired. The action of trg1 executes once for the entire statement, while trg2 executes ten times, once for each element in the rowset.
CREATE VIEW Statement SQL/MX Statements CREATE VIEW Statement Considerations for CREATE VIEW Examples of CREATE VIEW The CREATE VIEW statement creates an SQL/MX view. See Views on page 6-108. CREATE VIEW view [(column-name [heading] [,column-name [heading]]...)] [LOCATION [\node.]$volume[.subvolume.
Syntax Description of CREATE VIEW SQL/MX Statements Syntax Description of CREATE VIEW view specifies the ANSI logical name for the view of the form: [[catalog-name.]schema-name.]view where each part of the name is a valid SQL identifier with a maximum of 128 characters. view must be unique among table, view, SQL/MP alias, and procedure names in the schema. For more information, see Identifiers on page 6-52. (column-name [heading] [,column-name [heading]]...
Syntax Description of CREATE VIEW SQL/MX Statements SQL/MP, which does not display anything for a heading in a SELECT statement if the heading is specified as HEADING ‘’. The HEADING clause is an SQL/MX extension. LOCATION [\node.]$volume[.subvolume.filename] specifies a node and volume for the label of the view. node is the name of a node on the Expand network. For Guardian files representing a table or index partition or a view label, node can be any node from which the object's catalog is visible.
Considerations for CREATE VIEW SQL/MX Statements WITH [CASCADED] CHECK OPTION specifies that no row can be inserted or updated in the database through the view unless the row satisfies the view definition—that is, the search condition in the WHERE clause of the query expression must evaluate to TRUE for any row that is inserted or updated.
Examples of CREATE VIEW SQL/MX Statements • • • • • It cannot contain a GROUP BY or HAVING clause. It cannot directly contain the keyword DISTINCT. The FROM clause must refer to exactly one table or one updatable view. It cannot contain a WHERE clause that contains a subquery. The select list cannot include expressions or functions or duplicate column names. An updatable view is insertable if the column list does not include a SYSKEY from the underlying base table.
DELETE Statement SQL/MX Statements DELETE Statement Considerations for DELETE MXCI Examples of DELETE C Examples of DELETE COBOL Examples of DELETE Publish/Subscribe Examples of DELETE The DELETE statement is a DML statement that deletes a row or rows from a table or an updatable view. Deleting rows from a view deletes the rows from the table on which the view is based. DELETE does not remove a table or view, even if you delete the last row in the table or view.
DELETE Statement SQL/MX Statements Embed Positioned DELETE is: DELETE FROM table C/COBOL Embed WHERE CURRENT OF {cursor-name | ext-cursor-name} ROWSET FOR INPUT SIZE rowset-size-in Allowed only if you specify rowset-search-condition in the WHERE clause. rowset-size-in restricts the size of the input rowset to the specified size.
DELETE Statement SQL/MX Statements set-roll-clause sets the specified column to a particular value. For each set-roll-clause, the value of the specified target column-name is replaced by the value of the update source expression. The data type of each target column must be compatible with the data type of its source value. column-name names a column in table to update. You cannot qualify or repeat a column name. You cannot update the value of a column that is part of the primary key.
Considerations for DELETE SQL/MX Statements SERIALIZABLE | REPEATABLE READ specifies that the DELETE statement and any concurrent process (accessing the same data) execute as if the statement and the other process had run serially rather than concurrently. SKIP CONFLICT enables transactions to skip rows locked in a conflicting mode by another transaction. The rows under consideration are the result of evaluating the search condition for the DELETE statement.
Considerations for DELETE SQL/MX Statements Authorization Requirements DELETE requires authority to read and write to the table or view being deleted from and authority to read tables or views specified in subqueries used in the search condition. Transaction Initiation and Termination The DELETE statement automatically initiates a transaction if there is no active transaction and if the statement references an audited table.
MXCI Examples of DELETE SQL/MX Statements or utility operations with DML operations, can lead to inconsistent data within a nonaudited table or between a nonaudited table and its indices. To avoid problems, do not run DDL or utility operations concurrently with DML operations on nonaudited tables. When you try to delete data in a nonaudited table with an index, NonStop SQL/MX returns an error.
C Examples of DELETE SQL/MX Statements • Remove from the table PARTSUPP all suppliers who charge more than $1,600.00 for items that have part numbers in the range 6400 to 6700: DELETE FROM invent.partsupp WHERE partnum BETWEEN 6400 AND 6700 AND partcost > 300.00 SERIALIZABLE ACCESS; --- 3 row(s) deleted. This DELETE uses SERIALIZABLE access, which provides maximum consistency but reduces concurrency. Therefore, you should run this statement at a time when few users need concurrent access to the database.
COBOL Examples of DELETE SQL/MX Statements COBOL Examples of DELETE • Remove the row for JOHN WALKER from the EMPLOYEE table: EXEC SQL DELETE FROM PERSNL.EMPLOYEE WHERE FIRST_NAME = 'JOHN' AND LAST_NAME = 'WALKER' SERIALIZABLE ACCESS END-EXEC. • Use a cursor and delete some of the returned rows during processing: ... EXEC SQL DECLARE emp_cursor CURSOR FOR SELECT EMPNUM, DEPTNUM, JOBCODE, SALARY FOR UPDATE ACCESS FROM PERSNL.EMPLOYEE SERIALIZABLE ACCESS END-EXEC. ... EXEC SQL OPEN emp_cursor END-EXEC.
SQL/MX Statements • Publish/Subscribe Examples of DELETE This example shows the SET ON ROLLBACK clause in an embedded delete of a SELECT statement: SELECT * FROM (DELETE FROM tab1 SET ON ROLLBACK a = a + 1) tab1; • This example shows SKIP CONFLICT ACCESS used with an embedded delete statement accessing a table as a stream: SELECT a FROM (DELETE FROM STREAM(tab1) WHERE a = 1 FOR SKIP CONFLICT ACCESS) as tab1; HP NonStop SQL/MX Reference Manual—540440-003 2 -117
DROP CATALOG Statement SQL/MX Statements DROP CATALOG Statement Considerations for DROP CATALOG Examples of DROP CATALOG The DROP CATALOG statement deletes an empty SQL/MX catalog. See Catalogs on page 6-2. DROP CATALOG is an SQL/MX extension. DROP CATALOG catalog Syntax Description of DROP CATALOG catalog is the name of the empty catalog. You must drop all schemas from the catalog before you can use the DROP CATALOG statement.
DROP INDEX Statement SQL/MX Statements DROP INDEX Statement Considerations for DROP INDEX Examples of DROP INDEX The DROP INDEX statement deletes an SQL/MX index. See Database Object Names on page 6-12. DROP INDEX is an SQL/MX extension. DROP INDEX index [RESTRICT | CASCADE] Syntax Description of DROP INDEX index is the ANSI logical name of the index to drop, of the form: [[catalog-name.]schema-name.]index where each part of the name is a valid SQL identifier with a maximum of 128 characters.
Examples of DROP INDEX SQL/MX Statements Examples of DROP INDEX • This example drops an index: DROP INDEX myindex; DROP PROCEDURE Statement Considerations for DROP PROCEDURE Example of DROP PROCEDURE The DROP PROCEDURE removes a stored procedure in Java (SPJ) from NonStop SQL/MX. To develop, deploy, and manage SPJs in SQL/MX, see the SQL/MX Guide to Stored Procedures in Java. DROP PROCEDURE procedure-ref [RESTRICT] procedure-ref is: [[catalog-name.]schema-name.
Considerations for DROP PROCEDURE SQL/MX Statements Considerations for DROP PROCEDURE Required Privileges To issue a DROP PROCEDURE statement, you must own the SPJ or be the super ID. Example of DROP PROCEDURE • Drop an SPJ named ADJUSTSALARY from NonStop SQL/MX: DROP PROCEDURE samdbcat.persnl.adjustsalary; DROP SCHEMA Statement Considerations for DROP SCHEMA Examples of DROP SCHEMA The DROP SCHEMA statement deletes an SQL/MX schema. See Schemas on page 6-101.
Considerations for DROP SCHEMA SQL/MX Statements Authorization and Availability Requirements To drop a schema, you must own the schema or be the super ID. You must have remote passwords for any nodes to which the schema’s catalog has been registered.
Examples of DROP SCHEMA SQL/MX Statements *AuditTrailBuffer/SQLMXBuffer (MB)..... *AutoRevive............................ *AutoSelect............................ *AutoStart............................. *CBPoolLen............................. *FSTCaching............................ *FullCheckpoints....................... *HaltOnError........................... *LKIDLongPoolLen....................... *LKTableSpaceLen....................... *MaxLocksPerOCB........................ *MaxLocksPerTCB.............
DROP SQL Statement SQL/MX Statements DROP SQL Statement Considerations for DROP SQL Examples of DROP SQL The DROP SQL statement puts NonStop SQL/MX in an uninitialized state. It drops a system catalog that has no user-created catalogs. DROP SQL is an SQL/MX extension. DROP SQL Considerations for DROP SQL After you run the DROP SQL statement, you must run the InstallSqlmx script again to re-enable the use of SQL on the system.
DROP SQLMP ALIAS Statement SQL/MX Statements DROP SQLMP ALIAS Statement Considerations for DROP SQLMP ALIAS Examples of DROP SQLMP ALIAS The DROP SQLMP ALIAS statement is used to drop mappings from ANSI names to physical names of SQL/MP tables or views. DROP SQLMP ALIAS is an SQL/MX extension. DROP SQLMP ALIAS catalog.schema.object catalog.schema.object is the alias name of an SQL/MP table or view.
Examples of DROP SQLMP ALIAS SQL/MX Statements Examples of DROP SQLMP ALIAS • Suppose that you have created an SQL/MP table by using this SQL/MP CREATE TABLE statement: CREATE TABLE $myvol.mysubvol.mytable ( num NUMERIC (4) UNSIGNED NOT NULL ,name VARCHAR (20) ,PRIMARY KEY (num) ); This statement creates a mapping in the system metadata table: CREATE SQLMP ALIAS mycatalog.myschema.mytable $myvol.mysubvol.mytable; This statement drops the mapping in the system metadata table: DROP SQLMP ALIAS mycatalog.
DROP TABLE Statement SQL/MX Statements DROP TABLE Statement Considerations for DROP TABLE Examples of DROP TABLE The DROP TABLE statement deletes an SQL/MX table and any indexes, constraints, and inactive locks on the table. See Database Object Names on page 6-12. DROP TABLE table [RESTRICT | CASCADE] Syntax Description of DROP TABLE table is the name of the table to delete. If the table has an active DDL lock, neither the table nor any of its dependent objects are dropped.
Examples of DROP TABLE SQL/MX Statements in an RDF backup database, full Guardian file names are preserved and can be used to create identical file names. Grant and revoke privileges are not saved as part of DDL text. However, the DDL text includes DELETE statements to remove the default security information from the metadata tables TBL_PRIVILEGES and COL_PRIVILEGES and INSERT statements to record the correct security information.
DROP TRIGGER Statement SQL/MX Statements DROP TRIGGER Statement Considerations for DROP TRIGGER Examples of DROP TRIGGER The DROP TRIGGER statement is used to drop a trigger on an SQL/MX table. DROP TRIGGER trigger-name; Syntax Description of DROP TRIGGER trigger-name specifies the ANSI logical name of the trigger to be dropped, of the form: [[catalog-name.]schema-name.]trigger-name where each part of the name is a valid SQL identifier with a maximum of 128 characters.
DROP VIEW Statement SQL/MX Statements DROP VIEW Statement Considerations for DROP VIEW Examples of DROP VIEW The DROP VIEW statement deletes an SQL/MX view. See Views on page 6-108. DROP VIEW view [CASCADE | RESTRICT] Syntax Description of DROP VIEW view is the name of the view to drop. If you specify RESTRICT, you cannot drop the specified view if it is referenced in the query expression of any other view or in the search condition of another object's constraint.
EXECUTE Statement SQL/MX Statements EXECUTE Statement Considerations for EXECUTE MXCI Examples of EXECUTE C Examples of EXECUTE COBOL Examples of EXECUTE The EXECUTE statement executes an SQL statement previously compiled by a PREPARE statement. You can use EXECUTE in an MXCI session or in an embedded SQL program. C/COBOL MXCI C/COBOL Input data can be supplied either by using host variables or through an SQL descriptor area in an embedded SQL program.
EXECUTE Statement SQL/MX Statements The module that contains EXECUTE must also contain a PREPARE statement for statement-name. MXCI USING param-value [,param-value]... specifies values for the unnamed parameters in the prepared statement. The data type of a parameter value must be compatible with the data type of the associated parameter.
EXECUTE Statement SQL/MX Statements When EXECUTE with INTO executes, NonStop SQL/MX stores information into the host variables (and optionally their indicator variables) that correspond to columns specified in the select list for the prepared statement. :variable-name [[INDICATOR] :indicator-name] is a variable specification—a host variable with optionally an indicator variable. A variable name begins with a colon (:). The data type of an indicator variable is exact numeric with a scale of 0.
Considerations for EXECUTE SQL/MX Statements Considerations for EXECUTE Scope of EXECUTE A statement must be compiled by PREPARE before you EXECUTE it, but after it is compiled, you can execute the statement multiple times without recompiling it. MXCI C/COBOL The statement must have been compiled during the same MXCI session as its execution. The statement must have been prepared during the same compilation unit as its execution.
C Examples of EXECUTE SQL/MX Statements • Use EXECUTE USING for one parameter value, which is unnamed in the prepared statement: PREPARE FINDEMP FROM SELECT * FROM persnl.employee WHERE salary > ?SALARY AND jobcode = ?; SET PARAM ?SALARY 40000.00; EXECUTE FINDEMP USING 450; SET PARAM ?SALARY 20000.00; EXECUTE FINDEMP USING 300; C Examples of EXECUTE • Prepare and execute an UPDATE statement with dynamic input parameters: ... strcpy(stmt_buffer,"UPDATE SALES.
COBOL Examples of EXECUTE SQL/MX Statements • This example uses extended statement names: ... strcpy(stmt,"ins_cust1"); EXEC SQL PREPARE :stmt FROM :stmt_buffer; EXEC SQL EXECUTE :stmt; ... strcpy(stmt,"ins_cust2"); EXEC SQL PREPARE :stmt FROM :stmt_buffer; EXEC SQL EXECUTE :stmt; COBOL Examples of EXECUTE • Prepare and execute an UPDATE statement with dynamic input parameters: ... MOVE "UPDATE SALES.CUSTOMER SET CREDIT = ? & " WHERE CUSTNUM = CAST(? AS NUMERIC(4) UNSIGNED)" TO stmt-buffer. ...
COBOL Examples of EXECUTE SQL/MX Statements END-EXEC. ... EXEC SQL EXECUTE USING SQL DESCRIPTOR 'in_args' INTO SQL DESCRIPTOR 'out_cols' END-EXEC. ... • This example uses extended statement names: ... MOVE EXEC EXEC ... MOVE EXEC EXEC "ins_cust1" TO stmt. SQL PREPARE :stmt FROM :stmt-buffer END-EXEC. SQL EXECUTE :stmt END-EXEC. "ins_cust2" TO stmt. SQL PREPARE :stmt FROM :stmt-buffer END-EXEC. SQL EXECUTE :stmt END-EXEC.
GRANT Statement SQL/MX Statements GRANT Statement Considerations for GRANT Examples of GRANT The GRANT statement grants access privileges for an SQL/MX table, view, or stored procedure to specified users. See also GRANT EXECUTE Statement on page 2-141 GRANT {privilege [,privilege]... | ALL [PRIVILEGES]} ON [TABLE] object TO {grantee [,grantee ]...} [WITH GRANT OPTION] [BY authid-grantor] grantee is: authid | PUBLIC privilege is: SELECT | DELETE | INSERT | UPDATE [(column [,column]...
Syntax Description of GRANT SQL/MX Statements ON [TABLE] object specifies a table, view, or stored procedure on which to grant privileges. When the object is a stored procedure, the only privileges you can specify are ALL PRIVILEGES or EXECUTE. See GRANT EXECUTE Statement on page 2-141. TO {authid [,authid ]... | PUBLIC} specifies one or more users to whom you grant privileges. authid specifies an authorization ID to whom you grant privileges.
Considerations for GRANT SQL/MX Statements Considerations for GRANT Authorization and Availability Requirements To grant a privilege on an object, you must have both that privilege and the right to grant that privilege. That is, the privilege must have been issued to you WITH GRANT OPTION and not revoked. If you lack authority to grant one or more of the specific privileges, the system returns a warning (and does perform the grant of any of the specified privileges that you do have authority to grant).
GRANT EXECUTE Statement SQL/MX Statements • In this example, the super ID grants SELECT and DELETE privileges on a table on behalf of sql.user1: GRANT SELECT, DELETE ON TABLE sales.odetail TO "sql.user3" BY "sql.user1"; GRANT EXECUTE Statement Considerations for GRANT EXECUTE Examples of GRANT EXECUTE The GRANT EXECUTE statement grants privileges for calling a stored procedure in Java (SPJ) to one or more specified users. GRANT EXECUTE ON [PROCEDURE] procedure-ref TO {grantee [,grantee ]...
Considerations for GRANT EXECUTE SQL/MX Statements • SYSTEM specifies the implicit grantor of privileges to the creators of stored procedures. You cannot specify SYSTEM as an authid in a GRANT EXECUTE statement. WITH GRANT OPTION specifies that users of the authorization IDs to whom the EXECUTE privilege is granted have the right to grant EXECUTE privilege to other authorization IDs. BY authid-grantor specifies the authorization ID authid-grantor on whose behalf the grant operation is performed.
Examples of GRANT EXECUTE SQL/MX Statements WITH GRANT OPTION BY 'SYSMGT.ANDY'; The users, 'SYSMGT.BEN' and 'SYSMGT.JASON,' can then issue EXECUTE and WITH GRANT OPTION privileges to other users on the system. They can also execute CALL statements. • The user 'SYSMGT.BEN' grants EXECUTE and WITH GRANT OPTION privileges on spj1 to user 'HR.BETTY': GRANT EXECUTE ON PROCEDURE samdbcat.persnl.spj1 TO 'HR.BETTY' WITH GRANT OPTION; • The user 'HR.
INITIALIZE SQL Statement SQL/MX Statements INITIALIZE SQL Statement Considerations for INITIALIZE SQL Examples of INITIALIZE SQL The INITIALIZE SQL statement prepares a node to run NonStop SQL/MX. INITIALIZE SQL is an SQL/MX extension. INITIALIZE SQL The INITIALIZE SQL statement creates the SQL/MX user metadata (UMD) tables and system metadata (SMD) tables in the system volume configured during installation. If the volume is not audited, INITIALIZE SQL cannot execute.
INSERT Statement SQL/MX Statements INSERT Statement Considerations for INSERT MXCI Examples of INSERT C Examples of INSERT COBOL Examples of INSERT The INSERT statement is a DML statement that inserts rows in a table or view. Embed [ ROWSET FOR INPUT SIZE rowset-size-in ] INSERT INTO table [(target-col-list)] insert-source target-col-list is: colname [,colname]...
INSERT Statement SQL/MX Statements Embed Embed simple-table is: VALUES (row-value-const) [,(row-value-const)]... | VALUES (rowset-value-const) | TABLE table | SELECT [ALL | DISTINCT] select-list FROM table-ref [,table-ref]... | FROM ROWSET [rowset-size] (:array-name [,:array-name]...) [WHERE search-condition | rowset-search-condition] [SAMPLE sampling-method] [TRANSPOSE transpose-set [transpose-set]... [KEY BY key-colname]]...
INSERT Statement SQL/MX Statements (target-col-list) names the columns target-col-list in the table or view in which to insert values. The data type of each target column must be compatible with the data type of its corresponding source value. Within the list, each target column must have the same position as its associated source value, whose position is determined by the columns in the table derived from the evaluation of the query expression (query-expr).
INSERT Statement SQL/MX Statements For the description of value expressions, see Expressions on page 6-37. For the description of query-expr, see SELECT Statement on page 2-174. Embed rowset-value-const There must be at least one rowset expression in the rowset value constructor. See the SQL/MX Programming Manual for C and COBOL for a discussion of semantics when rowsets of different length or rowsets and scalars are used in a rowset value constructor.
Considerations for INSERT SQL/MX Statements ASC | DESC specifies the sort order. The default is ASC. For ordering the source table on a column that can contain null, nulls are considered equal to one another but greater than nonnulls. DEFAULT VALUES specifies a query expression of the form VALUES (DEFAULT, ... ). The value of each DEFAULT is the default value defined in the column descriptor of colname, which is contained in the table descriptor of table.
Considerations for INSERT SQL/MX Statements If the default INSERT_VSBB is set to USER, NonStop SQL/MX does not use statement atomicity. Unless you are inserting only a few records, you should not disable INSERT_VSBB to use statement atomicity, because performance is affected. Perform UPDATE STATISTICS on the tables so that row estimates are correct.
Considerations for INSERT SQL/MX Statements avoid dynamic recompilation because of a change in the transaction mode, consider specifying access options for individual DML statements instead of using SET TRANSACTION. Use of a VALUES Clause for the Source Query Expression If the query expression consists of the VALUES keyword followed by rows of values, each row consists of a list of value expressions or a row subquery (a subquery that returns a single row of column values).
Considerations for INSERT SQL/MX Statements value is longer than the column length, string truncation of nonblank trailing characters returns an error, and the truncated string is not inserted. For variable length, a shorter inserted value is not padded. As is the case for fixed length, if the value is longer than the column length, string truncation of nonblank trailing characters returns an error, and the truncated string is not inserted.
MXCI Examples of INSERT SQL/MX Statements MXCI Examples of INSERT • Insert a row into the CUSTOMER table and supply the value 'A2' for the CREDIT column: INSERT INTO sales.customer VALUES (4777, 'ZYROTECHNIKS', '11211 40TH ST.', 'BURLINGTON', 'MASS.', '01803', 'A2'); --- 1 row(s) inserted. Notice that the column name list is not specified for this INSERT statement.
MXCI Examples of INSERT SQL/MX Statements (200,'PRODUCTION SUPV'), (250,'ASSEMBLER'), (300,'SALESREP'), (400,'SYSTEM ANALYST'), (420,'ENGINEER'), (450,'PROGRAMMER'), (500,'ACCOUNTANT'), (600,'ADMINISTRATOR'), (900,'SECRETARY'); --- 10 row(s) inserted. • The PROJECT table consists of five columns using the data types NUMERIC, VARCHAR, DATE, TIMESTAMP, and INTERVAL. Insert values by using these types: INSERT INTO persnl.
C Examples of INSERT SQL/MX Statements C Examples of INSERT • Execute an INSERT statement: ... EXEC SQL INSERT INTO SALES.CUSTOMER (CUSTNUM, CUSTNAME, STREET, CITY, STATE, POSTCODE) VALUES (1120, 'EXPERT MAILERS', '5769 N.25TH PLACE', 'PHOENIX', 'ARIZONA', '85016'); ... • Use host variables to insert values with an INSERT statement: ... EXEC SQL INSERT INTO SALES.
LOCK TABLE Statement SQL/MX Statements LOCK TABLE Statement Considerations for LOCK TABLE Examples of LOCK TABLE The LOCK TABLE statement locks a table (or the underlying tables of a view) and its indexes, limiting other access to the table and its indexes while your process executes DML statements. See Database Integrity and Locking on page 1-10. LOCK TABLE is an SQL/MX extension. LOCK TABLE table IN {SHARE | EXCLUSIVE} MODE table is the name of the table or view to be locked.
Examples of LOCK TABLE SQL/MX Statements You can use LOCK TABLE with the EXCLUSIVE option to force the use of EXCLUSIVE locks for a subsequent SELECT; however, keep in mind that LOCK TABLE locks the entire table. Unlocking Locked Tables Audited tables do not need to be explicitly unlocked. An audited table can be locked only within a transaction and is automatically unlocked when the transaction ends. You can unlock nonaudited tables by using UNLOCK TABLE.
Examples of LOCK TABLE SQL/MX Statements • Delete all rows of the JOB table that have a job code that is not assigned to any employee: BEGIN WORK; --- SQL operation complete. LOCK TABLE persnl.job IN EXCLUSIVE MODE; --- SQL operation complete. LOCK TABLE persnl.employee IN SHARE MODE; --- SQL operation complete. DELETE FROM persnl.job WHERE jobcode NOT IN (SELECT DISTINCT jobcode FROM persnl.employee); --- 1 row(s) deleted. COMMIT WORK; --- SQL operation complete. UNLOCK TABLE persnl.
PREPARE Statement SQL/MX Statements PREPARE Statement Considerations for PREPARE MXCI Examples of PREPARE C Examples of PREPARE COBOL Examples of PREPARE The PREPARE statement compiles a dynamic SQL statement for later execution with the EXECUTE statement. You can use PREPARE in an MXCI session or in an embedded SQL program. C/COBOL MXCI MXCI C/COBOL The application must supply a name to be associated with the prepared statement.
Considerations for PREPARE SQL/MX Statements C/COBOL GLOBAL | LOCAL specifies the scope of the prepared statement. The default is LOCAL. A GLOBAL prepared statement can be executed within the SQL session. A LOCAL prepared statement can be executed only within the module or compilation unit in which it was prepared. C/COBOL SQL-statement-variable is a value-specification—a host variable with character data type that specifies the SQL statement to prepare (for example, :stmt_buffer).
MXCI Examples of PREPARE SQL/MX Statements If you do not specify a name for a static SQL statement, the SQL 3GL preprocessor assigns the statement a name of the form SQLMX_DEFAULT_STATEMENT_n, where n is an integer incremented by the preprocessor. C/COBOL Statement Names You cannot have more than one statement allocated with the same name within the same scope. For example, this sequence from a C program is not valid: strcpy(stmt1,"STMT1"); EXEC SQL PREPARE :stmt1 FROM :stmt_buffer1; ...
C Examples of PREPARE SQL/MX Statements C Examples of PREPARE • Prepare and execute an INSERT statement: ... strcpy(stmt_buffer,"INSERT INTO SALES.CUSTOMER" " (CUSTNUM, CUSTNAME, STREET, CITY, STATE, POSTCODE)" " VALUES (1120, 'EXPERT MAILERS', '5769 N.25TH PLACE'," " 'PHOENIX', 'ARIZONA', '85016')"); ... EXEC SQL PREPARE ins_cust FROM :stmt_buffer; ... EXEC SQL EXECUTE ins_cust; ... • Prepare and execute an UPDATE statement with dynamic input parameters: ... strcpy(stmt_buffer,"UPDATE SALES.
COBOL Examples of PREPARE SQL/MX Statements COBOL Examples of PREPARE • Prepare and execute an INSERT statement: - • ... MOVE "INSERT INTO SALES.CUSTOMER " (CUSTNUM, CUSTNAME, STREET, CITY, STATE, POSTCODE) " VALUES (1120, 'EXPERT MAILERS', '5769 N.25TH PLACE', " 'PHOENIX', 'ARIZONA', '85016')" TO stmt-buffer. ... EXEC SQL PREPARE ins_cust FROM :stmt-buffer END-EXEC. ... EXEC SQL EXECUTE ins_cust END-EXEC. ... Prepare and execute an UPDATE statement with dynamic input parameters: ...
REGISTER CATALOG Statement SQL/MX Statements REGISTER CATALOG Statement The REGISTER CATALOG statement registers an SQL/MX catalog on a remote node. A catalog is not visible to a remote node until you register it. REGISTER CATALOG catalog ON \node.$volume [RESTRICT | CASCADE] catalog is the ANSI name of the target catalog. It must be visible on the local node. No catalog with the same name can exist on the target node. You cannot register the system catalog. \node.
Examples of REGISTER CATALOG SQL/MX Statements • Suppose that you create a view that references two tables in different catalogs: CREATE VIEW view_catalog.view_schema.MYVIEW4 (v_ordernum, v_partnum) AS SELECT od.ordernum, p.partnum FROM SALES.SALES_SCHEMA.ODETAIL OD INNER JOIN CUST.CUST_SCHEMA.ORDERS P ON od.partnum = p.partnum; If you issue either of these commands: REGISTER CATALOG SALES ON \nodex.$data47; REGISTER CATALOG SALES ON \nodex.
REVOKE Statement SQL/MX Statements REVOKE Statement Considerations for REVOKE Examples of REVOKE The REVOKE statement revokes access privileges for an SQL/MX table, view, or stored procedure from specified users. See also REVOKE EXECUTE Statement on page 2-169 REVOKE [GRANT OPTION FOR] {privilege [,privilege ]... | ALL [PRIVILEGES]} ON [TABLE] object FROM {grantee [,grantee]...
Syntax Description of REVOKE SQL/MX Statements UPDATE Can use UPDATE statement. REFERENCES Can create constraints that reference the object. ALL PRIVILEGES Can have all privileges that apply to the object type. (column [,column]...) names the columns of the object to which the UPDATE or REFERENCES privilege applies. If you specify UPDATE or REFERENCES without column names, the privileges apply to all columns of the table or view.
Considerations for REVOKE SQL/MX Statements clause is the same as if the authid-grantor were to issue the REVOKE directly (without using the BY clause). authid-grantor must be a valid authorization ID and cannot be SYSTEM. Considerations for REVOKE Authorization and Availability Requirements You can revoke only those privileges that you have previously granted to the user. If one or more of the privileges does not exist, the system returns a warning.
REVOKE EXECUTE Statement SQL/MX Statements REVOKE EXECUTE Statement Considerations for REVOKE EXECUTE Examples of REVOKE EXECUTE The REVOKE EXECUTE statement removes privileges for calling a stored procedure in Java (SPJ) from one or more specified users. REVOKE [GRANT OPTION FOR] EXECUTE ON [PROCEDURE] procedure-ref FROM {grantee [,grantee]...} [RESTRICT | CASCADE] [BY authid-grantor] procedure-ref is: [[catalog-name.]schema-name.
Considerations for REVOKE EXECUTE SQL/MX Statements • SYSTEM specifies the implicit grantor of privileges to the creators of stored procedures. You cannot specify SYSTEM as an authid in a REVOKE EXECUTE statement. If you specify RESTRICT, the REVOKE operation fails if there are privilege descriptors that would no longer be valid after the EXECUTE privilege is removed. If you specify CASCADE, any such dependent privilege descriptors are removed as part of the REVOKE EXECUTE operation.
Examples of REVOKE EXECUTE SQL/MX Statements Examples of REVOKE EXECUTE • To revoke the WITH GRANT OPTION privilege on ADJUSTSALARY from user 'HR.BETTY,' the super ID issues this REVOKE EXECUTE statement: REVOKE GRANT OPTION FOR EXECUTE ON PROCEDURE samdbcat.persnl.adjustsalary FROM 'HR.BETTY' BY 'SYSMGT.BEN'; The user 'HR.BETTY' no longer has the WITH GRANT OPTION privilege but still has EXECUTE privilege on ADJUSTSALARY. • To revoke the EXECUTE privilege on ADJUSTSALARY from user 'HR.
ROLLBACK WORK Statement SQL/MX Statements ROLLBACK WORK Statement Considerations for ROLLBACK WORK MXCI Examples of ROLLBACK WORK C Examples of ROLLBACK WORK COBOL Examples of ROLLBACK WORK The ROLLBACK WORK statement undoes all database modifications to audited objects made during the current transaction, releases all locks on audited objects held by the transaction, and ends the transaction. See Transaction Management on page 1-12. ROLLBACK [WORK] WORK is an optional keyword that has no effect.
C Examples of ROLLBACK WORK SQL/MX Statements ROLLBACK WORK; ROLLBACK WORK cancels the inserts that occurred during the transaction and releases the locks held on ORDERS and ODETAIL. C Examples of ROLLBACK WORK • Start a transaction, execute an UPDATE statement, and test SQLSTATE. If the UPDATE is successful, the database changes are committed. Otherwise, the database changes are rolled back. ... char SQLSTATE_OK[6] = "00000"; EXEC SQL BEGIN DECLARE SECTION; char SQLSTATE[6]; ...
SELECT Statement SQL/MX Statements SELECT Statement Considerations for SELECT Considerations for Select List Considerations for SEQUENCE BY Considerations for GROUP BY Considerations for ORDER BY Considerations for UNION MXCI Examples of SELECT C Examples of SELECT COBOL Examples of SELECT Publish/Subscribe Examples of SELECT The SELECT statement is a DML statement that retrieves values from tables, views, derived tables determined by the evaluation of query expressions, or joined tables.
SELECT Statement SQL/MX Statements select-list is: * | select-sublist [,select-sublist]... select-sublist is: corr.* | [corr.
SELECT Statement SQL/MX Statements Embed Embed join-spec is: ON search-condition | rowset-search-condition simple-table is: VALUES (row-value-const) [,(row-value-const)]... | TABLE table | SELECT [ALL | DISTINCT] select-list FROM table-ref [,table-ref]... | FROM ROWSET [rowset-size] (:array-name [,:array-name]...) [WHERE search-condition | rowset-search-condition] [SAMPLE sampling-method] [TRANSPOSE transpose-set [transpose-set]... [KEY BY key-colname]]...
SELECT Statement SQL/MX Statements expression-list is: expression [,expression]... transpose-col-list is: colname | (colname-list) colname-list is: colname [,colname].. Embed ROWSET FOR size-and-index Allowed only if you use rowsets in the SELECT statement. INPUT SIZE rowset-size-in and KEY BY row-id are allowed only if you specify rowset-search-condition in the where clause.
SELECT Statement SQL/MX Statements [ANY N] | [FIRST N] specifies whether to select ANY of the first N rows or the FIRST N sorted rows. You must enclose ANY N or FIRST N in square brackets. [FIRST N] is different from [ANY N] only if you use ORDER BY on any of the columns in the select list to sort the result table of the SELECT statement. N is an unsigned numeric literal with no scale. If N is greater than the number of rows in the table, all rows are returned.
SELECT Statement SQL/MX Statements number of specified host variables, and the data type of each source value must be compatible with the data type of its target host variable. The first value in the result row is assigned to the first host variable, the second value to the second variable, and so on. C/COBOL You can specify rowset host variables in variable-spec. If you specify one rowset host variable, all specified host variables in the INTO list must be rowsets.
SELECT Statement SQL/MX Statements Pub/Sub Pub/Sub Pub/Sub table [[AS] corr [(col-expr-list)]] | STREAM (table) [[AS] corr [(col-expr-list)]] [AFTER LAST ROW] | view [[AS] corr [(col-expr-list)]] | STREAM (view) [[AS] corr [(col-expr-list)]] [AFTER LAST ROW] | (query-expr) [AS] corr [(col-expr-list)] | (delete-statement [RETURN select-list]) [AS] corr [(col-expr-list)] | (update-statement [RETURN select-list]) [AS] corr [(col-expr-list)] | joined-table specifies a table-ref as either a single table, vi
SELECT Statement SQL/MX Statements [AFTER LAST ROW] causes the stream to skip all existing rows in the view and return only rows that are published after the stream’s cursor is opened. Pub/Sub (delete-statement [RETURN select-list]) [AS] corr [(col-expr-list)] enables an application to read and delete rows with a single operation. For the syntax of delete-statement, see the DELETE Statement on page 2-109. RETURN select-list specifies the columns or column expressions returned from the deleted row.
SELECT Statement SQL/MX Statements [OLD.| NEW.]* specifies the row from the OLD or NEW table exposed by the embedded UPDATE. The OLD table refers to column values before the update operation; the NEW table refers to column values after the update operation. If a column has not been updated, the NEW value is equivalent to the OLD value. An implicit NEW.* return list is assumed for an embedded update operation that does not specify a RETURN list.
SELECT Statement SQL/MX Statements ON search-condition specifies a search-condition for the join. Each column reference in search-condition must be a column that exists in either of the two result tables derived from the table references to the left and right of the JOIN keyword. A join of two rows in the result tables occurs if the condition is satisfied for those rows. Embed ON rowset-search-condition specifies a rowset-search-condition for the join.
SELECT Statement SQL/MX Statements table-ref RIGHT JOIN table-ref ON joins rows that satisfy the condition in the ON clause, plus rows from the right table-ref that do not satisfy the condition. The three ways a simple-table can be specified are: VALUES (row-value-const) [,(row-value-const)]... | TABLE table | SELECT [ALL | DISTINCT] select-list FROM table-ref [,table-ref]... | FROM ROWSET [rowset-size] (:array-name [,:array-name]...
SELECT Statement SQL/MX Statements :array-name [,:array-name]... specifies a set of host variable arrays. Each array-name can be used like a column in the rowset-derived table. Each array-name can be any valid host language identifier with a data type that corresponds to an SQL data type. Precede each array-name with a colon (:) within an SQL statement. For more information on rowsets and host variable arrays, see the SQL/MX Programming Manual for C and COBOL.
SELECT Statement SQL/MX Statements SAMPLE sampling-method specifies the sampling method used to select a subset of the intermediate result table of a SELECT statement. Each of the methods uses a sampling size. The three sampling methods—random, first, and periodic—are specified as: RANDOM percent-size directs NonStop SQL/MX to choose rows randomly (each row having an unbiased probability of being chosen) without replacement from the result table.
SELECT Statement SQL/MX Statements TRANSPOSE is an SQL/MX extension. See TRANSPOSE Clause on page 7-25. SEQUENCE BY colname [ASC[ENDING] | DESC[ENDING]] [,colname [ASC[ENDING] | DESC[ENDING]]]... specifies the order in which to sort the rows of the intermediate result table for calculating sequence functions. You must include a SEQUENCE BY clause if you include a sequence function in select-list. Otherwise, NonStop SQL/MX returns an error.
SELECT Statement SQL/MX Statements GROUP BY clause, if one exists, must precede the HAVING clause in the SELECT statement. To comply with ANSI standards, NonStop SQL/MX does not move aggregate predicates from the WHERE clause to a HAVING clause and does not move non-aggregate predicates from the HAVING clause to the WHERE clause, as NonStop SQL/MP does.
SELECT Statement SQL/MX Statements READ UNCOMMITTED specifies that any data accessed need not be from committed rows. You can specify the SQL/MP extension BROWSE instead of READ UNCOMMITTED. READ COMMITTED specifies that any data accessed must be from committed rows. SERIALIZABLE | REPEATABLE READ specifies that the SELECT statement and any concurrent process (accessing the same data) execute as if the statement and the other process had run serially rather than concurrently.
Considerations for SELECT SQL/MX Statements the UNION are the same as the corresponding names in the select list of the left SELECT statement. A column resulting from the UNION of expressions or constants has the name (EXPR). See Considerations for UNION on page 2-196. ORDER BY {colname | colnum} [ASC[ENDING] | DESC[ENDING]] [,{colname | colnum} [ASC[ENDING] | DESC[ENDING]]]... specifies the order in which to sort the rows of the final result table.
Considerations for SELECT SQL/MX Statements Authorization Requirements SELECT requires authority to read all views and tables referred to in the statement, including the underlying tables of views referred to in the statement. Transactions Queries on audited tables must be performed within a transaction unless the SELECT statement uses READ UNCOMMITTED access.
Considerations for SELECT SQL/MX Statements Join Limits Note. HP recommends that you limit the number of tables in a join to a maximum of 64, which includes base tables of views referenced in joins. Queries with joins that involve a larger number of tables are not guaranteed to compile. Object Names in SELECT You can use fully qualified Guardian names only in the FROM clause of a SELECT statement.
Considerations for SELECT SQL/MX Statements overflows. See the run-time limits on streams in the SQL/MX Queuing and Publish/Subscribe Services for details. • • Pub/Sub You cannot use streams with nonaudited tables. Stream access within compound statements is not supported. Joining the Results of an Embedded Delete or Update SQL/MX Release 2.x enables you to join another table with the results of an embedded delete or embedded update.
Considerations for Select List SQL/MX Statements permitted on different columns.
Considerations for GROUP BY SQL/MX Statements The RANDOM function cannot be part of the SEQUENCE BY clause of a sampling method. Considerations for GROUP BY • • • • If you include a GROUP BY clause, the columns you refer to in the select-list must be either grouping columns or arguments of an aggregate (or set) function. For example, if AGE is not a grouping column, you can refer to AGE only as the argument of a function, such as AVG (AGE).
Considerations for UNION SQL/MX Statements Considerations for UNION Suppose that the contributing SELECT statements are named SELECT1 and SELECT2, the contributing tables resulting from the SELECT statements are named TABLE1 and TABLE2, and the table resulting from the UNION operation is named RESULT.
Considerations for UNION SQL/MX Statements ORDER BY Clause and the UNION Operator In a query containing a UNION operator, the ORDER BY clause defines an ordering on the result of the UNION. In this case, the SELECT statement cannot have an individual ORDER BY clause. You can specify an ORDER BY clause only as the last clause following the final SELECT statement (SELECT2 in this example).
Considerations for UNION SQL/MX Statements Access Modes and the UNION Operator In a query containing the UNION operator, if you specify an access option for the second operand before the ORDER BY clause (or if the UNION has no ORDER BY clause) and you do not specify an option for the first operand, the first operand inherits the session’s transaction isolation level setting. If this setting is different from the one you specified for the second operand, NonStop SQL/MX issues a warning.
MXCI Examples of SELECT SQL/MX Statements • Specify the access mode after the ORDER BY clause: SELECT common.isma_no from sdcommon common where common.sec_status='L' UNION SELECT main.isma_no from sdmain main where main.iss_eligible='Y' ORDER BY 1 ascending for browse access; For more about the effect of UNION on SELECT statements, including its effect on performance, see the SQL/MX Query Guide.
MXCI Examples of SELECT SQL/MX Statements • Select data from more than one table by specifying the table names in the FROM clause and specifying the condition for selecting rows of the result in the WHERE clause: SELECT jobdesc, first_name, last_name, salary FROM persnl.employee E, persnl.job J WHERE E.jobcode = J.jobcode AND E.jobcode IN (900, 300, 420); JOBDESC -----------SALESREP SALESREP ... ENGINEER ENGINEER ... SECRETARY SECRETARY ...
MXCI Examples of SELECT SQL/MX Statements EMPLOYEE Table JOB Table 207 420 33000 420 ENGINEER ... ... ... ... ... 568 300 39500 300 SALESREP 3. Drop rows with job codes not equal to 900, 300, or 420. EMPLOYEE Table JOB Table EMPNUM ... JOBCODE ... SALARY JOBCODE JOBDESC 75 300 32000 300 SALESREP ... ... ... ... ... 178 900 28000 900 SECRETARY ... ... ... ... ... 207 420 33000 420 ENGINEER ... ... ... ... ... 568 300 39500 300 SALESREP 4.
MXCI Examples of SELECT SQL/MX Statements JOBCODE ------900 900 ... 300 900 ... 300 420 ... DEPTNUM ------1500 2500 (EXPR) ----------17000.00 18000.00 (EXPR) ----------17000.00 18000.00 3000 2000 19000.00 32000.00 32000.00 32000.00 3200 4000 22000.00 18000.10 33000.10 36000.00 --- 16 row(s) selected. Only job codes 300, 420, and 900 are selected. The minimum and maximum salary for the same job in each department are computed, and the rows are ordered by maximum salary.
MXCI Examples of SELECT SQL/MX Statements • Suppose that the JOB_CORPORATE table has been created from the JOB table by using the CREATE LIKE statement.
C Examples of SELECT SQL/MX Statements GROUP BY OD.ordernum; ORDERNUM (EXPR) ---------- --------------------200490 1030.00 300350 71025.00 300380 28560.00 --- 3 row(s) selected. The price for the total quantity ordered is computed for each order number. • Show employees, their salaries, and the percentage of the total payroll that their salaries represent.
COBOL Examples of SELECT SQL/MX Statements ... EXEC SQL SELECT SALARY INTO :hv_salary INDICATOR :ihv_salary FROM EMPLOYEE WHERE EMPNUM = 1234; ... COBOL Examples of SELECT • Use a single-row SELECT statement: EXEC SQL SELECT LAST_NAME, FIRST_NAME INTO :hv-lname, :hv-fname FROM EMPLOYEE WHERE EMPNUM = 1234 END-EXEC. • This example uses an indicator variable: EXEC SQL BEGIN DECLARE SECTION END-EXEC. ... 01 ihv-salary PIC S9(4) comp. 01 hv-salary PIC 9(6)V9(2) comp.
Publish/Subscribe Examples of SELECT SQL/MX Statements For more information, see ordered streams in SQL/MX Queuing and Publish/Subscribe Services. • These examples show join operations with a base table and a stream: SELECT * FROM tab1, (SELECT * FROM STREAM(tab2)) AS tab2 WHERE tab1.a = tab2.a; SELECT * FROM STREAM(tab1), tab2 WHERE tab1.a = tab2.a; The two preceding queries yield identical results.
SET Statement SQL/MX Statements SET Statement Considerations for SET statement The SET statement is used with BEFORE triggers to assign values to variables representing columns in the SQL/MX table to be modified by the triggering action. SET correlation-name.column-name = value-expression; correlation-name is the name of the new row that correlates to the row to be modified. column-name is the name of the new column that correlates to the column to be modified.
SET CATALOG Statement SQL/MX Statements SET CATALOG Statement Considerations for SET CATALOG MXCI Examples of SET CATALOG C Example of SET CATALOG COBOL Example of SET CATALOG The SET CATALOG statement sets the default logical catalog for unqualified schema names for the current SQL session. Embed The SET CATALOG statement sets the default catalog for unqualified schema names in all dynamic statements within the control flow scope of an embedded SQL program for the current SQL session.
C Example of SET CATALOG SQL/MX Statements C Example of SET CATALOG • Set the default catalog name with an SQL string literal: EXEC SQL SET CATALOG 'mycatalog'; • Set the default catalog name with an SQL identifier: EXEC SQL SET CATALOG mycatalog; COBOL Example of SET CATALOG • Set the default catalog name with an SQL string literal: EXEC SQL SET CATALOG 'mycatalog' END-EXEC. • Set the default catalog name with an SQL identifier: EXEC SQL SET CATALOG mycatalog END-EXEC.
SET MPLOC Statement SQL/MX Statements SET MPLOC Statement Considerations for SET MPLOC Examples of SET MPLOC The SET MPLOC statement sets the default NonStop operating system volume and subvolume for physical object names for the current SQL session. Embed The SET MPLOC statement sets the default volume and subvolume for physical object names in all dynamic statements within the control flow scope of an embedded SQL program for the current SQL session. SET MPLOC is an SQL/MX extension. SET MPLOC [\node.
SET NAMETYPE Statement SQL/MX Statements SET NAMETYPE Statement Considerations for SET NAMETYPE Examples of SET NAMETYPE The SET NAMETYPE statement sets the NAMETYPE attribute value for the current SQL session. Embed The SET NAMETYPE statement sets the NAMETYPE attribute for all dynamic statements within the control flow scope of an embedded SQL program for the current SQL session. SET NAMETYPE is an SQL/MX extension.
SET SCHEMA Statement SQL/MX Statements SET SCHEMA Statement Considerations for SET SCHEMA MXCI Examples of SET SCHEMA C Example of SET SCHEMA COBOL Example of SET SCHEMA The SET SCHEMA statement sets the default logical schema (and optionally the catalog) for unqualified object names for the current SQL session.
MXCI Examples of SET SCHEMA SQL/MX Statements MXCI Examples of SET SCHEMA • Set the default schema name: SET SCHEMA myschema; • Set the default catalog and schema name by specifying both: SET SCHEMA mycatalog.myschema; C Example of SET SCHEMA • Set the default catalog and schema with an SQL string literal: EXEC SQL SET SCHEMA 'prodcat.persnl'; • Set the default catalog and schema with an SQL identifier: EXEC SQL SET SCHEMA prodcat.
SET TABLE TIMEOUT Statement SQL/MX Statements SET TABLE TIMEOUT Statement Considerations for SET TABLE TIMEOUT MXCI Examples of SET TABLE TIMEOUT C Examples of SET TABLE TIMEOUT The SET TABLE TIMEOUT statement sets a dynamic timeout value for a lock timeout or a stream timeout in the environment of the current session. The dynamic timeout value overrides the compiled static timeout value in the execution of subsequent DML statements. You can use SET TABLE TIMEOUT from MXCI or in embedded SQL programs.
SET TABLE TIMEOUT Statement SQL/MX Statements TIMEOUT value specifies that value is for a lock timeout. If value elapses before a DML statement can acquire a lock on a table, the statement fails, and NonStop SQL/MX returns file-system error 73 (disk file or record is locked). The value overrides any compiled values, such as those previously set by a CONTROL TABLE statement with the TIMEOUT option. STREAM TIMEOUT value specifies that value is for a stream timeout.
Considerations for SET TABLE TIMEOUT SQL/MX Statements Considerations for SET TABLE TIMEOUT • • • Embed • Embed • Embed • The SET TABLE TIMEOUT statement does not perform any security checks on a table. A CONTROL statement is a directive that affects the compilation of subsequent DML statements but produces no executable code. A SET TABLE TIMEOUT statement, however, produces executable code and has no effect on the compilation of other statements.
C Examples of SET TABLE TIMEOUT SQL/MX Statements • Reset all the lock timeout settings.
SET TRANSACTION Statement SQL/MX Statements /* Set timeout value for ORDERS table from host variable */ EXEC SQL SET TABLE orders TIMEOUT hv_timeout; SET TRANSACTION Statement Considerations for SET TRANSACTION MXCI Examples of SET TRANSACTION C Examples of SET TRANSACTION COBOL Examples of SET TRANSACTION The SET TRANSACTION statement is used to set attributes for the next transaction (and only the next transaction).
SET TRANSACTION Statement SQL/MX Statements isolation-level specifies the level of data consistency defined for the transaction and the degree of concurrency the transaction has with other transactions that use the same data. The default isolation level of a transaction is determined according to the rules specified in Isolation Level on page 10-45. access-mode specifies the type of data access that the transaction requires, depending on whether changes are made to the database by the transaction.
Considerations for SET TRANSACTION SQL/MX Statements Considerations for SET TRANSACTION Implicit Transactions Most DML statements are transaction-initiating—the system automatically initiates a transaction when the statement begins executing.
MXCI Examples of SET TRANSACTION SQL/MX Statements MXCI Examples of SET TRANSACTION • Set the isolation level of a transaction that performs deletes, inserts, and updates: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; --- SQL operation complete. BEGIN WORK; --- SQL operation complete. DELETE FROM persnl.employee WHERE empnum = 23; --- 1 row(s) deleted. INSERT INTO persnl.employee (empnum, first_name, last_name, deptnum, salary) VALUES (50, 'JERRY','HOWARD', 1000, 137000.00); --- 1 row(s) inserted.
SIGNAL SQLSTATE Statement SQL/MX Statements SIGNAL SQLSTATE Statement The SIGNAL statement is used with triggers. It allows a trigger execution to raise an exception that causes both the triggered and triggering statements to fail. The SIGNAL statement sends an SQLSTATE and error text. SIGNAL SQLSTATE quoted_sqlstate (quoted_string_expr); quoted_sqlstate is the five-digit SQLSTATE to be passed to SIGNAL. quoted_string_expr is a string expression.
TABLE Statement SQL/MX Statements TABLE Statement Considerations for TABLE Examples of TABLE The TABLE statement is equivalent to the query specification SELECT * FROM table. TABLE table table names the user table or view. Considerations for TABLE Relationship to SELECT Statement The result of the TABLE statement is one form of a simple-table, which is part of the definition of a table reference within a SELECT statement. See SELECT Statement on page 2-174.
UNLOCK TABLE Statement SQL/MX Statements UNLOCK TABLE Statement Considerations for UNLOCK TABLE Examples of UNLOCK TABLE The UNLOCK TABLE statement releases locks owned by MXCI on a nonaudited SQL/MP table or on underlying nonaudited SQL/MP tables of a view. UNLOCK TABLE does not affect audited tables. Ending a transaction unlocks an audited table. UNLOCK TABLE is an SQL/MX extension. UNLOCK TABLE table table is the name of the table or view to unlock. See Database Object Names on page 6-12.
UNREGISTER CATALOG Statement SQL/MX Statements UNREGISTER CATALOG Statement The UNREGISTER CATALOG statement removes an empty SQL/MX catalog reference from a node. UNREGISTER CATALOG catalog FROM \node [RESTRICT | CASCADE] catalog is the ANSI name of the target catalog. It must be visible on the local node. It must not include any objects. No object in the catalog can be dependent on another object. \node is the name of the target node, local or remote.
UPDATE Statement SQL/MX Statements UPDATE Statement Considerations for UPDATE MXCI Examples of UPDATE C Examples of UPDATE COBOL Examples of UPDATE Publish/Subscribe Examples of DELETE The UPDATE statement is a DML statement that updates data in a row or rows in a table or updatable view. Updating rows in a view updates the rows in the table on which the view is based.
UPDATE Statement SQL/MX Statements Embed Positioned UPDATE is: UPDATE table SET set-clause [,set-clause]... C/COBOL WHERE CURRENT OF {cursor-name | ext-cursor-name} set-clause is: column-name = {expression |rowset-expression | NULL} Embed ROWSET FOR INPUT SIZE rowset-size-in Allowed only if you specify rowset-search-condition in the WHERE clause. rowset-size-in restricts the size of the input rowset to the specified size.
UPDATE Statement SQL/MX Statements value of the update source expression (or NULL). The data type of each target column must be compatible with the data type of its source value. Embed If you include a rowset search condition in the WHERE clause, you can use a rowset expression in set-clause, but it is not required. If the rowset sizes are different in the SET and WHERE clause, the smaller of the two sizes is used, and the remaining entries in the larger rowset are ignored.
UPDATE Statement SQL/MX Statements NULL can also specify the value of the update source. Pub/Sub SET ON ROLLBACK set-roll-clause [,set-roll-clause]... causes one or more columns to be updated when the execution of the UPDATE statement causes its containing transaction to be rolled back. set-roll-clause sets the specified column to a particular value. For each set-roll-clause, the value of the specified target column-name is replaced by the value of the update source expression.
UPDATE Statement SQL/MX Statements described above for expression apply to each array element in the rowsetexpression. For details on using host variables and rowsets, see the SQL/MX Programming Manual for C and COBOL. WHERE search-condition specifies a search-condition that selects rows to update. Within the search-condition, columns being compared are also being updated in the table or view. See Search Condition on page 6-102.
Considerations for UPDATE SQL/MX Statements The default access option is the isolation level of the containing transaction, which is determined according to the rules specified in Isolation Level on page 10-45. C/COBOL WHERE CURRENT OF {cursor-name | ext-cursor-name} specifies the name of a cursor (or extended cursor) positioned at the row to update. If you specify cursor-name for an audited table or view, the UPDATE must execute within a transaction that also includes the FETCH for the row.
Considerations for UPDATE SQL/MX Statements Embed Positioned UPDATE With AUTOCOMMIT If you are using the positioned form of UPDATE, check that AUTOCOMMIT is set to OFF before you open a cursor. Otherwise, NonStop SQL/MX commits the transaction after each UPDATE statement and closes the cursor. Consequently, you might get rows fetched by your cursor that are part of different transactions.
Considerations for UPDATE SQL/MX Statements In addition, a candidate row from a view created with the WITH CHECK OPTION must satisfy the view selection criteria. The selection criteria are specified in the WHERE clause of the AS query-expression clause in the CREATE VIEW statement. Reporting of Updates When an UPDATE completes successfully, NonStop SQL/MX reports the number of times rows were updated during the operation.
Considerations for UPDATE SQL/MX Statements In an SQL/MP entry-sequenced table, a value that updates a variable-length character column must be the same length as the value it replaces. Audited and Nonaudited Tables SQL/MX tables must be audited. You can run NonStop SQL/MX against nonaudited SQL/MP tables. The Transaction Management Facility (TMF) product works only on audited tables, so a transaction does not protect operations on nonaudited tables.
Considerations for UPDATE SQL/MX Statements Suppose you have a table with two rows: >>select * from =TAB1; K1 K2 V3 ---- ---- -----------------------------------------------------0001 AAAA 0001 BBBB If you perform this statement: EXEC SQL SELECT * INTO :hv_k1 , :hv_k2 , :hv_v3 FROM (UPDATE =TAB1 SET v3 = 'ABCD' WHERE k1 ='0001' SKIP CONFLICT ACCESS ) AS PIPO READ UNCOMMITTED ACCESS ; Both rows would satisfy the selection criteria, so both rows could be updated.
MXCI Examples of UPDATE SQL/MX Statements NonStop SQL/MX updates both rows. MXCI Examples of UPDATE • Update a single row of the ORDERS table that contains information about order number 200300 and change the delivery date: UPDATE sales.orders SET deliv_date = DATE '1998-05-02' WHERE ordernum = 200300; • Update several rows of the CUSTOMER table: UPDATE sales.
C Examples of UPDATE SQL/MX Statements VALUES (50, 'JERRY','HOWARD', 1000, 137000.00); --- 1 row(s) inserted. UPDATE persnl.dept SET manager = 50 WHERE deptnum = 1000; --- 1 row(s) updated. COMMIT WORK; --- SQL operation complete. This transaction uses SERIALIZABLE access, which provides maximum data consistency.
Publish/Subscribe Examples of UPDATE SQL/MX Statements INTO SQL DESCRIPTOR 'out_sqlda' END-EXEC. ... PERFORM UNTIL SQLSTATE NOT = SQLSTATE-OK * Retrieve and test values in the descriptor area ... EXEC SQL UPDATE CUSTOMER SET CREDIT = :new-default WHERE CURRENT OF cursor1 END-EXEC. EXEC SQL FETCH cursor1 INTO SQL DESCRIPTOR 'out_sqlda' END-EXEC. END-PERFORM. Publish/Subscribe Examples of UPDATE Suppose that these SQL/MP tables and index (and the metadata mappings) have been created: CREATE TABLE $db.
UPDATE STATISTICS Statement SQL/MX Statements UPDATE STATISTICS Statement Considerations for UPDATE STATISTICS Examples of UPDATE STATISTICS The UPDATE STATISTICS statement updates the histogram statistics for one or more groups of columns within a table. These statistics are used to devise optimized access plans. In addition to histogram statistics, UPDATE STATISTICS generates physical statistics (index level, nonempty block count, and EOF) for partitions of SQL/MX tables.
UPDATE STATISTICS Statement SQL/MX Statements CLEAR deletes some or all histograms for the table table. Use this option when new applications no longer use certain histogram statistics. If you do not specify column-group-list, all histograms for table are deleted. If you specify column-group-list, only columns in the group list are deleted.
UPDATE STATISTICS Statement SQL/MX Statements For more information about specifying columns, see Generating and Clearing Statistics for Columns on page 2-244. EVERY COLUMN The EVERY COLUMN keyword indicates that histogram statistics are to be generated for each individual column of table and any multicolumns that make up the primary key and indexes. For example, table has columns A, B, C, D defined, where A, B, C compose the primary key.
UPDATE STATISTICS Statement SQL/MX Statements If you specify the SAMPLE clause without additional options, a row sample is used to read 2 percent of the rows in the table, with a maximum of 2 million rows. If you specify the ROWCOUNT option, NonStop SQL/MX reads 2 percent of c, with a maximum of 2 million rows. If you do not specify the SAMPLE clause, table has fewer rows than specified, or the sample size is greater than the system limit. NonStop SQL/MX reads all rows from table.
Considerations for UPDATE STATISTICS SQL/MX Statements See SAMPLE Clause on page 7-8. Considerations for UPDATE STATISTICS Physical Statistics Physical statistics (index level, nonempty block count, and EOF) are generated for UPDATE STATISTICS statements unless you use the CLEAR option. Using Statistics Use UPDATE STATISTICS to collect and save statistics on columns. The SQL compiler uses histogram statistics to determine the selectivity of predicates, indexes, and tables.
Considerations for UPDATE STATISTICS SQL/MX Statements periods, and timeout errors do not occur. If the lock is held for a longer time, multiple retry attempts help to complete concurrent operations with minimum timeout interruption. Generating and Clearing Statistics for Columns To generate statistics for particular columns, name each column, or name the first and last columns of a sequence of columns in the table. For example, suppose that a table has consecutive columns CITY, STATE, ZIP.
Considerations for UPDATE STATISTICS SQL/MX Statements Sample Option When you use the SAMPLE option, the UPDATE STATISTICS statement estimates the unique entry counts for each column for each histogram interval. The estimated unique entry counts tend to be more accurate for those columns that have fewer unique entries than the sampled number of rows.
Examples of UPDATE STATISTICS SQL/MX Statements Managing SQL/MP Histograms Before you drop an SQL/MP table, perform UPDATE STATISTICS with the CLEAR option. Otherwise, orphan histograms for that table are left on the system. However, if you drop an SQL/MP table before performing this step, use UPDATE STATISTICS with the CLEAR option to remove orphan tables: 1. Create a dummy table in the catalog where the primary partition of the table you dropped resided: CREATE TABLE trash (a int); 2.
Examples of UPDATE STATISTICS SQL/MX Statements • Suppose that a construction company has an ADDRESS table of potential sites and a DEMOLITION_SITES table that contains some of the columns of the ADDRESS table. The primary key is ZIP. Join these two tables on two of the columns in common: SELECT COUNT(AD.number), AD.street, AD.city, AD.zip, AD.state FROM address AD, demolition_sites DS WHERE AD.zip = DS.zip AND AD.type = DS.type GROUP BY AD.street, AD.city, AD.zip, AD.
VALUES Statement SQL/MX Statements VALUES Statement Considerations for VALUES Examples of VALUES The VALUES statement starts with the VALUES keyword followed by a sequence of row value constructors, each of which is enclosed in parentheses. It displays the results of the evaluation of the expressions and the results of row subqueries within the row value constructors. VALUES (row-value-constructor) [,(row-value-constructor)]...
Examples of VALUES SQL/MX Statements • This VALUES statement displays the results of the expressions and the row subquery in the lists: VALUES ('a','b',UPSHIFT('c')), ((SELECT jobdesc FROM job WHERE jobcode=300),'d',NULL); (EXPR) -----------------a SALESREP (EXPR) -----b d (EXPR) -----C ? --- 2 row(s) selected.
Examples of VALUES SQL/MX Statements HP NonStop SQL/MX Reference Manual—540440-003 2 -250
3 Embedded-Only SQL/MX Statements This section describes the syntax and semantics of NonStop SQL/MX statements that you can embed only in programs written in C, C++, COBOL, or Java. In NonStop SQL/MX Release 2.x, mixing embedded SQL calls to NonStop SQL/MP and NonStop SQL/MX from the same application process is not supported. You cannot run these statements, or specific forms of these statements, in MXCI: C/COBOL ALLOCATE CURSOR Statement on page 3-3 Allocates an SQL cursor.
Embedded-Only SQL/MX Statements DECLARE SCHEMA Declaration on page 3-32 Sets default schema for unqualified object names in static SQL statements within a compilation unit. DESCRIBE Statement on page 3-33 Uses an SQLDA to return descriptions of output variables (usually SELECT columns) and input parameters for a prepared statement. END DECLARE SECTION Declaration on page 3-36 Designates the end of a Declare Section. EXEC SQL Directive on page 3-37 Begins an embedded SQL statement or declaration.
Embedded-Only SQL/MX Statements ALLOCATE CURSOR Statement ALLOCATE CURSOR Statement Considerations for ALLOCATE CURSOR C Examples of ALLOCATE CURSOR COBOL Examples of ALLOCATE CURSOR C/COBOL The ALLOCATE CURSOR statement is a dynamic SQL statement used to define an extended cursor based on a statement already prepared for the cursor specification. It allows applications to dynamically create an unlimited number of cursors. Use ALLOCATE CURSOR only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements Considerations for ALLOCATE CURSOR CURSOR statement is functionally equivalent to the DECLARE CURSOR statement. Considerations for ALLOCATE CURSOR Cursor Names You cannot have more than one cursor allocated with the same name within the same scope.
Embedded-Only SQL/MX Statements COBOL Examples of ALLOCATE CURSOR COBOL Examples of ALLOCATE CURSOR This example uses extended cursor and statement names in the PREPARE and ALLOCATE CURSOR statements: ... ACCEPT in-curspec. ... EXEC SQL PREPARE :curspec FROM :in-curspec END-EXEC. ... EXEC SQL ALLOCATE :extcur CURSOR FOR :curspec END-EXEC. ... Publish/Subscribe Examples of ALLOCATE CURSOR This example uses the WITH HOLD clause with ALLOCATE CURSOR: ...
Embedded-Only SQL/MX Statements ALLOCATE DESCRIPTOR Statement ALLOCATE DESCRIPTOR Statement Considerations for ALLOCATE DESCRIPTOR C Examples of ALLOCATE DESCRIPTOR COBOL Examples of ALLOCATE DESCRIPTOR C/COBOL The ALLOCATE DESCRIPTOR statement allocates a named SQL descriptor area used for storing information necessary for the execution of dynamic SQL statements. Use ALLOCATE DESCRIPTOR only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements C Examples of ALLOCATE DESCRIPTOR hvdouble1 = 1.0E-76; EXEC SQL PREPARE insert_q FROM :insert_buf; printf("SQLCODE after prepare insert_q - 1 is %d\n", SQLCODE); Exec SQL execute insert_q using :hvdouble1; printf("SQLCODE after insert - 3 is %d \n", SQLCODE); Defining Values in the Descriptor Area All values in all items of the descriptor area are initially undefined. To define values, use a DESCRIBE statement or explicitly set values with a SET DESCRIPTOR statement.
Embedded-Only SQL/MX Statements COBOL Examples of ALLOCATE DESCRIPTOR COBOL Examples of ALLOCATE DESCRIPTOR • This example uses an SQL string literal as the descriptor name: MOVE 1 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'in_sqlda' WITH MAX :desc-max END-EXEC. • This example uses a host variable as the descriptor name: ... EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 desc-name PIC X(20). 01 desc-max S9(9) comp. ... EXEC SQL END DECLARE SECTION END-EXEC. ... MOVE "in_sqlda" TO desc-name.
Embedded-Only SQL/MX Statements BEGIN DECLARE SECTION Declaration BEGIN DECLARE SECTION Declaration C/COBOL BEGIN DECLARE SECTION is a preprocessor directive that begins SQL declarations in a host program. SQL declarations are used to define host variables to be used in SQL/MX statements—for example, to transfer data to and from a database. Use BEGIN DECLARE SECTION only in embedded SQL programs in C or COBOL. BEGIN DECLARE SECTION See END DECLARE SECTION Declaration on page 3-36.
Embedded-Only SQL/MX Statements COBOL Examples of BEGIN DECLARE SECTION COBOL Examples of BEGIN DECLARE SECTION • This example shows a declaration section: EXEC SQL 01 length 01 data EXEC SQL • BEGIN DECLARE SECTION END-EXEC. pic 9(4)comp. pic x(10). END DECLARE SECTION END-EXEC. This example shows a declaration section that uses an INVOKE directive to declare a record description of a table: EXEC SQL BEGIN DECLARE SECTION END-EXEC. EXEC SQL INVOKE SALES.PARTS END-EXEC.
CLOSE Statement Embedded-Only SQL/MX Statements CLOSE Statement Considerations for CLOSE C Examples of CLOSE COBOL Examples of CLOSE C/COBOL The CLOSE statement closes a cursor in a host program and releases the result table established by the OPEN statement for the cursor. The COMMIT WORK statement or ROLLBACK WORK statement also closes all open cursors in a host program and releases all result tables. In dynamic SQL, the cursor name is provided at execution time.
Embedded-Only SQL/MX Statements C Examples of CLOSE Reusing a Cursor After CLOSE executes, the result table for the cursor (the output that results from the execution of the SELECT that specifies the cursor) no longer exists. To use the same cursor again, you must reopen it with an OPEN statement. Effect on Locks Closing a cursor does not affect locks. Locks on audited tables are released when the containing transaction completes or aborts; locks on nonaudited tables must be released with UNLOCK TABLE.
Embedded-Only SQL/MX Statements COBOL Examples of CLOSE COBOL Examples of CLOSE • Declare and open a cursor, fetch a row of retrieved data, then close the cursor. Note that in an actual program you would include processing the data in the host variables hostvar1, hostvar2, and hostvar3, and looping back to fetch the next row provided by the cursor. ... EXEC SQL DECLARE cursor1 CURSOR FOR SELECT COL1, COL2, COL3 FROM SALES.PARTS WHERE COL1 >= :hostvar1 ORDER BY COL1 READ UNCOMMITTED ACCESS END-EXEC.
Embedded-Only SQL/MX Statements Compound (BEGIN...END) Statement Compound (BEGIN...END) Statement Considerations for Compound Statement C Examples of Compound Statement C/COBOL A compound statement is an embedded SQL statement that groups other embedded SQL statements together. A compound statement is an SQL/MX extension that you use only in embedded SQL programs in C or COBOL. BEGIN SQL-statement;[SQL-statement;]... END; SQL-statement;[SQL-statement;]...
Embedded-Only SQL/MX Statements C Examples of Compound Statement SELECT Statements Within Compound Statements Every SELECT statement within a BEGIN…END statement should return at least one row. If a SELECT statement within a BEGIN..END statement does not return at least one row, further execution of the compound statement stops and NonStop SQL/MX issues a warning or an error. A warning is displayed if no updates occurred before the SELECT statement that did not return a row.
Embedded-Only SQL/MX Statements DEALLOCATE DESCRIPTOR Statement DEALLOCATE DESCRIPTOR Statement C Examples of DEALLOCATE DESCRIPTOR COBOL Examples of DEALLOCATE DESCRIPTOR C/COBOL The DEALLOCATE DESCRIPTOR statement deallocates an SQL descriptor area used for storing information necessary for the execution of dynamic SQL statements. The descriptor area was previously allocated with the ALLOCATE DESCRIPTOR statement. Use DEALLOCATE DESCRIPTOR only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements C Examples of DEALLOCATE DESCRIPTOR C Examples of DEALLOCATE DESCRIPTOR • This example uses an SQL string literal as the descriptor name: EXEC SQL DEALLOCATE DESCRIPTOR 'in_sqlda'; • This example uses a host variable as the descriptor name: ... EXEC SQL BEGIN DECLARE SECTION; char desc_name[20]; long desc_max; ... EXEC SQL END DECLARE SECTION; ... strcpy(desc_name, "in_sqlda"); ... desc_max = 10; EXEC SQL ALLOCATE DESCRIPTOR :desc_name WITH MAX :desc_max; ...
Embedded-Only SQL/MX Statements DEALLOCATE PREPARE Statement DEALLOCATE PREPARE Statement Considerations for DEALLOCATE PREPARE C Examples of DEALLOCATE PREPARE COBOL Examples of DEALLOCATE PREPARE C/COBOL The DEALLOCATE PREPARE statement deallocates a prepared SQL statement in a host program. It releases resources held by the prepared statement and allows you to reuse the name of the statement. Use DEALLOCATE PREPARE only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements Considerations for DEALLOCATE PREPARE Considerations for DEALLOCATE PREPARE Cursor Specification When you deallocate a prepared statement, any cursor associated with that statement is canceled. C Examples of DEALLOCATE PREPARE • Prepare, execute, and deallocate an UPDATE statement with dynamic input parameters: ... strcpy(stmt_buffer,"UPDATE SALES.CUSTOMER" " SET CREDIT = ?" " WHERE CUSTNUM = CAST(? AS NUMERIC(4) UNSIGNED)") ...
Embedded-Only SQL/MX Statements COBOL Examples of DEALLOCATE PREPARE COBOL Examples of DEALLOCATE PREPARE • Prepare, execute, and deallocate an UPDATE statement with dynamic input parameters: ... MOVE "UPDATE SALES.CUSTOMER SET CREDIT = ?" & " WHERE CUSTNUM = CAST(? AS NUMERIC(4) UNSIGNED)" & x"00" TO stmt-buffer. ... EXEC SQL PREPARE upd_cust FROM :stmt-buffer END-EXEC. ... * Input values for parameters into host variables ACCEPT in-credit. ... ACCEPT in-custnum. ...
Embedded-Only SQL/MX Statements DECLARE CATALOG Declaration DECLARE CATALOG Declaration The DECLARE CATALOG declaration is a compiler directive that sets the default catalog for unqualified schema names in static SQL statements that follow the declaration within a compilation unit. The DECLARE SCHEMA declaration sets the default schema name. See DECLARE SCHEMA Declaration on page 3-32. DECLARE CATALOG is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DECLARE CURSOR Declaration DECLARE CURSOR Declaration Considerations for DECLARE CURSOR C Examples of DECLARE CURSOR COBOL Examples of DECLARE CURSOR Publish/Subscribe Examples of DECLARE CURSOR C/COBOL The DECLARE CURSOR declaration or statement specifies a cursor in a host program. It associates the name of the cursor with a query expression that specifies the rows to be retrieved.
Embedded-Only SQL/MX Statements DECLARE CURSOR Declaration See SELECT Statement on page 2-174 for the syntax of query-expression. cursor-name is an SQL identifier—the name of the cursor being declared. The name is unique within the containing module or compilation unit. The maximum length of a cursor name is 128 characters. See Identifiers on page 6-52. Pub/Sub WITH HOLD | WITHOUT HOLD specifies whether (WITH) or not (WITHOUT) an application keeps cursors open across transaction boundaries.
Embedded-Only SQL/MX Statements Considerations for DECLARE CURSOR GLOBAL | LOCAL specifies the scope of the value specification for an ext-cursor-name. The default is LOCAL. The scope of a GLOBAL cursor is the SQL session. The scope of a LOCAL cursor is the module or compilation unit in which DECLARE CURSOR appears. ext-statement-name is a value specification—a character literal or host variable with character data type.
Embedded-Only SQL/MX Statements • • C Examples of DECLARE CURSOR If the READONLY_CURSOR attribute is set to TRUE (the default setting), you must declare cursors with the FOR UPDATE clause for the named columns or all columns to be updatable. (This READONLY_CURSOR setting improves cursor performance.
Embedded-Only SQL/MX Statements • COBOL Examples of DECLARE CURSOR This SQL statement defines a dynamic updatable cursor: EXEC SQL BEGIN DECLARE SECTION; char query[50]; ... EXEC SQL END DECLARE SECTION; ... strcpy(query,"SELECT COL1, COL2, COL3, COL4" " FROM SALES.PARTS"); ... EXEC SQL PREPARE curspec FROM :query; ...
Embedded-Only SQL/MX Statements Publish/Subscribe Examples of DECLARE CURSOR Publish/Subscribe Examples of DECLARE CURSOR Suppose that these SQL/MP tables and index (and the metadata mappings) have been created: CREATE TABLE $db.dbtab.tab1 (a int, b int, c int); CREATE TABLE $db.dbtab.tab2 (a int, b int, c int); CREATE INDEX $db.dbtab.itab1 ON tab1(b, c); CREATE SQLMP ALIAS cat.sch.tab1 $db.dbtab.tab1; CREATE SQLMP ALIAS cat.sch.tab2 $db.dbtab.
Embedded-Only SQL/MX Statements DECLARE MPLOC Declaration DECLARE MPLOC Declaration Considerations for DECLARE MPLOC C Examples of DECLARE MPLOC COBOL Examples of DECLARE MPLOC The DECLARE MPLOC declaration is a compiler directive that sets the default volume and subvolume for unqualified Guardian physical object names in static SQL statements that follow the declaration within a compilation unit. C/COBOL DECLARE MPLOC is used by the preprocessor when the INVOKE directive is not fully qualified.
Considerations for DECLARE MPLOC Embedded-Only SQL/MX Statements Considerations for DECLARE MPLOC C/COBOL Preprocessor and INVOKE Directive The way you specify DECLARE MPLOC affects whether the preprocessor preserves or overrides the INVOKE directive: DECLARE MPLOC is specified as... INVOKE Directive Preprocessor Action \node.$vol.subvol.filename table is not fully qualified and does not contain \node. Overrides the INVOKE directive with DECLARE MPLOC names. \node.$vol.subvol.
Embedded-Only SQL/MX Statements COBOL Examples of DECLARE MPLOC COBOL Examples of DECLARE MPLOC • Set the default volume and subvolume: EXEC SQL DECLARE MPLOC '$MYVOL.MYSUBVOL' END-EXEC.
Embedded-Only SQL/MX Statements DECLARE NAMETYPE Declaration DECLARE NAMETYPE Declaration The DECLARE NAMETYPE declaration is a compiler directive that sets the default NAMETYPE attribute value to ANSI or NSK for static SQL statements that follow the declaration within a compilation unit. C/COBOL DECLARE NAMETYPE is used by the preprocessor when the INVOKE directive is not fully qualified. DECLARE NAMETYPE is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DECLARE SCHEMA Declaration DECLARE SCHEMA Declaration The DECLARE SCHEMA declaration is a compiler directive that sets the default schema (and optionally, the catalog) for unqualified object names in static SQL statements that follow the declaration within a compilation unit. The DECLARE CATALOG declaration also sets the default catalog. See DECLARE CATALOG Declaration on page 3-21. DECLARE SCHEMA is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DESCRIBE Statement DESCRIBE Statement C Examples of DESCRIBE COBOL Examples of DESCRIBE C/COBOL The DESCRIBE statement obtains information, including data types of columns, about dynamic input and output parameters contained in a prepared statement. A parameter is a placeholder for a value to be supplied when the statement executes.
Embedded-Only SQL/MX Statements C Examples of DESCRIBE GLOBAL | LOCAL specifies the scope of the prepared statement. The default is LOCAL. A GLOBAL prepared statement can be described and executed within the SQL session. A LOCAL prepared statement can be described and executed only within the module or compilation unit in which it was prepared.
Embedded-Only SQL/MX Statements ... EXEC SQL ... desc_max EXEC SQL desc_max EXEC SQL ... EXEC SQL EXEC SQL ...
Embedded-Only SQL/MX Statements END DECLARE SECTION Declaration END DECLARE SECTION Declaration C/COBOL END DECLARE SECTION is a preprocessor directive that ends SQL declarations in a host program. SQL declarations are used to define host variables to be used in SQL/MX statements—for example, to transfer data to and from a database. Use END DECLARE SECTION only in embedded SQL programs in C or COBOL. END DECLARE SECTION See BEGIN DECLARE SECTION Declaration on page 3-9.
Embedded-Only SQL/MX Statements EXEC SQL Directive EXEC SQL Directive C/COBOL EXEC SQL is a preprocessor directive that begins an embedded SQL declaration or statement. Use EXEC SQL only in embedded SQL programs in C or COBOL. EXEC SQL {sql-declaration | sql-statement} sql-terminator sql-declaration is any embedded SQL declaration. sql-statement is any embedded SQL statement. sql-terminator terminates the SQL declaration or statement. For a C program, semicolon (;) is the terminator.
Embedded-Only SQL/MX Statements EXECUTE IMMEDIATE Statement EXECUTE IMMEDIATE Statement C/COBOL The EXECUTE IMMEDIATE statement compiles and executes an SQL statement whose text is contained in a host variable. The SQL statement supplied cannot have any input or output parameters and must be a preparable statement. Use EXECUTE IMMEDIATE only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements FETCH Statement FETCH Statement Considerations for FETCH C Examples of FETCH COBOL Examples of FETCH The FETCH statement is an SQL statement that positions a cursor on the next row of the result table defined by the cursor specification and retrieves values from that row, leaving the cursor positioned at that row.
Embedded-Only SQL/MX Statements C/COBOL FETCH Statement ext-cursor-name is a value-specification—a character literal or a host variable with character data type. When FETCH executes, the content of the host variable (if used) gives the name of the open cursor. C/COBOL GLOBAL | LOCAL specifies scope. The default is LOCAL. The scope of a GLOBAL cursor is the SQL session. The scope of a LOCAL cursor is the module or compilation unit in which FETCH appears.
Embedded-Only SQL/MX Statements Considerations for FETCH :variable-name is a variable specification—a host variable. A variable name begins with a colon (:). Considerations for FETCH Authorization Requirements FETCH requires read access to any tables or views associated with the cursor or iterator. Updating fetched rows requires write access to the table or view. Ordering Fetched Rows Successive executions of FETCH retrieve successive rows in the result table of the cursor specification or iterator.
Embedded-Only SQL/MX Statements C Examples of FETCH FETCH also returns an integer status code to SQLCODE, as follows: 0 The FETCH was successful. 100 The result table is empty or the end of the table was encountered. >0 A warning was issued. <0 An error occurred. SQLSTATE, the SQL:1999 standard, is the preferred status code for NonStop SQL/MX. C Examples of FETCH • Suppose that you have a cursor that returns information from the PARTS table.
Embedded-Only SQL/MX Statements • COBOL Examples of FETCH This example uses extended cursor and statement names: scanf("%s", in_curspec); ... EXEC SQL PREPARE :curspec FROM :in_curspec; EXEC SQL ALLOCATE :extcur CURSOR FOR :curspec; ... EXEC SQL OPEN :extcur; ... desc_max = 10; ALLOCATE DESCRIPTOR 'fetch_sqlda' WITH MAX :desc_max; DESCRIBE OUTPUT :curspec USING SQL DESCRIPTOR 'fetch_sqlda'; FETCH :extcur INTO SQL DESCRIPTOR 'fetch_sqlda'; ... /* Process values in SQL descriptor area.
Embedded-Only SQL/MX Statements COBOL Examples of FETCH * Close cursor. EXEC SQL CLOSE cursor1 END-EXEC. ... nodata SECTION. ... • This example uses extended cursor and statement names: ACCEPT in-curspec. ... EXEC SQL PREPARE :curspec FROM :in-curspec END-EXEC. EXEC SQL ALLOCATE :extcur CURSOR FOR :curspec END-EXEC. ... EXEC SQL OPEN :extcur END-EXEC. ... MOVE 10 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'fetch_sqlda' WITH MAX desc-max END-EXEC.
Embedded-Only SQL/MX Statements GET DESCRIPTOR Statement GET DESCRIPTOR Statement SQL Item Descriptor Area of GET DESCRIPTOR SQL Descriptor Area Data Type Declarations of GET DESCRIPTOR Considerations for GET DESCRIPTOR C Examples of GET DESCRIPTOR COBOL Examples of GET DESCRIPTOR C/COBOL The GET DESCRIPTOR statement retrieves information from an SQL descriptor area.
Embedded-Only SQL/MX Statements | | | | | GET DESCRIPTOR Statement SCALE TYPE | TYPE_FS UNNAMED VARIABLE_DATA | DATA VARIABLE_POINTER descriptor-name is a value-specification—a character literal or host variable with character data type. The named SQL descriptor area must be currently allocated. variable-name = COUNT retrieves the count of item descriptors with information and stores the count in the named host variable.
SQL Item Descriptor Area of GET DESCRIPTOR Embedded-Only SQL/MX Statements SQL Item Descriptor Area of GET DESCRIPTOR Table 3-1 describes the items in the descriptor area for GET DESCRIPTOR. For character fields with lengths greater than or equal to 128, declare the corresponding host variables as type VARCHAR with length 129 (with an extra byte for the null terminator) in C or type PIC X with length 128 in COBOL. Table 3-1.
SQL Item Descriptor Area of GET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-1. GET DESCRIPTOR Items (page 2 of 4) Name of Field Data Type and Description INDICATOR_DATA Exact numeric, scale 0. Value for the indicator variable of VARIABLE_DATA: 0 INDICATOR_DATA is not null. <0 INDICATOR_DATA is null. >0 VARIABLE_DATA was truncated and INDICATOR_DATA is the length of the source data. This field is equivalent to the ANSI-named INDICATOR field. You can also use INDICATOR as the name of the field.
SQL Item Descriptor Area of GET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-1. GET DESCRIPTOR Items (page 3 of 4) Name of Field Data Type and Description PARAMETER_ORDINAL_ POSITION Smallint. Indicates the position of a formal parameter in the signature of a stored procedure that corresponds to a described dynamic parameter. Values start at 1. A value of 0 (zero) means the position is undefined. For all SQL statements other than the CALL statement, PARAMETER_ORDINAL_POSITION is undefined.
SQL Descriptor Area Data Type Declarations of GET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-1. GET DESCRIPTOR Items (page 4 of 4) Name of Field Data Type and Description TYPE_FS* Exact numeric, scale 0. These codes are SQL/MP-specific codes returned in the SQL descriptor area, as shown under SQL Descriptor Area Data Type Declarations of GET DESCRIPTOR on page 3-50. If you set TYPE_FS, you must also set LENGTH.
Embedded-Only SQL/MX Statements SQL Descriptor Area Data Type Declarations of GET DESCRIPTOR Table 3-2. Descriptor Area Data Type Declarations (page 2 of 2) Value Declaration in sqlci.
Embedded-Only SQL/MX Statements Considerations for GET DESCRIPTOR Considerations for GET DESCRIPTOR Processing Items in a Descriptor Area You can retrieve: • • The number of filled-in descriptor items Fields for a specific item You can use the number of filled-in descriptor items to construct a loop to process individual items. Version Differences for TYPE and TYPE_FS In NonStop SQL/MX Release 1.
Embedded-Only SQL/MX Statements COBOL Examples of GET DESCRIPTOR COBOL Examples of GET DESCRIPTOR • Allocate a descriptor area, describe the output parameters of a dynamic SQL statement, and use the descriptor area to get information about the parameters: * * * * * MOVE 10 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'out_sqlda' WITH MAX :desc-max END-EXEC. ... EXEC SQL DESCRIBE OUTPUT dynamic_stmt USING SQL DESCRIPTOR 'out_sqlda' END-EXEC. ... First, get the count of the number of output values.
Embedded-Only SQL/MX Statements GET DIAGNOSTICS Statement GET DIAGNOSTICS Statement Considerations for GET DIAGNOSTICS C Examples of GET DIAGNOSTICS COBOL Examples of GET DIAGNOSTICS C/COBOL The GET DIAGNOSTICS statement returns information from the diagnostics area about the most recently executed statement and its exception status and assigns the specified statement and condition information to host variables. Use GET DIAGNOSTICS only in embedded SQL programs in C or COBOL.
Embedded-Only SQL/MX Statements GET DIAGNOSTICS Statement condition-item-name is: | | | | | | | | | | | | | | | | | | CONDITION_NUMBER RETURNED_SQLSTATE CLASS_ORIGIN SUBCLASS_ORIGIN SERVER_NAME CONNECTION_NAME CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME CATALOG_NAME SCHEMA_NAME TABLE_NAME COLUMN_NAME CURSOR_NAME MESSAGE_TEXT MESSAGE_LENGTH MESSAGE_OCTET_LENGTH NSK_CODE SQLCODE statement-info assigns statement information, statement-info, to host variables.
Statement Items of GET DIAGNOSTICS Embedded-Only SQL/MX Statements Statement Items of GET DIAGNOSTICS Table 3-3 describes the statement items in the diagnostics area. For exact numeric fields with scale 0, declare the corresponding host variables as type long in C or type PIC S9(18) COMP in COBOL.
Condition Items of GET DIAGNOSTICS Embedded-Only SQL/MX Statements Table 3-4. GET DIAGNOSTICS Condition Items (page 2 of 2) Condition Item Name Data Type and Description SERVER_NAME Character varying, length>=128. Identifies server. Reserved for future use. CONNECTION_NAME Character varying, length>=128. Identifies connection. Reserved for future use. CONSTRAINT_CATALOG Character varying, length>=128. Identifies catalog of schema containing constraint or assertion. Reserved for future use.
Embedded-Only SQL/MX Statements Considerations for GET DIAGNOSTICS Considerations for GET DIAGNOSTICS Processing Condition Items in the Diagnostics Area You can retrieve: • • The number of filled-in condition items Fields for a specific condition item You can use the number of filled-in condition items to construct a loop to process individual items. Writing a Log of Exception Conditions You can retrieve the message text of the exception condition for SQLSTATE and SQLCODE.
Embedded-Only SQL/MX Statements COBOL Examples of GET DIAGNOSTICS COBOL Examples of GET DIAGNOSTICS • Use the diagnostics area to get information about exception conditions: ... EXEC SQL GET DIAGNOSTICS :hv-num = NUMBER, ... END-EXEC. PERFORM VARYING i FROM 1 BY 1 UNTIL i > hv-num EXEC SQL GET DIAGNOSTICS EXCEPTION :i :hv-sqlstate = RETURNED_SQLSTATE, :hv-sqlcode = SQLCODE, :hv-msgtext = MESSAGE_TEXT, ... END-EXEC. * Write to the exception condition log file. ... * Process the diagnostic area values. ..
Embedded-Only SQL/MX Statements IF Statement IF Statement Considerations for IF Statement C Example of IF Statement C/COBOL An IF statement is a compound statement that provides conditional execution based on the truth value of a conditional expression. IF is an SQL/MX extension that you use only in embedded SQL programs in C or COBOL. IF conditional-expression THEN SQL-statement;[SQL-statement;]... [ELSEIF conditional-expression THEN SQL-statement;[SQL-statement;]...]...
Embedded-Only SQL/MX Statements Considerations for IF Statement Considerations for IF Statement SQL Statements in the List The restrictions for which SQL statements can be used in a list are the same as the restrictions for the compound statement. Transactional SQL statements BEGIN WORK, COMMIT WORK, ROLLBACK WORK, and SET TRANSACTION cannot be used in IF statements. UPDATE STATISTICS and CONTROL statements cannot be used in IF statements. SELECT INTO (retrieving only one row) can be used in a list.
Embedded-Only SQL/MX Statements COBOL Example of IF Statement COBOL Example of IF Statement • These INSERT and SELECT statements execute sequentially for new orders. Otherwise, the SELECT statement returns information about the current customer: EXEC SQL BEGIN IF :hv_now_ordernum <> 0 THEN INSERT INTO SALES.ORDERS (ORDERNUM, ORDER_NAME, DELIV_DATE,...
Embedded-Only SQL/MX Statements INVOKE Directive INVOKE Directive Considerations for INVOKE C Examples of INVOKE COBOL Examples of INVOKE C/COBOL The INVOKE preprocessor directive generates a C structure template or COBOL record declaration that corresponds to a row in a specified table or view and inserts the declaration directly into the host program. The row description includes a data item for each column. INVOKE is an SQL/MX extension.
INVOKE Directive Embedded-Only SQL/MX Statements DATEFORMAT {DEFAULT | EUROPEAN | USA} specifies the format of host variables for datetime columns. For a column with a datetime data type that has an HOUR field, DATEFORMAT USA causes INVOKE to produce a host variable that is three bytes longer than an equivalent host variable for EUROPEAN or DEFAULT format. The extra bytes allow room for “am” or “pm” following the values. The default is DATEFORMAT DEFAULT.
Embedded-Only SQL/MX Statements Considerations for INVOKE Considerations for INVOKE Preserving or Overriding the INVOKE Directive The preprocessor expands the table or view name in the INVOKE directive to a fully qualified object name, such as [\node.][[$volume.]subvol.]filename for a Guardian physical name or catalog.schema.object for an ANSI logical name. Expansion of the name depends on how the name is qualified in the INVOKE directive and how you have declared object names in the program.
Embedded-Only SQL/MX Statements C Examples of INVOKE Using INVOKE in a C Program The general syntax for using an embedded INVOKE directive within an SQL declare section in a C program is: EXEC SQL INVOKE table [AS structure-name]; struct structure-name structure-instance ; The struct declaration declares structure-instance to be a structure of the type structure-name. You must declare a variable of the struct type so that you can use that variable in your C language statements.
Embedded-Only SQL/MX Statements • C Examples of INVOKE This example shows the generated structure template that the previous INVOKE directive would have generated if the EMPLOYEE table did not contain a userdefined primary key, such as the EMPNUM column.
Embedded-Only SQL/MX Statements COBOL Examples of INVOKE COBOL Examples of INVOKE • Suppose that the EMPLOYEE table consists of the EMPNUM, FIRST_NAME, LAST_NAME, and DEPTNUM columns. The FIRST_NAME column allows null, and the EMPNUM column is the primary key. This example shows an INVOKE statement with the NULL STRUCTURE clause and part of the structure that is generated: EXEC SQL BEGIN DECLARE SECTION END-EXEC. EXEC SQL INVOKE employee AS EMPTBL-REC NULL STRUCTURE END-EXEC.
Embedded-Only SQL/MX Statements MODULE Directive MODULE Directive The MODULE directive specifies the name of an embedded SQL/MX module for the C or COBOL preprocessor. If you do not specify a MODULE directive, the preprocessor generates a module name. MODULE is an SQL/MX extension that you use only in embedded SQL programs. MODULE module-name [NAMES ARE ISO88591] module-name is the name of the module.
Embedded-Only SQL/MX Statements C Examples of MODULE Automatic Generation of Module Names If you do not specify a MODULE directive, the preprocessor or customizer generates a module name for you. If you change your source program and process and compile it again, the new module overwrites the old module. System-generated module names can become a management problem if you want to create different versions of your program.
Embedded-Only SQL/MX Statements OPEN Statement OPEN Statement Considerations for OPEN C Examples of OPEN COBOL Examples of OPEN C/COBOL The OPEN statement opens a cursor in a host program and establishes the result table specified by the DECLARE CURSOR statement for the named cursor. It positions the cursor before the first row of the result table. In dynamic SQL, the cursor name is provided at execution time. An optional USING clause provides input parameters for the cursor specification.
Embedded-Only SQL/MX Statements Considerations for OPEN USING variable-spec [,variable-spec]... (dynamic SQL) identifies the host variables for the dynamic input parameters of the cursor specification. Before OPEN with USING executes, the application must store information for each parameter of the cursor specification in the appropriate host variable. USING SQL DESCRIPTOR descriptor-name (dynamic SQL) identifies the SQL descriptor area for the dynamic input parameters of the cursor specification.
Embedded-Only SQL/MX Statements C Examples of OPEN USING Clause If the cursor specification uses dynamic input parameters, you must provide a USING clause for either a list of arguments or an SQL descriptor area. This requirement is the same as that for providing a USING clause for an EXECUTE statement that executes a prepared statement with dynamic input parameters. See EXECUTE Statement on page 2-131.
Embedded-Only SQL/MX Statements COBOL Examples of OPEN COBOL Examples of OPEN • Declare and open a cursor, using FETCH to retrieve data, then closing the cursor: EXEC SQL DECLARE cursor1 CURSOR FOR SELECT COL1, COL2, COL3 FROM PARTS WHERE COL1 >= :hostvar ORDER BY COL1 READ UNCOMMITTED ACCESS END-EXEC. ... EXEC SQL OPEN cursor1 END-EXEC. ... EXEC SQL FETCH cursor1 INTO :hostvar1, :hostvar2, :hostvar3 END-EXEC. ... EXEC SQL CLOSE cursor1 END-EXEC.
Embedded-Only SQL/MX Statements SET (Assignment) Statement SET (Assignment) Statement C Examples of Assignment Statement C/COBOL An assignment statement in a compound statement assigns a value to a host variable so that subsequent statements in the containing compound statement can reference and use the value of that host variable. SET is an SQL/MX extension that you use only in embedded SQL programs in C or COBOL.
C Examples of Assignment Statement Embedded-Only SQL/MX Statements assignment-source specifies a list of value expressions, a list of rowset expressions, the NULL specification, or a subquery. These values are to be inserted into the assignment-target. subquery | {expression | rowset-expression | NULL} [,{expression | rowset-expression | NULL}]... is a value expression, rowset expressions, NULL, or the result of a subquery. NULL can be assigned to a host variable of any type.
Embedded-Only SQL/MX Statements SET DESCRIPTOR Statement SET DESCRIPTOR Statement SQL Item Descriptor Area of SET DESCRIPTOR Considerations for SET DESCRIPTOR C Examples of SET DESCRIPTOR COBOL Examples of SET DESCRIPTOR C/COBOL The SET DESCRIPTOR statement changes specified information in an SQL descriptor area. An application program can either set the count of item descriptors with information or set the value of a specific field within a specific item.
Embedded-Only SQL/MX Statements SQL Item Descriptor Area of SET DESCRIPTOR ROWSET_SIZE = value-specification sets the length of rowsets specified in the item descriptors from value-specification, a literal with exact numeric data type or a host variable. value-specification is the common length of all rowsets described in the descriptor. VALUE item-number set-item-info [,set-item-info]... sets the value of a specific field within a specific item.
SQL Item Descriptor Area of SET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-5. SET DESCRIPTOR Descriptor Area Items (page 1 of 2) Field Data Type and Description CHARACTER_SET_NAME Character string. One-part character set name. DATETIME_CODE Exact numeric, scale 0. Codes for datetime type: 1 date; 2 time; 3 timestamp.
Considerations for SET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-5. SET DESCRIPTOR Descriptor Area Items (page 2 of 2) Field Data Type and Description SCALE Exact numeric, scale 0. Scale for exact numeric types. SCALE specifies the number of digits to the right of the decimal point. TYPE Exact numeric, scale 0.
Embedded-Only SQL/MX Statements Considerations for SET DESCRIPTOR col_num = 1; data_ind = -1; EXEC SQL SET DESCRIPTOR :upd_desc VALUE :col_num INDICATOR_DATA = :data_ind, VARIABLE_DATA = :data_pic_2; printf("SQLCODE after SET DESCRIPTOR is %d \n", SQLCODE); EXEC SQL EXECUTE P_UPD USING SQL DESCRIPTOR :upd_desc; printf("SQLCODE after EXECUTE = %ld\n", SQLCODE); DECIMAL Data Types and SET DESCRIPTOR When a host variable is defined as the DECIMAL data type in an embedded program, there are two ways to set t
Embedded-Only SQL/MX Statements Considerations for SET DESCRIPTOR " VALUES (cast(? as decimal(3,0) unsigned));"); desc_max = 1; EXEC SQL ALLOCATE DESCRIPTOR 'in_desc3' WITH MAX :desc_max; printf("SQLCODE after allocate descriptor is %d\n", SQLCODE); EXEC SQL PREPARE FROM :insert_buf; printf("SQLCODE after prepare is %d\n", SQLCODE); desc_val = 1; type_val = -301; strncpy(decimal_3_unsigned, " ", sizeof(decimal_3_unsigned)); strcpy(decimal_3_unsigned, " 999"); precision = 3; scale = 0; length = 5; EXEC SQL
Embedded-Only SQL/MX Statements C Examples of SET DESCRIPTOR VARIABLE_POINTER is not supported in COBOL. Embedded COBOL does not support the pointer type. Processing Items in a Descriptor Area You can retrieve the number of filled-in descriptor items for input parameters and set fields for a specific item. Use the number of filled-in descriptor items to construct a loop to set values for individual parameters.
Embedded-Only SQL/MX Statements COBOL Examples of SET DESCRIPTOR COBOL Examples of SET DESCRIPTOR • Allocate a descriptor area, describe the input parameters of a dynamic SQL statement, and use the descriptor area to set values for the parameters: - MOVE 1 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'in_sqlda' WITH MAX :desc-max END-EXEC. ... MOVE "UPDATE employee " SET salary = salary * 1.1 " WHERE jobcode = CAST(? AS NUMERIC(4) unsigned)" TO hv-sql-statement.
WHENEVER Declaration Embedded-Only SQL/MX Statements WHENEVER Declaration Considerations for WHENEVER C Examples of WHENEVER COBOL Examples of WHENEVER C/COBOL The WHENEVER declarative statement specifies an action to take when an error, warning, or no-rows-found condition occurs. The preprocessor inserts code after every embedded SQL statement to check values of SQLSTATE and jump to the appropriate routine to handle the error, warning, or no-rows-found condition.
Considerations for WHENEVER Embedded-Only SQL/MX Statements condition-action specifies the action to take: CONTINUE Continue with next statement. GOTO target Pass control to the target location. CALL C-function Execute the named C function. PERFORM COBOL-routine Execute the named COBOL routine. If you do not specify an action, NonStop SQL/MX discontinues checking for the specified condition. target is a host label identifier that specifies a target location in a C program.
Embedded-Only SQL/MX Statements C Examples of WHENEVER C Examples of WHENEVER • The effect of this statement is the same as if you had written a C statement that tests for an SQLSTATE of 02000 and executes a C continue statement: WHENEVER NOT FOUND CONTINUE; • WHENEVER sets actions for all embedded SQL statements that physically follow it in the program. In this example, if statement_2 caused an error, control continues at label x. ... EXEC SQL EXEC SQL EXEC SQL EXEC SQL EXEC SQL ... label_x: ...
Embedded-Only SQL/MX Statements COBOL Examples of WHENEVER HP NonStop SQL/MX Reference Manual—540440-003 3- 88
4 MXCI Commands This section describes the syntax and semantics of MXCI commands. MXCI commands are NonStop SQL/MX extensions that typically affect attributes of an MXCI session. You can run these commands only through MXCI, with the exceptions noted: ADD DEFINE Command on page 4-3 Creates DEFINEs for Guardian file names. ALTER DEFINE Command on page 4-5 Changes DEFINEs for Guardian file names. CD Command on page 4-7 Changes the current working directory.
MXCI Commands OBEY Command on page 4-41 Executes MXCI commands and statements from a file. This file is referred to as an OBEY command file. REPEAT Command on page 4-43 Reexecutes a command. You can also use the exclamation point (!) command. RESET PARAM Command on page 4-44 Clears the values of the specified parameter or all the parameters in the current session. SET LIST_COUNT Command on page 4-46 Sets the maximum number of rows to be displayed for the next SELECT statement.
ADD DEFINE Command MXCI Commands ADD DEFINE Command Considerations for ADD DEFINE Examples of ADD DEFINE The ADD DEFINE command creates a new DEFINE in the current MXCI session. (ADD DEFINE is similar to the TACL command ADD DEFINE and the OSS shell command add_define.) You can use defines only for SQL/MP objects. You can use ADD DEFINE only within an MXCI session. ADD DEFINE define [,CLASS MAP], FILE [\node.][[$volume.]subvol.]filename define is the name for the new DEFINE.
Considerations for ADD DEFINE MXCI Commands If the Guardian physical name includes a reserved word, consider using the CREATE SQLMP ALIAS statement, instead of the ADD DEFINE command, to create a logical name mapping. Considerations for ADD DEFINE Scope of ADD DEFINE A DEFINE stays in effect until you change or delete it or until you exit the current session. A user can delete a DEFINE within MXCI.
ALTER DEFINE Command MXCI Commands ALTER DEFINE Command Considerations for ALTER DEFINE Examples of ALTER DEFINE The ALTER DEFINE command changes a DEFINE in the current MXCI session. (ALTER DEFINE is similar to the TACL command ALTER DEFINE.) You can use ALTER DEFINE only within an MXCI session. ALTER DEFINE define [,CLASS MAP], FILE [\node.][[$volume.]subvol.]filename define is the name of the existing DEFINE to change.
Examples of ALTER DEFINE MXCI Commands Examples of ALTER DEFINE • Alter a DEFINE that assigns the logical name =ORDERS to the table whose Guardian physical name is $MYVOL.SALES.ORDERS: ALTER DEFINE =ORDERS, FILE $MYVOL.SALES.
CD Command MXCI Commands CD Command The CD command changes the current working session directory. You can use CD only within an MXCI session. CD [directory] directory is an absolute or relative path name that specifies the new current working directory. An absolute path name begins with a slash (/), the symbol representing the root directory. A relative path name defines a path relative to the current directory; it does not begin with /.
DELETE DEFINE Command MXCI Commands DELETE DEFINE Command The DELETE DEFINE command deletes a DEFINE in the current MXCI session. (DELETE DEFINE is similar to the TACL command DELETE DEFINE and the OSS shell command del_define.) You can use DELETE DEFINE only within an MXCI session. DELETE DEFINE define define is the name of the existing DEFINE to delete.
DISPLAY USE OF Command MXCI Commands DISPLAY USE OF Command Considerations for DISPLAY USE OF Examples of DISPLAY USE OF The DISPLAY USE OF command provides usage information on statically compiled modules. display use of [NOE] [module_dir 'module-directory-path'] [ module 'module-name'] [ object 'object-name' ] DISPLAY USE OF displays a list of modules and, for each module, a list of dependent objects.
Considerations for DISPLAY USE OF MXCI Commands /usr/tandem/sqlmx/USERMODULES or in the directory you specified with module_dir. module-name is case-sensitive. You can look for similar values by specifying only part of the characters of module-name combined with the “*” (asterisk) wild-card characters. If you omit the module clause, DISPLAY USE OF will search for all modules. All of these specifications are valid: module 'CAT.SCH.M1' module 'CAT.sch.*' module 'CAT.*.
Examples of DISPLAY USE OF MXCI Commands Parallel Execution of DISPLAY USE OF Suppose your system has many modules. When you run DISPLAY USE OF against all modules on the system, it might take 30 minutes or more. If you name the modules with a distinguishing prefix, such as an indication of what application the module belongs to, you can use wild cards to run multiple instances of DISPLAY USE OF that each target a different set of modules, in different CPUS.
Examples of DISPLAY USE OF MXCI Commands TANDEM_SYSTEM_NSK.SCH.MULTCURM Object: \NODE1.$DATA08.ORDERS.T1 Module: TANDEM_SYSTEM_NSK.SCH.MULTIM Object: \NODE1.$DATA08.ORDERS.T1 Module: TANDEM_SYSTEM_NSK.SCH.STRUCTM Table: \NODE1.$DATA08.ORDERS.T1 Module: TANDEM_SYSTEM_NSK.SCH.T1INDM Object: \NODE1.$DATA08.ORDERS.T1 Module: TANDEM_SYSTEM_NSK.SCH.T1ROWSM • Display use of a specified SQL/MP alias object in specified modules: >>display use of module 'CAT.SCH.*' object 'CAT.SCH.T'; Object: CAT.SCH.
DISPLAY_EXPLAIN Command MXCI Commands DISPLAY_EXPLAIN Command Considerations for DISPLAY_EXPLAIN Examples of DISPLAY_EXPLAIN The DISPLAY_EXPLAIN command generates and displays the result of the EXPLAIN function, describing an access plan for a SELECT, INSERT, DELETE, UPDATE, or CALL statement. For a description of the result table of the EXPLAIN function, see EXPLAIN Function on page 9-52. You can use DISPLAY_EXPLAIN only within an MXCI session.
Examples of DISPLAY_EXPLAIN MXCI Commands Purpose of the EXPLAIN Function Result The EXPLAIN function result is an access plan. You can use the access plan to tune queries and to help determine whether to add or drop indexes for a table in a database. For more information about access plans, see the SQL/MX Query Guide. Examples of DISPLAY_EXPLAIN • Display all columns in the result of the EXPLAIN function for the specified statement: DISPLAY_EXPLAIN SELECT * FROM persnl.employee WHERE salary > 40000.
Examples of DISPLAY_EXPLAIN MXCI Commands buffer_size: 31000 record_length: 48 ? EXPL_NAME__ 211864141076058828 3 ROOT 2 ? 2.4783301E+000 9.8001182E-002 1.1864653E-001 CPU_TIME: 0.002373 IO_TIME: 0.020647 MSG_TIME: 0 IDLETIME: 0.098 PROBES: 1 select_list: indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.EMPNUM), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.FIRST_NAME), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.LAST_NAME), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.DEPTNUM), 450, indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.
Examples of DISPLAY_EXPLAIN MXCI Commands end_key: (indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.EMPNUM) = 65535) scan_type: file_scan SAMDBCAT.PERSNL.
Examples of DISPLAY_EXPLAIN MXCI Commands This output shows the sequence numbers, the operators, parallel information, and the cardinality for the operators. Using the sequence numbers, you can create a query tree that visually shows the query plan. For more information about parallelism and examples of how to build, display, and interpret query trees, see the SQL/MX Query Guide. The DESCRIPTION column contains information about parallelism for an operator.
DISPLAY_QC Command MXCI Commands DISPLAY_QC Command Considerations for DISPLAY_QC Examples of DISPLAY_QC The DISPLAY_QC command generates and displays selected data from the result of the QUERYCACHE function. For a description of the result table of the QUERYCACHE function, see the QUERYCACHE Function on page 9-108. You can use DISPLAY_QC only within an MXCI session.
Examples of DISPLAY_QC MXCI Commands Examples of DISPLAY_QC >>SET SCHEMA SAMDBCAT.PERSNL; --- SQL operation complete. >SELECT * FROM EMPLOYEE; Employee/Number First Name -------------- -------------1 ROGER 23 JERRY 29 JANE . . . --- 62 row(s) selected. Last Name -------------GREEN HOWARD RAYMOND Dept/Num -------9000 1000 3000 Job/Code -------100 100 100 Salary --------175500.00 137000.10 136000.
DISPLAY_QC_ENTRIES Command MXCI Commands DISPLAY_QC_ENTRIES Command Considerations for DISPLAY_QC_ENTRIES Examples of DISPLAY_QC_ENTRIES The DISPLAY_QC_ENTRIES command generates and displays selected data from the result of the QUERYCACHEENTRIES function. For a description of the result table of the QUERYCACHEENTRIES function, see the QUERYCACHEENTRIES Function on page 9-112. You can use DISPLAY_QC_ENTRIES only within an MXCI session.
Examples of DISPLAY_QC_ENTRIES MXCI Commands Examples of DISPLAY_QC_ENTRIES >>SET SCHEMA SAMDBCAT.PERSNL; --- SQL operation complete. >SELECT * FROM EMPLOYEE; Employee/Number First Name -------------- -------------1 ROGER 23 JERRY 29 JANE . . . --- 62 row(s) selected. Last Name -------------GREEN HOWARD RAYMOND Dept/Num -------9000 1000 3000 Job/Code -------100 100 100 Salary --------175500.00 137000.10 136000.
DISPLAY STATISTICS Command MXCI Commands DISPLAY STATISTICS Command Considerations for DISPLAY STATISTICS Examples of DISPLAY STATISTICS DISPLAY STATISTICS displays statistics about the last DML or PREPARE statement executed within the current MXCI session. Use DISPLAY STATISTICS only within an MXCI session. DISPLAY STATISTICS Considerations for DISPLAY STATISTICS When you issue the DISPLAY STATISTICS command, MXCI displays: Start time Time when the query is first issued from MXCI.
Examples of DISPLAY STATISTICS MXCI Commands Examples of DISPLAY STATISTICS • Suppose that this was the last DML command issued: DELETE FROM invent.partsupp WHERE suppnum NOT IN (SELECT suppnum FROM supplier WHERE state='TEXAS'); --- 41 row(s) deleted. You can display statistics for this statement by using the DISPLAY STATISTICS command: DISPLAY STATISTICS; Start Time End Time Elapsed Time Compile Time Execution Time Table Name 2001/08/22 09:24:50.188 2001/08/22 09:24:51.966 00:00:01.777 00:00:00.
ENV Command MXCI Commands ENV Command ENV displays attributes of the current MXCI session. You can use ENV (or SHOW SESSION Command) only within an MXCI session. ENV ENV displays these attributes: CURRENT DIRECTORY Path name of the current working directory. You can change it with the CD command. HOME DIRECTORY Default directory. LIST_COUNT Current list count. LOG FILE Current log file. MESSAGEFILE Current message file.
Examples of ENV MXCI Commands Examples of ENV • An ENV command and its output: >>env; ---------------------------------Current Environment ---------------------------------CURRENT DIRECTORY /usr/manager/bin HOME DIRECTORY /usr/manager LIST_COUNT 4294967295 LOG FILE MESSAGEFILE /usr/manager/bin/mxcierrors.cat TERMINAL CHARSET ISO88591 MESSAGEFILE LANG US English MESSAGEFILE VRSN {2003-12-11 13:56 NSK:SQUAW/SUPER.
ERROR Command MXCI Commands ERROR Command The ERROR command displays the error text associated with an error number. You can use ERROR only within an MXCI session. ERROR number [,BRIEF] number is an unsigned integer that identifies the error you want described. BRIEF displays the error text associated with the specified number. The ERROR command returns the same information with or without this keyword.
Exclamation Point (!) Command MXCI Commands Exclamation Point (!) Command The exclamation point (!) command reexecutes a previous MXCI command. You can use ! only within an MXCI session. ! [text | [-]number] text specifies the text of the most recent use of a command. The command must have been executed beginning with text, but text need be only as many characters as necessary to identify the command. Leading blanks are ignored. [-]number is an integer that identifies a command in the history buffer.
EXIT Command MXCI Commands EXIT Command The EXIT command ends an MXCI session and returns control to the process from which you started MXCI. You can use EXIT only within an MXCI session. EXIT Considerations for EXIT Effect of EXIT on Active Transactions A transaction can be user-initiated or system-initiated. If you attempt to end an MXCI session when either type of transaction is active, MXCI prompts you to specify whether to commit or roll back the work of the transaction.
FC Command MXCI Commands FC Command Examples of FC The FC command allows you to edit and reissue an MXCI command in the history buffer. You can display the commands in the history buffer by using the HISTORY command. For more information about the history buffer, see HISTORY Command on page 4-31. You can use FC only within an MXCI session. FC [text | [-]number] text is the beginning text of a command in the MXCI history buffer. Case is not significant in matching the text to a command.
Examples of FC MXCI Commands Examples of FC • Reexecute the most recent command that begins with SH: >>FC SH; >>SHOW SESSION; .. Pressing Return executes the SHOW SESSION command. • Correct a statement entered incorrectly: >>SELECR * FROM MYTABLE; *** ERROR[15001] A syntax error at or before: selecr * from $boy000.persnl.employee; ^ >>FC; >>SELECR * FROM MYTABLE; .. T >>SELECT * FROM MYTABLE; .. Pressing Return executes the corrected SELECT statement.
HISTORY Command MXCI Commands HISTORY Command The HISTORY command displays recently executed MXCI commands, identifying each command by a number you can use to reexecute or edit the command with FC. See FC Command on page 4-29. You can use HISTORY only within an MXCI session. HISTORY [number] number is the number of commands to display. The default number is 10.
INFO DEFINE Command MXCI Commands INFO DEFINE Command INFO DEFINE displays the logical and physical names of DEFINEs in the current MXCI session. (INFO DEFINE is similar to the TACL command INFO DEFINE and the OSS shell command info_define.) INFO DEFINE [ALL] ALL displays information about all the DEFINEs. If you do not specify ALL, the INFO DEFINE command displays information about the current class MAP DEFINEs, which are associated with the names of tables, views, or partitions.
INVOKE Command MXCI Commands INVOKE Command Examples of INVOKE The INVOKE command generates a record description that corresponds to a row in the specified table or view. The record description includes a data item for each column in the table or view except the SYSKEY column; it includes the SYSKEY column of a view only if the view explicitly listed the column in its definition. You can use this version of INVOKE only within an MXCI session.
LOG Command MXCI Commands LOG Command Considerations for LOG Examples of LOG The LOG command starts or stops MXCI logging to a disk file. When logging is in effect, MXCI writes the commands you enter to a file (in addition to executing them) and writes the output of the commands to the file. Use LOG only within an MXCI session. LOG [log_file [COMMAND[S]] [CLEAR]] log_file is the name of a file to which MXCI writes the commands you use and the command output.
Examples of LOG MXCI Commands To ensure that log information is retained for a session, use a unique name for each log file. Examples of LOG • Start logging only commands to an OSS text file in the current directory, clearing the file first: >>LOG myfile COMMANDS CLEAR; • Stop logging: >>LOG; After you exit MXCI, you can copy the file to the Guardian environment by using the OSS cp command. For example: cp myfile /G/data06/tempjb/myfile Exit OSS.
LS Command MXCI Commands LS Command Considerations for LS Examples of LS LS lists file statistics. You can use LS only within an MXCI session. LS [-abcCdfFgilmnopqrRstux1] [file | directory]... -abcCdfFgilmnopqrRstux1 indicates some of the standard flags available to you through your platform’s shell ls command, as follows: -a Lists all entries in directory, including those beginning with dot (.) -b Displays nonprintable characters in octal notation.
Considerations for LS MXCI Commands -R Lists all subdirectories recursively. -s Gives space used in 512-byte units (including indirect blocks) for each entry. -t Sorts by time of last modification (latest first) instead of by name, before sorting the operands by the collating sequence. -u Uses the time of the last access instead of the time of the last modification for sorting (when used with the -t option) or for displaying (when used with the -l option).
Examples of LS MXCI Commands 13:03 logjb -rw-rw-rw1 PUBS.JBROOK 14:11 myfile • PUBS 18961 Feb 8 Display detailed information about the directory named /usr: >>ls -d -l /usr; drwxrwxr-x 1 SUPER.SUPER /usr SUPER 4096 May 3 1999 Without the -d option, this LS command lists detailed information about all the files in the directory named /usr.
MODE Command MXCI Commands MODE Command MODE selects the MXCI command mode. MODE { MXCS | REPORT | SQL } MXCS specifies that commands that follow will be sent to MXCS. REPORT specifies that commands that follow will be sent to the Report Writer. For details on the Report Writer, see the SQL/MX Report Writer Guide. SQL specifies that commands that follow will be sent to NonStop SQL/MX. When you begin an MXCI session, the mode is set to SQL. For details on MXCI, see MXCI Session on page 1-2.
MXCI Command MXCI Commands MXCI Command MXCI is the command that starts an MXCI session from the OSS environment. MXCI [-ifilename] filename specifies the file from which MXCI reads the commands. The file must either be closed or open for read only. If the -i option is specified, MXCI stops the session immediately after executing the commands in the file. is the input file to MXCI, which might contain any SQL commands, DDL or DML statements.
OBEY Command MXCI Commands OBEY Command Considerations for OBEY Examples of OBEY The OBEY command executes MXCI commands and SQL statements from a file exactly as if you had entered the commands and statements from within an MXCI session. You can use OBEY only within an MXCI session. OBEY command-file [(section-name)] command-file is the path name of a file that contains MXCI commands and SQL statements to be executed by the OBEY command.
Examples of OBEY MXCI Commands Effect of the MXCI Break Key Typically, if you press the MXCI break key (Ctrl-c, Ctrl-Break, or the OutsideView Break icon) while MXCI is executing commands and statements from an OBEY command file, the current command or statement is interrupted, the processing of the OBEY command file is terminated, and the transaction might be rolled back. Execute the SHOW SESSION command to determine the status of the transaction.
REPEAT Command MXCI Commands REPEAT Command The REPEAT command reexecutes a previous MXCI command. You can use REPEAT only within an MXCI session. REPEAT [text | [-]number] text specifies the text of the most recent use of a command. The command must have been executed beginning with text, but text need be only as many characters as necessary to identify the command. Leading blanks are ignored. [-]number is an integer that identifies a command in the history buffer.
RESET PARAM Command MXCI Commands RESET PARAM Command The RESET PARAM command is used to clear all parameter values or a specified parameter value within an MXCI session. You can use RESET PARAM only within an MXCI session. RESET PARAM [?param-name] ?param-name is the name param-name of the parameter for which the value is specified. If you do not specify param-name, all of the parameter values in the current MXCI session are cleared.
Examples of RESET PARAM MXCI Commands Clear the ?ST parameter and display the parameters: >>RESET PARAM ?ST; >>SHOW PARAM; PARAM ?PN 3210 Note that NonStop SQL/MX displays only the ?PN parameter.
SET LIST_COUNT Command MXCI Commands SET LIST_COUNT Command The SET LIST_COUNT command is used to set the maximum number of rows to be displayed in SELECT statements executed after this command. You can use SET LIST_COUNT only within an MXCI session. SET LIST_COUNT [num-rows] num-rows is a positive integer that specifies the maximum number of rows of data to be displayed from the execution of SELECT statements after the execution of this command.
SET PARAM Command MXCI Commands SET PARAM Command Considerations for SET PARAM Examples of SET PARAM The SET PARAM command is used to set a parameter value within an MXCI session. The value is used for queries that contain the associated parameter name. A separate SET PARAM is required for each parameter. See MXCI Parameters on page 6-73. You can use SET PARAM only within an MXCI session.
Considerations for SET PARAM MXCI Commands Considerations for SET PARAM Using With PREPARE and EXECUTE If you use the PREPARE statement to compile an SQL statement, you must specify all of the parameters in the prepared SQL statement with the SET PARAM command prior to issuing the EXECUTE statement.
Examples of SET PARAM MXCI Commands • The PROJECT table has a SHIP_TIMESTAMP column. This UPDATE statement uses the character literal in the ?SHIP parameter to set the value: SET PARAM ?SHIP '1998-04-03 21:05:36.143'; UPDATE persnl.project SET ship_timestamp = CAST (?SHIP AS TIMESTAMP(3)); • The PROJECT table has an EST_COMPLETE column. This UPDATE statement uses the character literal in the ?EST parameter to set the value: SET PARAM ?EST 60; UPDATE persnl.
SET SHOWSHAPE Command MXCI Commands SET SHOWSHAPE Command Considerations for SET SHOWSHAPE Examples of SET SHOWSHAPE The SET SHOWSHAPE command allows you to display access plans in effect. The effect of SET SHOWSHAPE is to generate the output of the SHOWSHAPE command for multiple SQL statements. See SHOWSHAPE Command on page 4-89. You can use SET SHOWSHAPE only within an MXCI session.
Considerations for SET SHOWSHAPE MXCI Commands Considerations for SET SHOWSHAPE Default Control Query Shape For those statements that do not have a shape—for example, the CREATE SCHEMA statement—a control query shape (CQS) of the form CONTROL QUERY SHAPE ANYTHING is issued. CONTROL QUERY SHAPE ANYTHING resets the effect of any preceding CQSs. Its use is especially important when CQSs are being generated from an input file of commands and statements.
Examples of SET SHOWSHAPE MXCI Commands • To turn off the display of access plans, enter: SET SHOWSHAPE OFF; • To write results of queries, which are provided in an input file named examples, and their plans to an output file named plans, enter: SET SHOWSHAPE INFILE /G/data06/judy/examples OUTFILE plans; HP NonStop SQL/MX Reference Manual—540440-003 4- 52
SET STATISTICS Command MXCI Commands SET STATISTICS Command The SET STATISTICS command allows you to specify whether to display statistics after each SQL statement executes. SET STATISTICS {ON | OFF} ON displays statistics automatically after each statement executes. OFF turns off the automatic display of statistics. Note. The default setting when you start MXCI is STATISTICS OFF. For a description of the statistics displayed, see DISPLAY STATISTICS Command on page 4-22.
SET TERMINAL_CHARSET Command MXCI Commands SET TERMINAL_CHARSET Command The SET TERMINAL_CHARSET command is used to set the character set for messages that an interactive SQL/MX client can send to or receive from NonStop SQL/MX. Examples of such messages include commands, SQL statements or query results generated during a MXCI session. SET TERMINAL_CHARSET 'value' value is any one of the fifteen character set names enclosed in single quotes. The default value is 'ISO88591'.
SET WARNINGS Command MXCI Commands SET WARNINGS Command The SET WARNINGS command is used to turn the display of warnings on or off during an MXCI session. An MXCI session starts with the warnings on. You can use SET WARNINGS only within an MXCI session. SET WARNINGS {ON | OFF} Examples of SET WARNINGS • Suppose that T1 is a table containing one row.
SH Command MXCI Commands SH Command SH invokes the shell of your platform. You can use SH only within an MXCI session. SH [command-line-argument]... command-line-argument To display the command-line arguments that your shell supports, at the MXCI prompt, enter: sh man sh; A reference page of the SH command explains the command-line arguments that your shell supports. At the end of the reference page, the MXCI prompt automatically appears.
SHOW PARAM Command MXCI Commands SHOW PARAM Command The SHOW PARAM command is used to display all of the parameters and their values that are defined in the current MXCI session. You can use SHOW PARAM only within an MXCI session. SHOW PARAM See MXCI Parameters on page 6-73. Examples of SHOW PARAM • Display parameter values: SHOW PARAM; Param ?ST TEXAS Param ?PN 3210 Param ?pn 1234 Note that parameter names are case-sensitive. For example, the parameter ?pn is not equivalent to the parameter ?PN.
SHOW PREPARED Command MXCI Commands SHOW PREPARED Command The SHOW PREPARED command is used to display prepared statements in the current MXCI session. Use SHOW PREPARED only within an MXCI session. SHOW PREPARED [* | ALL] * | ALL displays all the currently prepared statements. Note. The SHOW PREPARED command displays all the currently prepared statements regardless of whether you specify the * or the ALL option. See PREPARE Statement on page 2-159.
SHOW SESSION Command MXCI Commands SHOW SESSION Command Examples of SHOW SESSION SHOW SESSION displays attributes of the current MXCI session. You can use SHOW SESSION (or ENV) only within an MXCI session. SHOW SESSION SHOW SESSION displays these attributes: CURRENT DIRECTORY Path name of the current server directory. You can use the CD command to change it. HOME DIRECTORY Default directory. LIST_COUNT Current list count. LOG FILE Current log file. MESSAGEFILE Current message file.
Examples of SHOW SESSION MXCI Commands Examples of SHOW SESSION • A SHOW SESSION command and its output: >>SHOW SESSION +>; ---------------------------------Current Environment ---------------------------------CURRENT DIRECTORY /usr/manager/bin HOME DIRECTORY /usr/manager LIST_COUNT 5 LOG FILE MESSAGEFILE /usr/manager/bin/mxcierrors.cat TERMINAL CHARSET ISO88591 MESSAGEFILE LANG US English MESSAGEFILE VRSN {2003-12-11 13:56 NSK:SQUAW/SUPER.
SHOWCONTROL Command MXCI Commands SHOWCONTROL Command Examples of SHOWCONTROL The SHOWCONTROL command displays the access plan, controls, and system defaults in effect. Use SHOWCONTROL only within an MXCI session.
Examples of SHOWCONTROL MXCI Commands MATCH FULL specifies that attribute-name must be the same as the attribute name used in a CONTROL QUERY DEFAULT statement. MATCH PARTIAL specifies that attribute-name must be included in the attribute name used in a CONTROL QUERY DEFAULT statement. The default is MATCH PARTIAL. If attribute-name is a reserved word, such as MAX, MIN, or TIME, you must capitalize attribute-name and delimit it within double quotes (").
Examples of SHOWCONTROL MXCI Commands • Display output when CONTROL TABLE has not been executed in the current session: SHOWCONTROL TABLE; No CONTROL TABLE settings are in effect. --- SQL operation complete. • Issue multiple CONTROL TABLE statements followed by a SHOWCONTROL TABLE: CONTROL TABLE PERSNL.JOB MDAM 'OFF'; --- SQL operation complete. CONTROL TABLE * TIMEOUT '3000'; --- SQL operation complete. SHOWCONTROL TABLE; CONTROL TABLE SAMDBCAT.PERSNL.
Examples of SHOWCONTROL MXCI Commands • Change the TIMEOUT attribute and then issue a SHOWCONTROL DEFAULT for TIME, which is a reserved word: CONTROL QUERY DEFAULT TIMEOUT '2000'; --- SQL operation complete. SHOWCONTROL DEFAULT "TIME", MATCH PARTIAL; CONTROL QUERY DEFAULT TIMEOUT 2000 Current DEFAULTS STREAM_TIMEOUT TIMEOUT -1 2000 --- SQL operation complete. In this example, the TIME name matches the TIMEOUT and STREAM_TIMEOUT attributes.
Examples of SHOWCONTROL MXCI Commands • Display all settings and defaults in effect: >>showcontrol all; .. No CONTROL QUERY SHAPE settings are in effect. No CONTROL SESSION settings are in effect. No CONTROL TABLE settings are in effect. No CONTROL QUERY DEFAULT settings are in effect.
MXCI Commands Examples of SHOWCONTROL MAX_ROWS_LOCKED_FOR_STABLE_ACCESS 1 MDAM_SCAN_METHOD ON MIN_MAX_OPTIMIZATION ON MIN_COALITIONS MP_SUBVOLUME SKYOSTST MP_SYSTEM \HPIDMR5 MP_VOLUME $DATA01 MSCF_ET_REMOTE_MSG_TRANSFER 0.
SHOWDDL Command MXCI Commands --- SQL operation complete. >> SHOWDDL Command Considerations for SHOWDDL Examples of SHOWDDL The SHOWDDL command displays the DDL syntax used to create a table, view, or stored procedure as it exists in metadata, including the object’s dependent objects. The output returned by SHOWDDL can be used as input to MXCI to re-create the specified object, including its dependent objects. SHOWDDL is an SQL/MX extension.
Considerations for SHOWDDL MXCI Commands Considerations for SHOWDDL • SHOWDDL cannot replicate the original object exactly. For ways in which the output of SHOWDDL can differ from the original DDL used to create an object, see Differences Between SHOWDDL Output and Original DDL on page 4-68.You can use SHOWDDL only within an MXCI session. • • • SHOWDDL requires that TMF, NonStop SQL/MX, and MXCI be available and running on the system.
Considerations for SHOWDDL MXCI Commands • • • • • • • • • • • • • • • • SHOWDDL generates ALTER TABLE ADD COLUMN statements for each column that was added to the table. SHOWDDL also generates the comment '--The partition is offline-' before the DDL of each partition that is offline due to a partition management operation, and the DDL for the offline partitions is commented out. The entire partition clause is commented out if all of the partitions are offline.
Considerations for SHOWDDL MXCI Commands SQL/MP Conversion Issues Note these syntax conversions when you are displaying DDL for an SQL/MP table: • • • • • • • • • If you run SHOWDDL on an MP alias, the MP alias name is displayed as the table name unless you use the SQLMP option, in which case the SQL/MP table name is displayed. SHOWDDL fully qualifies all SQL/MP aliases and fully expands SQL/MP table names.
Considerations for SHOWDDL MXCI Commands • • • • • • • • SHOWDDL displays the EXTENT and MAXEXTENTS only for the primary partition of an SQL/MP table or index. The only allowed BLOCKSIZE supported by NonStop SQL/MX is 4096. If you do not specify the SQLMP option and an SQL/MP table has a BLOCKSIZE other than 4096, its BLOCKSIZE is still displayed as 4096 for SQL/MX syntax. If its BLOCKSIZE is 4096, it is not displayed because this is the default.
Examples of SHOWDDL MXCI Commands Examples of SHOWDDL • This is an example of SHOWDDL on an SQL/MX table that contains unique and primary key constraints: >>CREATE TABLE CAT.SCH.T1 (N INT NOT NULL, C INT NOT NULL UNIQUE, CONSTRAINT PK PRIMARY KEY (N) NOT DROPPABLE) STORE BY (C DESC, N) ATTRIBUTE MAXEXTENTS 600; >>SHOWDDL CAT.SCH.T1; CREATE TABLE CAT.SCH.T1 ( N INT NO DEFAULT -- NOT NULL NOT DROPPABLE , C INT NO DEFAULT -- NOT NULL NOT DROPPABLE , CONSTRAINT CAT.SCH.
Examples of SHOWDDL MXCI Commands • These are examples of SHOWDDL on tables with partitions that are offline. Note the commenting out of partitions that are offline, and the whole partition clause if all of the partitions are offline. >>SHOWDDL T1; CREATE TABLE CAT.SCH.T1 ( A INT DEFAULT NULL , B INT NO DEFAULT -- NOT NULL NOT DROPPABLE , C INT NO DEFAULT -- NOT NULL NOT DROPPABLE , CONSTRAINT CAT.SCH.T1_104871912_0091 PRIMARY KEY (B ASC, C DESC) NOT DROPPABLE , CONSTRAINT CAT.SCH.
Examples of SHOWDDL MXCI Commands STORE BY (C1 ASC, C2 ASC) ; • This is an example of SHOWDDL on an SQL/MP table. By default, SQL/MX syntax is used to output the DDL of the table, and file names are not fully qualified. >>CREATE TABLE T1 (name CHAR(10) DEFAULT 'nobody' HEADING 'NAME', SID LARGEINT NOT NULL, PRIMARY KEY (SID DESC), SSN INT UNSIGNED NOT NULL, birthdate DATE NOT NULL ) PARTITION ( \FIGARO.$DATA14.DEANCAT.
Examples of SHOWDDL MXCI Commands LOCATION \FIGARO.$DATA14.DEANCAT.T1 ) CREATE INDEX IDXA ON T1 ( A ASC ) CATALOG \FIGARO.$DATA17.DEANCAT KEYTAG 1 ; CREATE UNIQUE INDEX UIDX ON IXT ( A ASC ) CATALOG \FIGARO.$DATA17.DEANCAT KEYTAG 2 ; CREATE CONSTRAINT C1 ON IXT CHECK (A > 100) ; --- SQL operation complete. ; • This is an example of SHOWDDL on an SQL/MP table using the SQLMP syntax option. File names are shown fully qualified.
Examples of SHOWDDL MXCI Commands CATALOG \FIGARO.$DATA17.DEANCAT PARTITION ( \FIGARO.$DATA14.DEANCAT.T1 FIRST KEY 5000 ) ; CREATE CONSTRAINT C1 on \FIGARO.$DATA17.DEANCAT.T1 CHECK SID > 1000; • This is an example of SHOWDDL on a table with a trigger. The DDL of the triggers is shown, but the ALTER TRIGGER DISABLE statement is not displayed for triggers that are disabled.
Examples of SHOWDDL MXCI Commands CREATE VIEW CAT.SCH.V1 AS SELECT CAT.SCH.T2.KEYCOL, CAT.SCH.T2.VALCOL, CAT.SCH.T2.SSN, CAT.SCH.T2.SALARY FROM CAT.SCH.T2 TRANSPOSE CAT.SCH.T2.SSN, CAT.SCH.T2.SALARY AS CAT.SCH.T2.VALCOL KEY BY CAT.SCH.T2.KEYCOL; • This is an example of SHOWDDL on a stored procedure. >>CREATE PROCEDURE CAT.SCH.T110_IO_NN ( IN IN1 NUMERIC(9,3), OUT OUT2 NUMERIC(9,3) ) EXTERNAL NAME 't110.T110_io_nn (java.math.BigDecimal,java.math.
SHOWLABEL Command MXCI Commands SHOWLABEL Command Considerations for SHOWLABEL Examples of SHOWLABEL The SHOWLABEL command displays file-label information for SQL/MX objects. This information includes the object version, physical location, and other characteristics. Supported objects are tables, trigger temporary tables, views, and indexes. SHOWLABEL is an SQL/MX extension. SHOWLABEL {[namespace ] object-name | location-name } [, DETAIL ] namespace is: TABLE | INDEX object-name is: [catalog.][schema.
Considerations for SHOWLABEL MXCI Commands • • Indexes Triggers Considerations for SHOWLABEL Every SQL object includes a logical file label to store the object’s file attributes and information about its dependent objects. The resource fork is a new file that contains structural descriptions of a table. When an SQL/MX object is created, two physical files are instantiated: the data fork and the resource fork. The data fork is where the user data resides.
Considerations for SHOWLABEL MXCI Commands LastModTimestamp Date, time, and Julian timestamp indicating when the object’s data was last modified. LastOpenTimestamp Date, time, and Julian timestamp of last open time. NEVER OPENED is generated if the object has never been opened (for example, timestamp=0). SMDtable Indicates whether the object is a system metadata (SMD) table. User metadata tables are not SMD tables. File Organization The file organization of the object (for example, key-sequenced).
Examples of SHOWLABEL MXCI Commands Max Extents Maximum number of extents. EOF The relative byte address of the first byte of the next available block. Extents Allocated Number of extents currently allocated for the file. Index Levels Number of index levels used for index blocks. SHOWLABEL, DETAIL Output SHOWLABEL, DETAIL returns the SHOWLABEL output and some additional information. This table describes the additional information that SHOWLABEL, DETAIL provides.
Examples of SHOWLABEL MXCI Commands Owner: QADEV.
Examples of SHOWLABEL MXCI Commands Owner: QADEV.
Examples of SHOWLABEL MXCI Commands Low Key: ( 20 ) Partition[2]: \CARNAG.$LORI.ZSDQHSJZ.HMNX9K00 Low Key: ( 40 ) IndexMap Array - 2 index[es] Index[0]: \CARNAG.$BLANCA.ZSDQHSJZ.JH8TCM00 Index columns: 1 ASC , 0 ASC Index[1]: \CARNAG.$BLANCA.ZSDQHSJZ.
Examples of SHOWLABEL MXCI Commands IncompletePartBoundChg: F (If T, a Utility operation is in progress or has failed) RedoNeeded: F RollfwdNeeded: F UndoNeeded: F UnreclaimedSpace: F (If T, a Utility operation is in progress or has failed) Primary Extent Size: 16 Pages Secondary Extent Size: 64 Pages Max Extents: 160 Extents Allocated: 0 EOF: 0 Index Levels: 0 ============================================================= • Use the SHOWLABEL, DETAIL command with a physical location (Guardian) name: >>sh
Examples of SHOWLABEL MXCI Commands failed) CrashLabel: F CrashOpen: F IncompletePartBoundChg: F (If T, a Utility operation is in progress or has failed) RedoNeeded: F RollfwdNeeded: F UndoNeeded: F UnreclaimedSpace: F (If T, a Utility operation is in progress or has failed) Primary Extent Size: 16 Pages Secondary Extent Size: 64 Pages Max Extents: 160 Extents Allocated: 0 EOF: 0 Index Levels: 0 Record Expression Label Length: 9168 Security Label Length: 120 Key Columns: 0 ASC Partitioning Scheme: RP Part
Examples of SHOWLABEL MXCI Commands • Use the SHOWLABEL, DETAIL command with a physical location (Guardian) name on a table with a SYSKEY: >>showlabel $FL0115.ZSDJNQHX.Z91KC400,detail; ============================================================= GuardianName: \BERT.$FL0115.ZSDJNQHX.Z91KC400 AnsiName: TESTCAT.TESTSCH.Y4 AnsiNameSpace: TA ObjectSchemaVersion: 1200 ObjectFeatureVersion: 1200 Owner: QADEV.
Examples of SHOWLABEL MXCI Commands Index Levels: 0 Record Expression Label Length: 46656 Security Label Length: 120 Key Columns: 2 ASC , 3 ASC , 5 ASC , 6 ASC , 7 ASC , 8 ASC , 9 ASC , 10 ASC, 0 ASC Partitioning Scheme: RP Partition Array - 1 partition[s] IndexMap Array - 4 index[es] Index[0]: \BERT.$FL0115.ZSDJNQHX.PJLVC400 Index columns: 11 ASC Index[1]: \BERT.$FL0115.ZSDJNQHX.CL17H400 Index columns: 15 ASC Index[2]: \BERT.$FL0115.ZSDJNQHX.L3ZHK400 Index columns: 16 ASC Index[3]: \BERT.$FL0115.
SHOWSHAPE Command MXCI Commands SHOWSHAPE Command The SHOWSHAPE command displays the control query shape for a given DML statement. You can use the result at a later time to force the same access plan for the statement. See CONTROL QUERY SHAPE Statement on page 2-35 and SET SHOWSHAPE Command on page 4-50. Use SHOWSHAPE only within an MXCI session. SHOWSHAPE statement statement is an SQL DML statement.
Examples of SHOWSHAPE MXCI Commands • Display the access plan for the given statement: SET NAMETYPE NSK; SET MPLOC $DATA06.PERSNL; SHOWSHAPE SELECT first_name, last_name, deptnum, salary FROM persnl.employee WHERE salary > (SELECT MAX (salary) FROM persnl.employee WHERE deptnum = 1500); control query shape hybrid_hash_join(partition_access( sort_groupby(scan(path 'EMPLOYEE', forward, mdam off))), partition_access(scan(path 'EMPLOYEE', forward, mdam off))); --- SQL operation complete.
5 SQL/MX Utilities A utility is a tool that runs within NonStop SQL/MX or from the OSS shell and performs such tasks as importing data, duplicating files, fixing database discrepancies, and migrating metadata. SQL/MX utilities can be run from MXCI or from the OSS command line. For a description of MXCI, see MXCI SQL/MX Conversational Interface on page 1-2. For more information about OSS, see the Open System Services User’s Guide.
Privileges Required to Execute Utilities SQL/MX Utilities PURGEDATA Utility on page 5-76 Purges data from tables, indexes, or partitions. RECOVER Utility on page 5-80 Determines the state of a failed utility operation and restores recoverable objects. VERIFY Operation on page 5-82 Reports whether SQL/MX objects and programs are consistently described in file labels, resource forks, and metadata. Privileges Required to Execute Utilities Utility Privileges Required BACKUP Be the schema owner.
Checking File Locks SQL/MX Utilities Checking File Locks When you run the DUP, import, MODIFY, POPULATE INDEX or PURGEDATA utilities, they lock files. If the operation fails before completion, you need to check the file locks to determine if you need to run the RECOVER utility to undo or resume the failed partition operation. To find out whether a failed partition operation needs to be recovered, issue this query from an MXCI prompt: select substring(o.object_name from 1 for 40) as object_name, o.
DUP Utility SQL/MX Utilities DUP Utility Syntax Description of DUP Considerations for DUP DUP is a syntax-based utility that can be executed through MXCI. The DUP utility copies SQL/MX tables and optionally their indexes and constraints. DUP source-target-list [ mapping ][,dup-option [, dup-option]...] source-target-list is: { source-table TO target-table } source-table is: [[catalog].schema.]object target-table is: [{catalog | *}.{schema | *}.]object mapping is: { LOCATION (volume-map [, volume-map ] ...
Syntax Description of DUP SQL/MX Utilities Syntax Description of DUP source-target-list specifies the source-table and target-table names. source-table specifies the fully qualified name for the table to be copied. The form of the name is catalog-name.schema-name.table-name, where each part is an SQL identifier. If you do not specify the catalog and schema parts of the source-table, DUP uses the default catalog and schema values for that session. target-table specifies the name of the target table.
Syntax Description of DUP SQL/MX Utilities INDEX[ES] [{ON [(index-list)] | OFF }] is an optional clause that specifies how dependent indexes are copied. INDEX[ES] is the same as INDEX[ES] ON. Unpopulated indexes are not duplicated. ON [(index-list)] duplicates all user-created and system-generated indexes. If the source and target tables reside in the same catalog and schema, you must specify index-list to identify the new index names. The default is ON.
Syntax Description of DUP SQL/MX Utilities constraints and are duplicated if you specify CONSTRAINTS ON. NOT DROPPABLE constraints are always duplicated. ON duplicates all DROPPABLE unique, not null, primary key, and check constraints. The default is ON. If the source table has unique or droppable primary key constraints, the INDEX option must be set to ON, otherwise DUP returns an error. constraint-list is a list of constraint-maps. constraint-map specifies the target constraint name.
Considerations for DUP SQL/MX Utilities Considerations for DUP • • • • • You must have all privileges for the source table and own the schema where the target table will reside or be the super ID. Referential integrity constraints and triggers are ignored. The source table can exist on a remote node and be referenced by the current DUP operation if the remote node is visible to the local node. The target table can also exist in a catalog and schema that reside on a visible remote node.
Considerations for DUP SQL/MX Utilities To serialize these utility operations, NonStop SQL/MX has the concept of a DDL lock. This is a lock that prevents database structure changes from occurring while a utility request is executing. A utility request informs SQL that it is running, perform commands in as many transactions as necessary, then informs SQL that the operation has completed. While the utility request is running, no conflicting DDL or utility operation can occur.
Examples of DUP SQL/MX Utilities Examples of DUP • This example copies the partitions of the source table (using a different catalog and schema) to the same locations: DUP mycat.myschema.mytable1 TO mycat1.myschema1.*; • This example copies the partitions of the source table on $data1 and $data2 to the partitions of the target table on $data2 and $data3 respectively.
FIXUP Operation SQL/MX Utilities FIXUP Operation Considerations for FIXUP Operation Examples of FIXUP Operation FIXUP is an OSS command-line utility run from mxtool that repairs problems in the SQL/MX database that cannot be repaired by normal operations. mxtool utility-operation utility-operation is: FIXUP {guardian-option | object-option} guardian-option is LABEL guardian-file g-opts guardian-file is [\node.]$volume.subvolume.
FIXUP Operation SQL/MX Utilities { -a= { on | off } toggles the audit attribute on the label. If the audit attribute is ON and you issue a request to turn it on, FIXUP returns a warning that the audit attribute is already on. If the audit attribute is OFF and you issue a request to turn it off, FIXUP returns a warning. You must be the super ID to perform this operation. If you turn off auditing for the table, this invalidates online dumps.
FIXUP Operation SQL/MX Utilities object-name specifies the SQL object to be changed. It must be fully qualified with the catalog and schema name. o-opts are options available for an SQL object: • • Turn off the corrupt attribute Reset the redefinition timestamp { -rc [-d] } turns off the corrupt attribute on the label and in the PARTITIONS metadata table. FIXUP attempts to reset all local partitions associated with the object.
Considerations for FIXUP Operation SQL/MX Utilities If you request the -d option, FIXUP updates timestamps for all dependencies associated with the object. Table dependencies include indexes and trigger temporary tables. Each dependent object has its own redefinition timestamp, so each object is set to its own individual time. You must be the super ID to execute this request. If the metadata and label timestamps do not match, no warning is issued, but the label value is set to the metadata value.
SQL/MX Utilities • Examples of FIXUP Operation Suppose a disk or node failure occurs and you must recover table FIXUPtable. Following instructions in the SQL/MX Installation and Management Guide, you use saved DDL information to recreate the table and recover the privileges in the metadata, then execute the TMF RECOVER FILES command to recover the label, data, and resource forks. The metadata will now have a new object UID and the label information will have the old object UID.
GOAWAY Operation SQL/MX Utilities GOAWAY Operation Considerations for GOAWAY Examples of GOAWAY GOAWAY is an OSS command-line utility run from mxtool that removes Guardian files associated with an SQL/MX object. SQL/MX files consist of two physical Guardian files, the data fork and the resource fork. Normally, when the data fork is dropped, DP2 automatically drops the corresponding resource fork. In some cases, either an orphaned resource fork or data fork might exist.
Syntax Description of GOAWAY SQL/MX Utilities If you do not specify this option, the default is -both. -df directs GOAWAY to drop a data fork file. guardian-file must be the name of the data fork. Successful delete of a data fork with the data fork option generates an informational message. If you specify a resource fork name, the operation fails. -rf directs GOAWAY to drop a resource fork file. guardian-file must be the name of the resource fork. If you specify a data fork name, the operation fails.
Considerations for GOAWAY SQL/MX Utilities resource fork). If you specify!, GOAWAY does not ask for confirmation but performs the requested operation. If you do not specify this option, GOAWAY returns with the name of the file it plans to drop. You must confirm (YES) or reject (NO) this action. If you specify YES, the operation continues to the next file that matches the list of files specified in the guardian-file.
Examples of GOAWAY SQL/MX Utilities • Drop a resource fork file: mxtool goaway \$data09.ZSDT6TG2.BLJ35501 -rf ! Goaway of file:\FIGARO.$DATA09.ZSDT6TG2.BLJ35501 successful • Drop a file and skip the step that extracts ANSI information: mxtool goaway \\FIGARO.$DATA09.ZSDLLS6G.QJ1QNR00 -s ! Goaway of file: \FIGARO.$DATA09.ZSDLLS6G.QJ1QNR00 successful Goaway of file: \FIGARO.$DATA09.ZSDLLS6G.QJ1QNR01 successful • Attempt to drop a file with an invalid node name: mxtool goaway \DATA09.ZSDKJWZP.
Examples of GOAWAY SQL/MX Utilities \FIGARO.$DATA09.ZSDLLS6G.WKPRKR00 but a resource fork exists \FIGARO.$DATA09.ZSDLLS6G.WKPRKR01. • Attempt to drop only a resource fork of a file with both forks: mxtool goaway \$DATA09.ZSDLLS6G.WKPRKR01 -rf *** ERROR[20451] You asked to drop only the resource fork \FIGARO.$DAT09.ZSDLLS6G.WKPRKR01 but a data fork exists \FIGARO.$DAT09.ZSDLLS6G.WKPRKR00. • Attempt to drop a Guardian file on a remote system: mxtool goaway \\SQUAW.\$DATA09.ZSDLLSRG.
import Utility SQL/MX Utilities import Utility Considerations for import Parallel Load for import Examples of import The import utility imports data from an input file in ASCII or UCS2 format into an SQL/MX table. This utility supports OSS large files (files greater than 2 GB) as input files. The import utility executes at the OSS or MXCI command prompt using the command-line options described next. You cannot directly execute the import utility from programs. Note.
import Utility SQL/MX Utilities To import data to the table mycat.mysch."%&*()", you must specify the delimited table name within the import command: import 'mycat.mysch."%&*()"' -I myinput.dat The delimited name is enclosed within a pair of double quotes (") and the fully qualified name of the destination table and the data are enclosed in single quotes (‘). -I input-filename specifies the name of the input file that contains the data to import.
import Utility SQL/MX Utilities specify both a field-delimiter and a row-delimiter, they cannot be the same character. If you are running import from the MXCI command prompt and are using special characters as field delimiters, you must enclose special characters in single or double quotes (for example, '|*|'). If you are running import from the OSS command prompt and are using special characters as field delimiters, you must use the escape character "\" before special characters.
Considerations for import SQL/MX Utilities -T transaction-size specifies the number of records processed before a commit. If import returns an error before the record count reaches transaction-size, the changes to the database within that transaction are rolled back. The number of imported rows is the number successfully committed. You might want to set the -T option to less than 500 to avoid lock escalation. If you do not specify this parameter the default transaction-size is 10,000 records.
Considerations for import SQL/MX Utilities • • It has no droppable primary key, unique key, or foreign key constraints. It has no enabled triggers or you specified the -D option to disable triggers. To improve the performance of the fast-loading technique, import turns off the audit attribute for the entire table at the start of the operation and turns it back on when the operation ends.
Considerations for import SQL/MX Utilities If the import operation fails unexpectedly, the RECOVER utility does not reenable triggers that were disabled before running import. You must reenable them. For expected errors, error handling ensures that triggers are reenabled. No restart facility is available to handle partially copied data. Concurrency If you are importing into an empty table or if the target table does not have index or referential integrity constraints, import uses fast-loading techniques.
Considerations for import SQL/MX Utilities FourDigitYear=four_year Y or N. Default is Y; 4 digits (for example, 12/25/1997). You have the option of specifying a two-digit year date or timestamp value. If you specify two digits and the year value is less than 30, import assumes the first two digits of the year to be 20. If the year value is greater than or equal to 30, import assumes the first two digits of the year to be 19. DecimalSymbol=decimal One character. Default is a decimal point (.).
Considerations for import SQL/MX Utilities RecordLength=record_length A decimal ASCII number that specifies the physical record length (in characters, not bytes) of each input row. The length must include the row delimiter, if used. You must specify record_length for fixed width format. The value specified for record_length must be greater than or equal to (start + length 1) / (number of bytes per character) for all subsequent col= lines in this section of the format file.
Considerations for import SQL/MX Utilities Format File Considerations––import Format File for a DELIM Input File If the input file type is DELIM and you want to use a format file, you must include the [COLUMN FORMAT] section. The other sections are optional. See [COLUMN FORMAT] on page 5-27. Format File for a FIXED Input File If the input file type is FIXED, you must specify a format file that includes the [COLUMN FORMAT] and [FIXED WIDTH FORMAT] sections.
Considerations for import SQL/MX Utilities Use a field qualifier to include field or row delimiters as part of the field data. For example, suppose that your input file uses a comma (,) to delimit the fields in a record. Suppose further that a record contains a field consisting of these characters: Jackson,Jane You can use a field qualifier to ensure that the comma (,) is included in this field. You are not required to use a field qualifier for other fields in the row.
Considerations for import SQL/MX Utilities column allows null. Some employees have no middle initial. As a result, the input file contains records like this: 2961,Mary,,Smith,143,3490,80000.00 To insert null in a nullable target column, you can specify two consecutive field delimiters as shown in the preceding example. To insert blanks in the target column, you can specify two field delimiters with the appropriate number of blanks between the delimiters.
Considerations for import SQL/MX Utilities Two-Digit Year Input Values for Input File You have the option of specifying a two-digit year date or timestamp value in the [DATE FORMAT] section of a format file. If you do and the year value is less than 30, import assumes the first two digits of the year to be 20. If the year value is greater than or equal to 30, import assumes the first two digits of the year to be 19.
Considerations for import SQL/MX Utilities If a character in the data file cannot be translated into one required by the target column, NonStop SQL/MX issues an error. Importing an UCS2 data file into an ISO88591 column with character' code values beyond the range of ISO88591 leads to this translation error condition. Datetime and Interval Data for Input File For datetime and interval data, do not specify keywords that are part of the data type in the column definition.
Considerations for import SQL/MX Utilities import and Nullable Columns Suppose you need to import into a table that allows nullable columns. Follow these guidelines: If you specify that the input file is in delimited format: • • • You can specify a null value for a particular column value with a record in the input file by using two successive field delimiters. In the case of the first column, start the record with a field delimiter.
Considerations for import SQL/MX Utilities • ° You can specify that the column be given the default value (for the column) by starting the input data specification with the character “D” or “d”. import ignores anything following that and preceding the end of the input field. ° If the first character of the input data is anything other than “N”, “n”, “D”, or “d”, import ignores the first character.
Examples of import SQL/MX Utilities You might specify the three import commands as: C:\>import corpcat.persnl.employee -I empfile -C 2999 -T 500 C:\>import corpcat.persnl.employee -I empfile -C 1999 -F 3000 -T 500 C:\>import corpcat.persnl.employee -I empfile -C 1999 -F 5000 -T 500 The number of records for each partition must be less than or equal to the space available in each partition, and the rows to be imported into each partition must have an appropriate clustering key.
Examples of import SQL/MX Utilities 7,"Test String 7","111-222-3333","222-333-4444" 8,"Test String 8","111-222-3333","222-333-4444" Format File Describing the Data Create a format file, FORMFILE, which consists of [DATE FORMAT], [COLUMN FORMAT], and [DELIMITED FORMAT] sections: [DATE FORMAT] DateOrder=MDY DateDelimiter=/ TimeDelimiter=: FourDigitYear=Y DecimalSymbol=.
Examples of import SQL/MX Utilities col=id,N col=company,N col=phone,N col=fax,N [FIXED WIDTH FORMAT] col=id,1,11 col=company,14,16 col=phone,33,12 col=fax,48,12 RecordLength=61 All commas and double-quote characters in the input file are ignored because they are not covered by any of the col= entries in the [FIXED WIDTH FORMAT] section of the format file. Also, in this example the RecordLength value of 61 includes one newline character at the end of each input record.
Examples of import SQL/MX Utilities RecordLength =5 col=col1,1,5 import Load Command This import command imports data into the table_2 table from the delimited input file named COINPUT using the format file FORMFILE: import cat.sch.
INFO Operation SQL/MX Utilities INFO Operation Considerations for INFO Examples of INFO INFO is an OSS command-line utility run from mxtool that displays information about SQL/MX files. INFO displays the Guardian file name, the ANSI name, the ANSI namespace, and the object schema version. INFO [\node.]\$volume.subvol.filename [node.]\$volume.subvol.filename is the Guardian qualified file set list that specifies the set of Guardian files that is being queried.
Examples of INFO SQL/MX Utilities • The object schema version Examples of INFO • These are examples of INFO queries: mxtool mxtool mxtool mxtool • INFO INFO INFO INFO \\figaro.\$data*.*svol*.* \\figaro.\$*.*.* \\figaro.\$vol.subvol.file* \\figaro.\$vol.subvol*.file*00 This is an example of an INFO query on SQL/MX catalogs using a wild card: mxtool INFO \$DATA09.ZSD0.CATSYS0* File Name: \FIGARO.$DATA09.ZSD0.CATSYS00 Object Schema Version: 1200 Ansi Name: NONSTOP_SQLMX_FIGARO.SYSTEM_SCHEMA.
migrate Utility SQL/MX Utilities migrate Utility Considerations for migrate Examples of migrate The migrate utility is an OSS command-line utility that copies SQL/MP metadata from SQL/MX Release 1.8 user metadata tables to SQL/MX Release 2.x system metadata tables. migrate handles full or partial migrations of SQL/MP metadata. Use the migrate utility immediately after installing SQL/MX Release 2.x after creating the catalogs and schemas in the SQL/MX Release 2.x database.
migrate Utility SQL/MX Utilities SHOW displays existing entries from the SQL/MP metadata tables. ALL displays all entries in the MPALIAS, DEFAULTS, ODBC (MXCS), and PROCS metadata tables. The default is ALL. MPALIAS displays the names of all the entries in the MPALIAS metadata table. DEFAULTS displays the names of all the entries in the DEFAULTS metadata table. ODBC displays the names of all the entries in the ODBC (MXCS) metadata tables: ZONAM2ID, ZOAS2DS, ZODS, ZOENV, and ZORES.
Considerations for migrate SQL/MX Utilities ALL migrates all entries in the MPALIAS, DEFAULTS, ODBC (MXCS), and PROCS metadata tables. The default is ALL. MPALIAS migrates entries in the MPALIAS metadata table. DEFAULTS migrates entries in the DEFAULTS metadata table. ODBC migrates entries in the OCBC (MXCS) ZONAM2ID, ZOAS2DS, ZODS, ZOENV, and ZORES metadata tables. PROCS migrates entries in the PROCS metadata table. SCRIPT migrates only those entries in the script file.
Examples of migrate SQL/MX Utilities System Requirements • • • TMF must be available and running on the system. SQL/MP must be installed and available on the system. SQL/MX Release 2.x must be installed and available on the system. Location of the migrate Utility Run the migrate utility from the /usr/tandem/sqlmx/bin directory. Recommendations • • • Run migrate after installing SQL/MX Release 2.x and after creating the necessary catalogs and schemas.
Examples of migrate SQL/MX Utilities == SQLMP ALIAS CREATE SQLMP ALIAS appcat.appsch.t1 \TEXMEX.$DATA01.SQLDATA.T1; CREATE SQLMP ALIAS appcat.appsch.t2 \TEXMEX.$DATA01. DATA.T2; /usr/tandem/sqlmx/bin: migrate EXECUTE SCRIPT script.out ERROR_LOG errlog.out > mig.
MODIFY Utility SQL/MX Utilities MODIFY Utility Considerations for MODIFY Examples of MODIFY MODIFY is a syntax-based utility that can be executed through MXCI that enables database administrators to perform partition operations on range and hash partitions of SQL/MX tables and indexes. Depending on the type of operation you are performing, MODIFY can be run as an online or offline operation. See Considerations for MODIFY on page 5-58 for details about limitations on online operations.
Reuse an Existing Partition of a Range Partitioned Table SQL/MX Utilities LOCATION [\node.]$volume[.subvolume.file-name] | [KEY=] {FIRST | LAST} PARTITION | [KEY=] key-value is a location for a partition, or the partitioning key (the FIRST KEY) value (key-value) of a partition, to be modified. If the partition is the primary partition, you can also specify the partition using the FIRST PARTITION phrase.
SQL/MX Utilities Manage Partitions of Range Partitioned Tables and Indexes Manage Partitions of Range Partitioned Tables and Indexes Use MODIFY to manage range partitions of SQL/MX tables and indexes. You must manage tables and indexes separately regardless of their relationship. Both offline and online operations are supported. See Considerations for MODIFY on page 5-58 for details about limitations on online operations.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities commit-options is: { COMMIT [ WORK ] [ WHEN READY ] } { [ { AFTER time } ] } { [ { BEFORE time } ] } [[catalog.]schema.]object is the name of the range partitioned object. If you do not specify the schema and catalog name, NonStop SQL/MX uses the default catalog and schema of your MXCI session. object is a table or an index, depending on the TABLE or INDEX keyword.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities add-move-boundary-range is the boundary range. | [KEY=] FIRST KEY UPTO [KEY=] key-value [KEY=] key-value [THRU [KEY=] LAST KEY] specifies the partitioning range add-move-boundary-range of a partition to be split and then added to a new partition.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities | | LOCATION [\node.]$volume[.subvolume.file-name] [KEY=] {FIRST | LAST} PARTITION [KEY=] key-value is a location for a partition, or the partitioning key (the FIRST KEY) value (key-value) of a partition, to be modified. If the partition is the primary partition, you can also specify the partition using the FIRST PARTITION phrase.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities the size of the primary extent and secondary extents separately. If you do not specify EXTENT, MODIFY uses the extent size values of the source partition. See EXTENT on page 8-6 and MAXEXTENTS on page 8-7. WITH SHARED ACCESS [commit-options] specifies that the operation is an online operation. If you do not specify commit-options, the default is COMMIT WHEN READY.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities new-partition is: LOCATION [\node.]$volume[.subvolume.file-name] [[catalog.]schema.]object is the name of the object. If you do not specify the schema and catalog name, MODIFY uses the current default schema and catalog of your MXCI session. object is a table or an index, depending on the TABLE or INDEX keyword. DROP [PARTITION] WHERE partition-identification is the hash partition to be dropped.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities MOVE [PARTITION] [WHERE partition-identification] [TO] LOCATION new-partition [partition-size] is an existing hash partition that is to be moved to a new location. You can define the size of the new partition using the optional partition-size clause. Otherwise, the values of the primary partition apply. partition-identification is optional only when the object has only one partition. partition-identification describes the partition.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities specify MAXEXTENTS, MODIFY checks all partitions and uses the value of the source partition. partition-extent-size is the extent size of the new partition. EXTENT { ext-size { (pri-ext-size, sec-ext-size) } } ext-size is an unsigned integer value. You can specify it as the size for both primary and secondary extents of the new partition. You can specify the size of the primary extent and secondary extents separately.
Manage System-Clustered Tables SQL/MX Utilities EXTENT { ext-size { (pri-ext-size, sec-ext-size) } } ext-size is an unsigned integer value. You can specify it as the size for both primary and secondary extents of the new partition. You can specify the size of the primary extent and secondary extents separately. If you do not specify EXTENT, MODIFY uses the largest extent size possible using the combination of primary, secondary and max extent values. See EXTENT on page 8-6 and MAXEXTENTS on page 8-7.
Considerations for MODIFY SQL/MX Utilities extents the partition can have. If you do not specify MAXEXTENTS, MODIFY uses the value of the primary partition. partition-extent-size is the extent size of the new partition EXTENT { ext-size { (pri-ext-size, sec-ext-size) } } ext-size is an unsigned integer value. You can specify it as the size for both primary and secondary extents of the new partition. You can specify the size of the primary extent and that of secondary extents separately.
Considerations for MODIFY SQL/MX Utilities Offline Partition Management for Range Partitions MODIFY supports these offline partition management operations for range partitions: • • • • • • • Adding a new empty partition. Dropping an existing empty partition. Moving an existing partition to a new location. Splitting an existing partition and then moving the first or last part of the data to a new partition.
Considerations for MODIFY SQL/MX Utilities To specify the number of rows to be copied in a transaction, use the CONTROL QUERY DEFAULT statement or insert an entry to the SYSTEM_DEFAULTS table. For offline partition operations, use the PM_OFFLINE_TRANSACTION_GRANULARITY attribute. For online partition operations, use the PM_ONLINE_TRANSACTION_GRANULARITY attribute.
Considerations for MODIFY SQL/MX Utilities MODIFY and Table Reloading Some of MODIFY’s options start a FUP RELOAD process that runs in the background. Until this process completes, you cannot do DDL or utility operations on the file. You can monitor the reload process’s progress with this command: FUP STATUS physical-file-name If FUP STATUS returns a RELOAD COMPLETED message and the physical file is not being opened by another process, you can start the next MODIFY operation.
Examples of MODIFY SQL/MX Utilities Examples of MODIFY • Move all records of an existing range partition to a new location: MODIFY TABLE tab1 MOVE PARTITION WHERE LOCATION $data02 TO LOCATION $data03; • Move records of an existing range partition, whose key is equal to 10000 to the last key, to a new location: MODIFY TABLE tab1 MOVE PARTITION WHERE KEY = VALUE (10000) THRU KEY = LAST KEY TO LOCATION $data02 EXTENT (512, 512) MAXEXTENTS 256; • Move the second partition of a hash partitioned table to
mxexportddl Utility SQL/MX Utilities mxexportddl Utility Considerations for mxexportddl mxexportddl is an OSS command-line utility that captures user SQL/MX metadata and saves it in XML format. This utility supports OSS large files (files greater than 2 GB) as output files. . mxexportddl {-I input-table-name | -S catalog-name.schema-name | -H} [-O export-metadata-file-name] [-C] mxexportddl must be lowercase. -I input-table-name specifies the fully qualified name for the SQL/MX Release 2.
Considerations for mxexportddl SQL/MX Utilities -O export-metadata-file-name [-C] is the name of a OSS text file that will contain the export metadata output created by mxexportddl. The file name is an OSS file that can include an optional path specification. This file’s file type should be .xml. If the output file exists and you do not specify the -C option, output is appended to the existing file. The existing output file must have the proper XML export metadata header tags.
MXGNAMES Utility SQL/MX Utilities MXGNAMES Utility Considerations for MXGNAMES Examples of MXGNAMES MXGNAMES is a Guardian program that is run from a TACL prompt or an OBEY command file. It converts one or more ANSI table names into a list of corresponding Guardian file names, appropriately formatted for TMF or BACKUP/RESTORE 2.
MXGNAMES Utility SQL/MX Utilities SQLMX-table-name is a single fully qualified SQLMX table name entered directly on the command line output-format indicates what subsystem the output file is to be used with: -BR2 indicates output should be formatted for use with the BR2 RESTORE command.
Considerations for MXGNAMES SQL/MX Utilities -HELP displays help for the utility. Considerations for MXGNAMES You must have READ/WRITE access to the Guardian subvolume where you are executing MXGNAMES. Input and output of MXGNAMES is in standard Guardian EDIT files, which have these characteristics: • • Guardian file code of 101 Maximum line length of 255 characters You can use other tools or programs to capture data for use with MXGNAMES.
Examples of MXGNAMES SQL/MX Utilities location $VOL1.ZSDA126B.BXNW1R00 hash partition by (c4) ( add location $VOL2.ZSDA126B.BXNW2R00 , add location $VOL3.ZSDA126B.BXNW3R00 , add location $VOL4.ZSDA126B.BXNW4R00 ) ; create unique index T126B_NDX1 on CAT.SCH.T126B(C2, C1) LOCATION $vol1.ZSDA126b.qdx1g100 hash partition by (c2) ( add location $VOL2.ZSDA126B.QDX1G200 , add location $VOL3.ZSDA126B.QDX1G300 , add location $VOL4.ZSDA126B.QDX1G400 , add location $VOL5.ZSDA126B.
Examples of MXGNAMES SQL/MX Utilities _ISO88591'abcd' , C4 SMALLINT NO DEFAULT -- NOT NULL NOT DROPPABLE , CONSTRAINT CAT.SCH.T126A_106009919_0001 PRIMARY KEY (C1 ASC, C2 ASC) NOT DROPPABLE , CONSTRAINT CAT.SCH.T126A_106009919_0000 CHECK (CAT.SCH.T126A.C1 IS NOT NULL AND CAT.SCH.T126A.C2 IS NOT NULL AND CAT.SCH.T126A.C4 IS NOT NULL) NOT DROPPABLE ) LOCATION \NSK.$VOL1.ZSDA126A.BXNL1R00 NAME PART_A_Z_1 PARTITION ( ADD FIRST KEY (1000) LOCATION \NSK.$VOL2.ZSDA126A.
Examples of MXGNAMES SQL/MX Utilities $VOL4.ZSDA126A.QDXWG4* & -- End of table CAT.SCH.T126A ) -- • This example prepares a list of file names to be used with TMF. The input is an SQL table name. MXGNAMES CAT.SCH.T126A -output=NAMELSTX -TMF The contents of NAMELSTX are identical to the output file of the second example. • This example uses MXGNAMES with TMF. The input is a list of SQL names with the file length specified. MXGNAMES -SQLNames=$VOL1.SQLSTUFF.
Examples of MXGNAMES SQL/MX Utilities \PNODE.$VOL6.ZSDA126A.BXNL6R00 \PNODE.$VOL1.ZSDA126A.QDXWG100 \PNODE.$VOL2.ZSDA126A.QDXWG200 \PNODE.$VOL3.ZSDA126A.QDXWG300 \PNODE.$VOL4.ZSDA126A.QDXWG400 \PNODE.$VOL1.ZSDA126A.BXNW1R00 \PNODE.$VOL2.ZSDA126A.BXNW2R00 \PNODE.$VOL3.ZSDA126A.BXNW3R00 \PNODE.$VOL4.ZSDA126A.BXNW4R00 \PNODE.$VOL1.ZSDA126A.QDX1G100 \PNODE.$VOL2.ZSDA126A.QDX1G200 \PNODE.$VOL3.ZSDA126A.QDX1G300 \PNODE.$VOL4.ZSDA126A.QDX1G400 \PNODE.$VOL5.ZSDA126A.
mxtool Utility SQL/MX Utilities mxtool Utility mxtool is an OSS command-line utility that performs various utility functions. mxtool utility-operation utility-operation is { FIXUP fixup operation GOAWAY goaway operation HELP [help options] INFO info operation VERIFY verify operation | | | | } help options is { ALL | FIXUP | GOAWAY | INFO | VERIFY } mxtool utility-operation executes this utility, which must appear in lowercase letters. utility-operation is the operation to be performed.
POPULATE INDEX Utility SQL/MX Utilities POPULATE INDEX Utility Considerations for POPULATE INDEX Examples of POPULATE INDEX POPULATE INDEX is a syntax-based utility that can be executed through MXCI. The POPULATE INDEX utility loads SQL/MX indexes. POPULATE INDEX index-name ON [[catalog.]schema.]table-name Syntax Description of POPULATE INDEX index-name is the name of the index to populate. An error is returned if index-name cannot be found. [[catalog.]schema.
Considerations for POPULATE INDEX SQL/MX Utilities run the RECOVER operation with the incorrect option, RECOVER displays an error message so you can rerun it with the correct option. See Checking File Locks on page 5-3 for details. No restart facility is provided to recover partially-loaded data. • • • To avoid TMF limitations if a large amount of data is to be moved, POPULATE INDEX runs in multiple TMF transactions. The actual loading of the data is performed outside a TMF transaction.
Examples of POPULATE INDEX SQL/MX Utilities Examples of POPULATE INDEX • This example loads the specified index from the specified table: POPULATE INDEX myindex ON mycat.myschema.
PURGEDATA Utility SQL/MX Utilities PURGEDATA Utility Considerations for PURGEDATA Examples of PURGEDATA PURGEDATA is a syntax-based utility that can be executed through MXCI. The PURGEDATA utility deletes all data from an SQL/MX table and its related indexes or from specified partitions of tables that have no indexes. PURGEDATA table-name [list-of-partitions] [IGNORE_TRIGGER] table-name is: [ [catalog.]schema.
Syntax Description of PURGEDATA SQL/MX Utilities this list. PURGEDATA returns errors if the specified partitions do not exist, if dependent indexes exist on the table, and if the source object does not exist. partition-map describes a partition or range of partitions: guardian-name specifies the partially or fully qualified Guardian name that identifies the partition. If you specify only the volume, all partitions on the volume that belong to the object are affected.
Considerations for PURGEDATA SQL/MX Utilities Considerations for PURGEDATA • • • • • • • You must have ALL privileges on the table. An error is returned if you specify a list-of-partitions for a hash-partitioned table. For hash-partitioned objects, data must be purged from the entire table. table-name can exist on a remote node and be referenced by the current PURGEDATA operation if the remote node is visible to the local node.
Examples of PURGEDATA SQL/MX Utilities Examples of PURGEDATA • This example purges the data in the specified table. If the table has indexes, their data is also purged. PURGEDATA mycat.myschema.mytable; • This example purges the data in the specified partition, which has a Guardian name: PURGEDATA mycat.myschema.mytable WHERE LOCATION $DATA1.ZSDA09TO.QZ780000; • This example purges data from all partitions of the table: PURGEDATA mycat.myschema.
RECOVER Utility SQL/MX Utilities RECOVER Utility Considerations for RECOVER Examples of RECOVER RECOVER is a syntax-based utility that can be executed through MXCI. The RECOVER utility determines the state of a failed utility operation and executes its recovery procedure. RECOVER completes the failed utility operation by rolling back the entire operation or by completing the operation.
Considerations for RECOVER SQL/MX Utilities CANCEL If you specify CANCEL, RECOVER attempts to undo the effects of the failed utility operation. Otherwise, recovery fails. The default is CANCEL. RESUME If you specify RESUME, RECOVER attempts to carry the failed utility operation to its completion. Otherwise, the recovery fails. Considerations for RECOVER • • You must have the privileges required to perform the utility you are recovering.
VERIFY Operation SQL/MX Utilities VERIFY Operation Considerations for VERIFY Examples of VERIFY VERIFY is an OSS command-line utility run from mxtool that reports whether SQL/MX objects and programs are consistently described in file labels, resource forks, and metadata. mxtool utility-operation utility-operation is: VERIFY { object-option | file-option } object-option is: catalog.schema.object name is catalog.schema.object file option is: PART [\node.]$volume.subvol.
Considerations for VERIFY SQL/MX Utilities If you do not specify \node, the default is the Guardian system named in your =_DEFAULTS define. You can find the Guardian (physical) file name by using the SHOWLABEL command. For example: SHOWLABEL CAT.SCH.T1, DETAIL; For details on this command, see SHOWLABEL Command on page 4-78. Considerations for VERIFY You must have SELECT privilege for all columns of the table you are verifying.
Examples of VERIFY SQL/MX Utilities Security Considerations • • • • • VERIFY does not check privilege information. You must be the super ID, be owner of the schema where the object being verified resides, or have SELECT privilege on the object being verified. VERIFY obtains read-only locks on metadata while verifying an object. Other operations that read metadata can run concurrently.
Examples of VERIFY SQL/MX Utilities STORE BY (C1 ASC); CREATE INDEX VERIFY_T1_NDX2 ON payroll.dec2000.hourly ( C3 ASC ) LOCATION \SQUAW.$DATA08.ZSDVVVVV.T1X20100 NAME SQUAW_DATA08_ZSDVVVVV_T1X20100 PARTITION ( ADD FIRST KEY (_ISO88591'a1') LOCATION \SQUAW.$DATA08.ZSDVVVVV.T1X20200 NAME SQUAW_DATA08_ZSDVVVVV_T1X20200 EXTENT (16, 128) MAXEXTENTS 200 , ADD FIRST KEY (_ISO88591'a2') LOCATION \SQUAW.$DATA08.ZSDVVVVV.
Examples of VERIFY SQL/MX Utilities Verifying Partition Map: \SQUAW.$DATA08.ZSDVVVVV.T1000200 Verifying Index Map : \SQUAW.$DATA08.ZSDVVVVV.T1000200 Verifying label for partition : \SQUAW.$DATA08.ZSDVVVVV.T1000300 Verifying resource fork for partition: \SQUAW.$DATA08.ZSDVVVVV.T1000300 Verifying constraints: \SQUAW.$DATA08.ZSDVVVVV.T1000300 Verifying Partition Map: \SQUAW.$DATA08.ZSDVVVVV.T1000300 Verifying Index Map : \SQUAW.$DATA08.ZSDVVVVV.T1000300 Verifying label for partition : \SQUAW.$DATA08.
6 SQL/MX Language Elements NonStop SQL/MX language elements, which include data types, expressions, functions, identifiers, literals, and predicates, occur within the syntax of SQL/MX statements and MXCI commands. The statement and command topics support the syntactical and semantic descriptions of the language elements in this section.
SQL/MX Language Elements Catalogs Catalogs SQL/MX Catalogs An SQL/MX catalog is a named logical object that contains descriptions of a set of schemas. You can access SQL/MX objects with the three-part name of the actual object. The ANSI SQL:1999 catalog name is an SQL identifier. In SQL/MX Release 2.x, ANSI catalogs do not have any physical representation, nor do they have a physical relationship to SQL/MP catalogs.
Character Sets SQL/MX Language Elements Character Sets When you run the InstallSqlmx script during NonStop SQL/MX installation, you specify the NATIONAL_CHARSET attribute to select a default NCHAR character set of UCS2, ISO88591, KANJI, or KSC5601. If you do not specify a character set, the default is UCS2. Once the default is set, you cannot change it. For more information about setting this default, see the instructions for installing NonStop SQL/MX in the SQL/MX Installation and Management Guide. Note.
Restrictions on Using Character Set Data SQL/MX Language Elements ISO88591 Field Where Found View text CREATE VIEW statement $volume specification CREATE CATALOG, CREATE TABLE, CREATE INDEX, CREATE PROCEDURE, CREATE VIEW, DUP, and PURGEDATA statements; MODIFY and RESTORE utilities SQL/MX names Names of catalogs, columns, constraints, indexes, schemas, stored procedures, tables, and views In addition, user data fields in SQL/MX tables must use either ISO88591 or UCS2.
SQL/MX Language Elements Collations Collations A collation is an object that contains rules for a collating sequence (the sequence in which characters are ordered for sorting), case, and character class and character string equivalence. Every character set has a collation. See Character Sets on page 6-3. To be compared, character strings must be from the same character set.
SQL/MX Language Elements Columns Columns Examples of Derived Column Names A column is a vertical component of a table and is the relational representation of a field in a record. A column contains one data value for each row of the table. A column value is the smallest unit of data that can be selected from or updated in a table. Each column has a name that is an SQL identifier and is unique within the table or view that contains the column.
SQL/MX Language Elements Column Default Settings Column Default Settings You can define specific default settings for columns when the table is created. The CREATE TABLE statement defines the default settings for columns within tables. The default setting for a column is the value inserted in a row when an INSERT statement omits a value for a particular column. Examples of Derived Column Names • These two examples show how to use names for derived columns.
Constraints SQL/MX Language Elements Constraints An SQL/MX constraint is an object that protects the integrity of data in a table by specifying a condition that all the values in a particular column or set of columns of the table must satisfy. NonStop SQL/MX enforces these constraints on SQL/MP and SQL/MX tables: CHECK Column or table constraint specifying a condition must be satisfied for each row in the table. For SQL/MX tables, check constraints cannot contain non-ISO88591 string literals.
SQL/MX Language Elements Creating and Dropping Constraints on SQL/MP Tables Constraint Names When you create a constraint, you can either specify a name for it or allow a name to be generated by NonStop SQL/MX. You can optionally specify both column and table constraint names. Constraint names are three-part logical names. Constraints have their own namespace within a schema, so a constraint name can have the same name as a table, index, or view.
SQL/MX Language Elements Correlation Names Correlation Names A correlation name is a name you can associate with a table reference that is a table, view, or subquery in a SELECT statement to: • • • Distinguish a table or view from another table or view referred to in a statement Distinguish different uses of the same table Make the query shorter A correlation name can be explicit or implicit.
SQL/MX Language Elements Database Objects Database Objects A database object is an SQL entity that exists in a namespace, maps to a Guardian file in most cases, and is registered in the system catalog. SQL/MX Release 2.x includes SQL/MX objects. SQL/MX DML statements can access both SQL/MX and SQL/MP objects. The subsections listed below describe these SQL/MX objects. Collations Constraints Indexes Partitions SQL/MP Aliases Stored Procedures Tables Triggers Views Ownership In SQL/MX Release 2.
SQL/MX Language Elements Database Object Names Database Object Names Logical Names for SQL/MX Objects Physical Names for SQL/MP Objects Logical Names for SQL/MP Objects DEFINE Names for SQL/MP Objects SQL/MX Object Namespaces Considerations for Database Object Names SQL/MX DML statements can refer to SQL/MX database objects and SQL/MP database objects. To refer to a database object in a statement, use an appropriate database object name.
SQL/MX Language Elements Logical Names for SQL/MP Objects You can choose to use physical names to refer to SQL/MP tables and views by setting the NAMETYPE attribute to NSK. If the NAMETYPE is NSK, NonStop SQL/MX automatically qualifies a physical table or view name with the current default node, volume, and subvolume names unless you explicitly specify these names with the object name. In SQL/MX releases earlier than SQL/MX Release 2.
SQL/MX Language Elements SQL/MX Object Namespaces You cannot use DEFINE names to refer to SQL/MX tables, views, partitions, or stored procedures. The advantages of using DEFINEs rather than Guardian physical names are: • DEFINE names are easier to understand than Guardian names. For example, the name =CUSTOMERS is simpler than the physical name \SYS.$VOL2.SALES.CSTMERS. See ADD DEFINE Command on page 4-3. • DEFINE names provide location independence.
SQL/MX Language Elements Considerations for Database Object Names You can use the CREATE SQLMP ALIAS command within your application to create the needed mappings from logical to physical names. This command has the form: CREATE SQLMP ALIAS catalog-name.schema-name.table-name [\node.]$volume.subvol.filename When this command is executed, a mapping is inserted as a row in the OBJECTS table. SQL/MP aliases are simulated ANSI names that represent the underlying Guardian physical names of SQL/MP objects.
Data Types SQL/MX Language Elements Data Types SQL/MX data types are either character, datetime, interval, or numeric (exact or approximate): Character String Data Types on page 6-19 Fixed-length and variable-length character data types. Datetime Data Types on page 6-23 DATE, TIME, and TIMESTAMP data types. Interval Data Types on page 6-28 Year-month intervals (years and months) and day-time intervals (days, hours, minutes, seconds, and fractions of a second).
SQL/MX Language Elements Comparable and Compatible Data Types Datetime Data Types Values of type datetime are mutually comparable and mutually assignable only if the types have the same datetime fields. A DATE, TIME, or TIMESTAMP value can be compared with another value only if the other value has the same data type. All comparisons are chronological.
Comparable and Compatible Data Types SQL/MX Language Elements In addition, if you are using an SQL/MP table that contains FLOAT columns (REAL, DOUBLE PRECISION) with user default values specified, a similarity check for the table with the compile-time default value might fail for some values, and NonStop SQL/MX will recompile the query. For some queries that use the default value, you might not be able to access a float column with a default value near the boundary value for Tandem float values.
SQL/MX Language Elements Character String Data Types You can select the rows from the table: >>select * from $vol.subvol.tfloat; C1 C2 C3 ----------- ----------- ------------------------10 ? -1.15792089237316160E+077 --- 1 row(s) selected. Character String Data Types Considerations for Character String Data Types SQL/MP Considerations for Character String Data Types SQL/MX includes both fixed-length character data and variable-length character data.
SQL/MX Language Elements Character String Data Types collation is the collation. The only allowed collation is DEFAULT. The UPSHIFT clause directs NonStop SQL/MX to upshift characters before storing them in the column. CHAR[ACTER] [(length [CHARACTERS])] [char-set] [collate-clause] [UPSHIFT] specifies a column with fixed-length character data. PIC[TURE] X[(length)] [DISPLAY] [char-set] [collate-clause] [UPSHIFT] specifies a column with fixed-length character data.
Character String Data Types SQL/MX Language Elements Considerations for Character String Data Types Difference Between CHAR and VARCHAR You can specify a fixed-length character column as CHAR(n), where n is the number of characters you want to store. However, if you store five characters into a column specified as CHAR(10), ten characters are stored where the rightmost five characters are blank.
SQL/MX Language Elements Character String Data Types SQL/MX, and you can select from the ISO88591, UCS2, KANJI or KSC5601 character sets. If you do not make a selection, the default is UCS2. Note. SQL/MX tables do not support the KANJI or KSC5601 character sets. If you attempt to create an SQL/MX table with these or other unsupported character set types, an SQL error is returned and the operation fails.
SQL/MX Language Elements Datetime Data Types You can also insert into or update NCHAR columns in SQL/MP tables. See Inserting Into or Updating SQL/MP NCHAR Columns on page 6-62.
SQL/MX Language Elements Datetime Data Types Considerations for Datetime Data Types Datetime Ranges The range of values for the individual fields in a DATE, TIME, or TIMESTAMP column is specified as: yyyy Year, from 0001 to 9999 mm Month, from 01 to 12 dd Day, from 01 to 31 hh Hour, from 00 to 23 mm Minute, from 00 to 59 ss Second, from 00 to 59 msssss Microsecond, from 000000 to 999999 SQL/MP Considerations for Datetime Data Types Not Equivalent to DATE, TIME, TIMESTAMP When accessing SQL/M
Datetime Data Types SQL/MX Language Elements • • • • • • DATETIME HOUR TO FRACTION(n) DATETIME MINUTE DATETIME MINUTE TO SECOND DATETIME MINUTE TO FRACTION(n) DATETIME SECOND DATETIME SECOND TO FRACTION(n) Selecting DATETIME Columns in SQL/MP Tables The SQL/MP DATETIME data type has a range of logically contiguous fields in this order: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, and FRACTION.
Datetime Data Types SQL/MX Language Elements ------------###### ###### ... NonStop SQL/MX returns a warning indicating that you selected an unsupported data type with undefined contents. SQL/MP Considerations for Datetime Data Types Equivalent to DATE, TIME, TIMESTAMP When accessing SQL/MP DATETIME columns, you can: • • Select SQL/MP DATETIME columns that are equivalent to DATE, TIME, or TIMESTAMP.
Datetime Data Types SQL/MX Language Elements Using SQL/MX Datetime Functions on DATETIME Data You can use SQL/MX datetime functions to select individual fields from a DATETIME column in an SQL/MP table. For example, suppose that an SQL/MP table has a DATETIME column defined as: MPDateTimeCol DATETIME MONTH TO DAY DEFAULT DATETIME '03-12' MONTH TO DAY You can select the month from this column: SELECT MONTH(MPDateTimeCol) FROM MPTable; (EXPR) ------... 3 ... See Datetime Functions on page 9-4.
Interval Data Types SQL/MX Language Elements Suppose that the current timestamp is 2000-01-26:10:24:10.212072. This expression involves extension on both ends: CAST(DATETIME '12-23' MONTH TO DAY AS TIMESTAMP) The result of the CAST is 2000-12-23:00:00:00.000000. Operations Equivalent to UNITS The SQL/MP UNITS operator is not supported. However, NonStop SQL/MX does support equivalent syntax.
SQL/MX Language Elements Interval Data Types {YEAR | MONTH | DAY | HOUR | MINUTE} [(leading-precision)] specifies the start-field. A start-field can have a leading-precision up to 18 digits (the maximum depends on the number of fields in the interval). The leading-precision is the number of digits allowed in the start-field. The default for leading-precision is 2. YEAR | MONTH | DAY | HOUR | MINUTE | SECOND [(fractionalprecision)] specifies the end-field.
SQL/MX Language Elements Interval Data Types To include a quoted string in a signed interval data type, the sign must be outside the quoted string. It can be before the entire literal or immediately before the duration enclosed in quotes.
Numeric Data Types SQL/MX Language Elements In general, a FRACTION end field in NonStop SQL/MP is interpreted in NonStop SQL/MX as though it were the fractional precision of a SECOND field, provided the start field is SECOND or larger. Selecting FRACTION-Only INTERVAL Columns If you attempt to select data from a FRACTION-only INTERVAL column, the column value is returned as a string of '#' characters with the same display length as the length of the column.
SQL/MX Language Elements Numeric Data Types A column in an SQL/MP table declared with a floating-point data type is stored in Tandem floating-point format and all computations on it are done assuming that. SQL/MP tables can contain only Tandem floating-point data. For more information about SQL/MP data types, see the SQL/MP Reference Manual. A column in an SQL/MX table declared with a floating-point data type is stored in IEEE floating-point format and all computations on it are done assuming that.
SQL/MX Language Elements Numeric Data Types PIC[TURE] [S]{ 9(integer) [V[9(scale)]] | V9(scale) } [DISPLAY [SIGN IS LEADING] | COMP] specifies an exact numeric column. If you specify COMP, the column is binary and equivalent to the data type NUMERIC. If you omit COMP, DISPLAY [SIGN IS LEADING] is the default, and the data type is equivalent to the data type DECIMAL. The S specifies a signed column. The sign is stored as the first bit of the leftmost byte (digit). If you omit S, the column is unsigned.
SQL/MX Language Elements DEFINEs DEFINEs A DEFINE is a named set of attribute-value pairs associated with a process. You can use DEFINEs to pass information to a process when you start the process. DEFINEs are often used to pass information about Guardian names. DEFINEs can be used only for SQL/MP objects. NonStop SQL/MX allows you to use DEFINE names as logical names for tables, views, or partitions in SQL/MX statements that query SQL/MP objects.
Using DEFINEs SQL/MX Language Elements When DEFMODE is OFF, DEFINEs are ignored, and you cannot create new DEFINEs. You can still modify, delete, and display information about existing DEFINEs, but such DEFINEs have no effect because they are not propagated to other programs. Use these commands to work with DEFINEs from MXCI. Each command is described in more detail in a separate entry.
SQL/MX Language Elements Using DEFINEs From MXCI Using DEFINEs From MXCI • Make sure DEFMODE is set to ON in TACL or the OSS shell. DEFMODE is ON by default but can be set to OFF in TACL or the OSS shell. To inherit DEFINEs from the process that starts MXCI, such as TACL or the OSS shell, verify that DEFMODE is ON before you start MXCI. If you set DEFMODE OFF before you start MXCI, you will not inherit DEFINEs, and you will not be able to create new DEFINEs during the MXCI session.
Expressions SQL/MX Language Elements Expressions An SQL value expression, referred to as an expression, can evaluate to a value with one of these: Character Value Expressions on page 6-37 Operands can be combined with the concatenation operator (||). Example: 'HOUSTON,' ||' TEXAS' Datetime Value Expressions on page 6-39 Operands can be combined in specific ways with arithmetic operators.
Character Value Expressions SQL/MX Language Elements Character (or string) value expressions are built from operands that can be: • • • • • • • Character string literals Character string functions Column references with character values Host variables of type CHAR, VARCHAR, and PIC X(l) Dynamic parameters CURRENT_USER, SESSION_USER, and USER functions Aggregate functions, sequence functions, scalar subqueries, CASE expressions, or CAST expressions that return character values Examples of Character Valu
SQL/MX Language Elements Datetime Value Expressions Datetime Value Expressions SQL/MP Considerations for Datetime Value Expressions Considerations for Datetime Value Expressions Examples of Datetime Value Expressions The operands of a datetime value expression can be combined in specific ways with arithmetic operators. In this syntax diagram, the data type of a datetime primary is DATE, TIME, or TIMESTAMP. The data type of an interval term is INTERVAL.
Datetime Value Expressions SQL/MX Language Elements Datetime value expressions are built from operands that can be: • • • • • • • • • Interval value expressions Datetime or interval literals Host variables of type DATE, TIME, TIMESTAMP, and INTERVAL Dynamic parameters Column references with datetime or interval values Host variables of type INTERVAL Dynamic parameters Datetime or interval value functions Any aggregate functions, sequence functions, scalar subqueries, CASE expressions, or CAST expression
Datetime Value Expressions SQL/MX Language Elements In the last expression, the datetime primary is this scalar subquery: ( SELECT ship_timestamp FROM project WHERE projcode=1000 ) The preceding subquery returns a value with TIMESTAMP data type. Therefore, the data type of the result is TIMESTAMP.
SQL/MX Language Elements • Datetime Value Expressions Add an interval value qualified by YEAR to a datetime value: SELECT start_date + INTERVAL '1' YEAR FROM persnl.project WHERE projcode = 1000; (EXPR) ---------1997-04-10 --- 1 row(s) selected. • Subtract an interval value qualified by MONTH from a datetime value: SELECT ship_timestamp - INTERVAL '1' MONTH FROM persnl.project WHERE projcode = 134; (EXPR) -------------------------1996-12-01 00:00:00.000000 --- 1 row(s) selected.
SQL/MX Language Elements Interval Value Expressions Interval Value Expressions SQL/MP Considerations for Interval Value Expressions Considerations for Interval Value Expressions Examples of Interval Value Expressions The operands of an interval value expression can be combined in specific ways with addition and subtraction operators. In this syntax diagram, the data type of a datetime expression is DATE, TIME, or TIMESTAMP; the data type of an interval term or expression is INTERVAL.
SQL/MX Language Elements Interval Value Expressions numeric-primary is: unsigned-numeric-literal | column-reference | numeric-type-host-variable | dynamic parameter | numeric-value-function | aggregate-function | sequence-function | scalar-subquery | CASE-expression | CAST-expression | (numeric-expression) interval-qualifier is: start-field TO end-field | single-field start-field is: {YEAR | MONTH | DAY | HOUR | MINUTE} [(leading-precision)] end-field is: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND [(frac
Interval Value Expressions SQL/MX Language Elements If the interval expression is the difference or sum of interval operands, the interval qualifiers of the operands are either year-month or day-time. If you are updating or inserting a value that is the result of adding or subtracting two interval qualifiers, the interval qualifier of the result depends on the interval qualifier of the target column.
Interval Value Expressions SQL/MX Language Elements Restrictions on Operations You can use datetime and interval operands with arithmetic operators in an interval value expression only in these combinations: Operand 1 Operator Operand 2 Result Type Datetime – Datetime Interval Interval + or – Interval Interval Interval * or / Numeric Interval Numeric * Interval Interval This table lists valid combinations of datetime and interval arithmetic operators, and the data type of the result: O
Interval Value Expressions SQL/MX Language Elements • If you subtract a datetime value from another datetime value, and you specify the interval qualifier, you must allow for the maximum number of digits in the result for the precision. For example: (CURRENT_TIMESTAMP - ship_timestamp) DAY(4) TO SECOND(6) • If you are updating a value that is the result of adding or subtracting two interval values, an SQL error occurs if the source value does not fit into the target column's range of interval fields.
Numeric Value Expressions SQL/MX Language Elements -----------1000 2000 2500 3000 4000 5000 --------------------1355 02:58:57.087086 1264 02:43:57.087086 1111 02:13:57.087086 1172 03:03:57.087086 1172 00:58:57.087086 1165 01:48:55.975986 --- 6 row(s) selected. Numeric Value Expressions Considerations for Numeric Value Expressions Examples of Numeric Value Expressions The operands of a numeric value expression can be combined in specific ways with arithmetic operators.
SQL/MX Language Elements • • • • Numeric Value Expressions Host variables of type NUMERIC, PIC S9()V9(), DECIMAL, SMALLINT, INTEGER, LARGEINT, FLOAT, REAL, and DOUBLE PRECISION Dynamic parameters Numeric value functions Aggregate functions, sequence functions, scalar subqueries, CASE expressions, or CAST expressions that return numeric values Considerations for Numeric Value Expressions Order of Evaluation 1. 2. 3. 4. 5.
SQL/MX Language Elements Numeric Value Expressions The maximum precision for exact numeric data types is 18 digits. The maximum precision for the REAL data type is approximately 7 decimal digits, and the maximum precision for the DOUBLE PRECISION data type is approximately 16 digits.
Rowset Expressions SQL/MX Language Elements Examples of Numeric Value Expressions These are examples of numeric value expressions: -57 Numeric literal. salary * 1.10 The product of the values in the SALARY column and a numeric literal. unit_price * qty_ordered The product of the values in the UNIT_PRICE and QTY_ORDERED columns. 12 * (7 - 4) An expression whose operands are numeric literals. COUNT (DISTINCT city) Function applied to the values in a column.
Identifiers SQL/MX Language Elements Identifiers SQL/MP Considerations for Identifiers Examples of Identifiers SQL identifiers are names used to identify tables, views, columns, and other SQL entities. The two types of identifiers are regular and delimited. A delimited identifier is enclosed in double quotes ("). An identifier of either type can contain up to 128 characters.
SQL/MP Considerations for Identifiers SQL/MX Language Elements your catalogs and the name ZONE for a schema within that catalog. You can pass these delimited identifier names as command-line arguments to an OSS hosted preprocessor invocation by using an escape character for their quotes. mxsqlco prog.cob -g moduleSchema="\"TIME\".\"ZONE\"" Suppose that prog.cob has this module directive: EXEC SQL MODULE progmod END-EXEC.
SQL/MX Language Elements Examples of Identifiers "1995 SALES" "CUSTOMER-BILLING-INFORMATION" "%&*()" Because delimited identifiers are case-sensitive, NonStop SQL/MX treats the identifier "mytable" as different from the identifiers "MYTABLE" or "MyTable". Trailing spaces in a delimited identifier are truncated. For example, "mytable " is equivalent to "mytable". You can use reserved words as delimited identifiers.
SQL/MX Language Elements Indexes Indexes An index is an ordered set of pointers to rows of a table. Each index is based on the values in one or more columns. An index is stored in a key-sequenced file. There is always a one-to-one correspondence between index rows and base table rows.
Keys SQL/MX Language Elements Keys NonStop SQL/MX supports these types of keys: Clustering Keys First (Partition) Keys Index Keys Primary Keys SYSKEYs Clustering Keys NonStop SQL/MX organizes records of a table or index by using a b-tree based on the “clustering key”. Values of the clustering key act as logical row-ids. The set of columns that make up the clustering key must guarantee uniqueness.
First (Partition) Keys SQL/MX Language Elements Table 6-1. Construction of the Clustering Key (page 2 of 2) STORE BY key column list Primary Key Specified DROPPABLE Attribute Clustering Key No Not applicable Key column list + SYSKEY Yes DROPPABLE Key column list + SYSKEY. Primary key enforced by unique index. Yes NOT DROPPABLE If STORE BY column list matches the primary key column list, NonStop SQL/MX uses the STORE BY column list.
SQL/MX Language Elements Index Keys Partitioning character columns must derive from the ISO88591 character set and cannot be floating-point data columns. Index Keys An index is stored in a key-sequenced file. There is always a one-to-one correspondence between index rows and base table rows.
SQL/MX Language Elements Primary Keys For a unique index, the clustering key of the index is composed of the first of these items. The clustering key of the index cannot exceed 255 bytes, but the entire row (including the clustering key of the index) can contain up to 510 bytes. For a nonunique index, the clustering key of the index is composed of both items. The clustering key cannot exceed 255 bytes. Because the clustering key includes all the columns in the table, each row is also limited to 255 bytes.
Literals SQL/MX Language Elements Literals A literal is a constant you can use in an expression, in a statement, or as a parameter value. Literals are stored in columns of tables according to how you specify the column definitions in a CREATE TABLE statement. An SQL literal can be one of these data types: Character String Literals on page 6-60 A series of characters enclosed in single quotes.
SQL/MX Language Elements Character String Literals You can specify string literals using hexadecimal code values in DML statements. [_character-set | N] X'hex-code-value... ' | [_character-set | N] X'[space…]hex-code-value[[space…] hex-code-value...][space…]' _character-set specifies the character set ISO88591 or UCS2. If you omit the character set specification, the default is whatever character set default you set when you installed NonStop SQL/MX. See Character Sets on page 6-3.
SQL/MX Language Elements Character String Literals When specifying string literals: • Do not put a space between the character set qualifier (for example, _KANJI) and the character string literal (for example, 'abcd'). If you use this character string literal in a statement, NonStop SQL/MX returns an error: _KANJI 'abcd' • • • • To specify a single quotation mark within a string literal, use two consecutive single quotation marks.
Character String Literals SQL/MX Language Elements Because the NATIONAL_CHARSET attribute is set to UCS2, the N'abcd' literal is a shorter way of writing _UCS2'abcd': UPDATE T SET K = _UCS2'abcd' See NCHAR Columns in SQL/MX and SQL/MP Tables on page 6-22. Inserting Into or Updating SQL/MP Kanji Columns NonStop SQL/MX Release 2.x supports inserting into or updating columns with the KANJI or KSC data type in SQL/MP tables.
Datetime Literals SQL/MX Language Elements Datetime Literals SQL/MP Considerations for Datetime Literals Examples of Datetime Literals A datetime literal is a DATE, TIME, or TIMESTAMP constant you can use in an expression, in a statement, or as a parameter value. Datetime literals have the same range of valid values as the corresponding datetime data types.
Datetime Literals SQL/MX Language Elements NonStop SQL/MX supports inserting into or updating any columns with the DATETIME data type in SQL/MP tables except those consisting of FRACTION only. Use a special SQL/MX DATETIME literal to insert into or update a DATETIME column in an SQL/MP table. The literal is written: DATETIME 'datetime' [start-field TO] end-field The string literal 'datetime' is a subset of the standard datetime form: 'yyyy-mm-dd:hh:mm:ss.
SQL/MX Language Elements Datetime Literals Examples of Datetime Literals • These are DATE literals in default, USA, and European formats, respectively: DATE '1990-01-22' DATE '01/22/1990' DATE '22.01.1990' • These are TIME literals in default, USA, and European formats, respectively: TIME '13:40:05' TIME '01:40:05 PM' TIME '13.40.05' • These are TIMESTAMP literals in default, USA, and European formats, respectively: TIMESTAMP '1990-01-22 13:40:05' TIMESTAMP '01/22/1990 01:40:05 PM' TIMESTAMP '22.01.
SQL/MX Language Elements Interval Literals Interval Literals Considerations for Interval Literals SQL/MP Considerations for Interval Literals Examples of Interval Literals An interval literal is a constant of data type INTERVAL that represents a positive or negative duration of time as a year-month or day-time interval; it begins with the keyword INTERVAL optionally preceded or followed by a minus sign (for negative duration).
SQL/MX Language Elements Interval Literals YEAR | MONTH | DAY | HOUR | MINUTE | SECOND [(fractionalprecision)] specifies the end-field. If the end-field is SECOND, it can have a fractional-precision up to 6 digits. The fractional-precision is the number of digits of precision after the decimal point. The default for fractional-precision is 6. start-field | SECOND [(leading-precision, fractional-precision)] specifies the single-field.
SQL/MX Language Elements Interval Literals minutes Unsigned integer that specifies a number of minutes. Used as a starting field, minutes can have up to 18 digits if there is no end-field; and 16-f digits if seconds is the end-field, where f is the fraction less than or equal to 6. These maximums are specified by MINUTE(18), and MINUTE(16-f) TO SECOND(f). Used as an ending field, the value of minutes must be in the range 0 to 59. seconds Unsigned integer that specifies a number of seconds.
Interval Literals SQL/MX Language Elements Updating Supported INTERVAL Columns Suppose that an SQL/MP table has an INTERVAL column defined as: MPIntervalCol INTERVAL YEAR TO MONTH DEFAULT INTERVAL '01-03' YEAR TO MONTH You can insert into this column by using an INTERVAL YEAR TO MONTH literal.
Numeric Literals SQL/MX Language Elements SQL/MP Start Field SQL/MP End Field Equivalent SQL/MX Type FRACTION FRACTION None FRACTION(x) FRACTION None FRACTION(x) FRACTION(y) None FRACTION FRACTION(y) None Note that in both NonStop SQL/MX and NonStop SQL/MP, the default leading precision for seconds is 2, and the default trailing precision for fraction of a second is 6.
Numeric Literals SQL/MX Language Elements exact-numeric-literal is an exact numeric value that includes an optional plus sign (+) or minus sign (-), up to 18 digits (0 through 9), and an optional period (.) that indicates a decimal point. Leading zeros do not count toward the 18-digit limit; trailing zeros do. A numeric literal without a sign is a positive number. An exact numeric literal that does not include a decimal point is an integer.
SQL/MX Language Elements MXCI Parameters MXCI Parameters Examples of MXCI Parameters Typically, you use parameters (both within MXCI and in embedded SQL) so that you can prepare an SQL statement and then execute it later, providing different values for each execution. Within an MXCI file to be obeyed, you can also use parameters for values so that an SQL statement within the file can execute with different values.
Working With MXCI Parameters SQL/MX Language Elements • • If the parameter is character and the target column has datetime data type, you must CAST the parameter to have the same data type as the target column. If the parameter is character or numeric and the target column has INTERVAL data type, you must CAST the parameter to have the INTERVAL data type. Working With MXCI Parameters Use these statements with MXCI parameters: SET PARAM Command on page 4-47 Sets the value of an MXCI-named parameter.
SQL/MX Language Elements Examples of MXCI Parameters Examples of MXCI Parameters • The PROJECT table has a START_DATE column. This UPDATE statement uses the character literal in the ?STARTDAY parameter to set the START_DATE column value in the PROJECT table: SET PARAM ?STARTDAY '1999-11-15'; UPDATE persnl.project SET start_date = CAST(?STARTDAY AS DATE); • Suppose that the PROJECT table has an EST_COMPLETE column whose default value is INTERVAL '30' DAY.
SQL/MX Language Elements Null Null Null is a special symbol, independent of data type, that represents an unknown. The SQL/MX keyword NULL represents null. Null indicates that an item has no value. For sorting purposes, null is greater than all other values. You cannot store null in a column by using either INSERT or UPDATE, unless the column allows null. A column that allows null can be null at any row position. A nullable column has extra bytes associated with it in each row.
SQL/MX Language Elements Defining Columns That Allow or Prohibit Null Defining Columns That Allow or Prohibit Null The CREATE TABLE and ALTER TABLE statements define the attributes for columns within tables. A column allows nulls unless the column definition includes the NOT NULL clause or the column is part of the primary key of the table.
Defining Columns That Allow or Prohibit Null SQL/MX Language Elements Null in DISTINCT, GROUP BY, and ORDER BY Clauses In evaluating the DISTINCT, GROUP BY, and ORDER BY clauses, NonStop SQL/MX considers all nulls to be equal. Additional considerations for these clauses are: DISTINCT Nulls are considered duplicates; therefore, a result has at most one null. GROUP BY The result has at most one null group. ORDER BY Nulls are considered greater than nonnull values.
SQL/MX Language Elements Partitions Partitions Typically, there is a one-to-one correspondence between a table definition and a physical file. However, large tables, or tables with special performance requirements, might require partitioning into multiple physical files. A partition is the part of a table or index that resides on a single disk volume. Each table or index consists of at least one partition. A nonpartitioned table or index consists of exactly one partition.
SQL/MX Language Elements SQL/MX Tables partitions, it is possible that records are not (for example, if data is skewed within partitioning key values). In this scenario, suppose that you have a database with 10 partitions and 1,000 unique partitioning key values. Each partition will be assigned approximately 100 partitioning key values, plus or minus.
Predicates SQL/MX Language Elements CONTROL QUERY DEFAULT attributes determine the number and physical location of the partitions. For values and syntax of these defaults, see Partition Management on page 10-51. For more information on this feature, see Creating Partitions Automatically on page 2-89. Predicates A predicate determines an answer to a question about a value or group of values. A predicate returns true, false, or, if the question cannot be answered, unknown.
SQL/MX Language Elements BETWEEN Predicate The BETWEEN predicate determines whether a sequence of values is within a range of sequences of values. row-value-constructor [NOT] BETWEEN row-value-constructor AND row-value-constructor row-value-constructor is: (expression [,expression ]...) | row-subquery row-value-constructor specifies an operand of the BETWEEN predicate. The three operands can be either of: (expression [,expression ]...
BETWEEN Predicate SQL/MX Language Elements If a clause specifies a column in a key BETWEEN expr2 and expr3, expr3 must be greater than expr2 even if the column is specified as DESCENDING within its table definition. Examples of BETWEEN • This predicate is true if the total price of the units in inventory is in the range from $1,000 to $10,000: qty_on_hand * price BETWEEN 1000.00 AND 10000.00 • This predicate is true if the part cost is less than $5 or more than $800: partcost NOT BETWEEN 5.
SQL/MX Language Elements Comparison Predicates Comparison Predicates Considerations for Comparison Predicates Examples of Comparison Predicates A comparison predicate compares the values of sequences of expressions, or the values of sequences of row values that are the result of row subqueries.
SQL/MX Language Elements Comparison Predicates Considerations for Comparison Predicates When a Comparison Predicate Is True NonStop SQL/MX determines whether a relationship is true or false by comparing values in corresponding positions in sequence, until it finds the first nonequal pair. You cannot use a comparison predicate in a WHERE or HAVING clause to compare row value constructors when the value expressions in one row value constructor are equal to null. Use the IS NULL predicate instead.
SQL/MX Language Elements Comparison Predicates For example, NonStop SQL/MX considers the string ‘JOE’ equal to a value JOE stored in a column of data type CHAR or VARCHAR of width three or more. Similarly, NonStop SQL/MX considers a value JOE stored in any column of the CHAR data type equal to the value JOE stored in any column of the VARCHAR data type. Two strings are equal if all characters in the same ordinal position are equal. Lowercase and uppercase letters are not considered equivalent.
Comparison Predicates SQL/MX Language Elements This multivalue predicate is equivalent to this condition with three comparison predicates: (last_name > 'MOSS') OR (last_name = 'MOSS' AND first_name > 'DUNCAN') • Compare two datetime values START_DATE and the result of the CURRENT_DATE function: START_DATE < CURRENT_DATE • Compare two datetime values START_DATE and SHIP_TIMESTAMP: CAST (start_date AS TIMESTAMP) < ship_timestamp • Compare two INTERVAL values: JOB1_TIME < JOB2_TIME Suppose that JOB1_TI
EXISTS Predicate SQL/MX Language Elements Find all employees from other departments whose salary is less than the minimum salary of employees (not in department 1500) that have a salary greater than the average salary for department 1500: SELECT first_name, last_name, deptnum, salary FROM persnl.employee WHERE deptnum <> 1500 AND salary < (SELECT MIN (salary) FROM persnl.employee WHERE deptnum <> 1500 AND salary > (SELECT AVG (salary) FROM persnl.
SQL/MX Language Elements EXISTS Predicate (SELECT jobcode FROM persnl.employee E WHERE D.deptnum = E.deptnum AND jobcode = 300); DEPTNUM ------3000 3100 3200 3300 3500 LOCATION ------------NEW YORK TORONTO FRANKFURT LONDON HONG KONG --- 5 row(s) selected. In the preceding example, the EXISTS predicate contains a subquery that determines which locations have employees with job code 300. The subquery depends on the value of D.
SQL/MX Language Elements IN Predicate IN Predicate Considerations for IN Examples of IN The IN predicate determines if a sequence of values is equal to any of the sequences of values in a list of sequences. The NOT operator reverses its truth value. For example, if IN is true, NOT IN is false. row-value-constructor [NOT] IN {table-subquery | in-value-list} row-value-constructor is: (expression [,expression]...) | row-subquery in-value-list is: (expression [,expression]...
SQL/MX Language Elements IN Predicate constructor is a single value. The data types of the values must be comparable. The limit for the number of expressions in thein-value-list is 1900. Considerations for IN Logical Equivalent Using ANY (or SOME) The predicate expr IN (expr1, expr2, ... ) is true if and only if the following predicate is true: expr = ANY (expr1, expr2, ...
IN Predicate SQL/MX Language Elements Examples of IN • Find those employees whose EMPNUM is 39, 337, or 452: SELECT last_name, first_name, empnum FROM persnl.employee WHERE empnum IN (39, 337, 452); LAST_NAME FIRST_NAME -------------------- --------------CLARK DINAH SAFFERT KLAUS --- 2 row(s) selected. • EMPNUM -----337 39 Find those items in PARTS whose part number is not in the PARTLOC table: SELECT partnum, partdesc FROM sales.parts WHERE partnum NOT IN (SELECT partnum FROM invent.
SQL/MX Language Elements LIKE Predicate LIKE Predicate Considerations for LIKE Examples of LIKE The LIKE predicate searches for character strings that match a pattern. match-value [NOT] LIKE pattern [ESCAPE esc-char-expression] match-value is a character value expression that specifies the set of strings to search for that match the pattern. pattern is a character value expression that specifies the pattern string for the search.
SQL/MX Language Elements LIKE Predicate Wild Card Characters You can look for similar values by specifying only part of the characters of pattern combined with these wild-card characters: % Use a percent sign to indicate zero or more characters of any type. For example, '%ART%' matches 'SMART', 'ARTIFICIAL', and 'PARTICULAR'—but not 'smart'. The code value for %r for KANJI character set is 0x8193, while that for KSC5601 is 0xA3A5. _ Use an underscore to indicate any single character.
SQL/MX Language Elements NULL Predicate Examples of LIKE • Find all employee last names beginning with ZE: last_name LIKE 'ZE%' • Find all job titles that match a specific string provided at execution time: jobdesc LIKE ?SOMEJOB This predicate example is a part of a prepared statement where the parameter value of SOMEJOB is provided at execution time.
NULL Predicate SQL/MX Language Elements Considerations for NULL Summary of NULL Results Let rvc be the value of the row-value-constructor. This table summarizes the results of NULL predicates. The degree of a rvc is the number of values in the rvc.
SQL/MX Language Elements Quantified Comparison Predicates Quantified Comparison Predicates Considerations for ALL, ANY, SOME Examples of ALL, ANY, SOME A quantified comparison predicate compares the values of sequences of expressions to the values in each row selected by a table subquery. The comparison operation is quantified by the logical quantifiers ALL, ANY, or SOME. row-value-constructor comparison-op quantifier table-subquery row-value-constructor is: (expression [,expression]...
SQL/MX Language Elements Quantified Comparison Predicates ANY | SOME specifies that the predicate is true if the comparison is true for at least one row selected by the table-subquery and specifies that the predicate is false if the comparison is false for every row selected (or if table-subquery selects no rows). table-subquery provides the values for the comparison.
Quantified Comparison Predicates SQL/MX Language Elements The inner query providing the comparison values yields these results: SELECT salary FROM persnl.employee WHERE jobcode = 420; SALARY ----------33000.00 36000.00 18000.10 --- 3 row(s) selected. The SELECT statement using this inner query yields these results. The salaries listed are greater than the salary of every employees with jobcode equal to 420— that is, greater than $33,000.00, $36,000.00, and $18,000.
Rowset Predicates SQL/MX Language Elements The inner query providing the comparison values yields these results: SELECT partnum FROM sales.odetail WHERE qty_ordered > 5; Part/Num -------2403 5100 5103 6301 6500 .... --- 60 row(s) selected. The SELECT statement using this inner query yields these results.
SQL/MX Language Elements Schemas Schemas The ANSI SQL:1999 schema name is an SQL identifier that is unique for a given ANSI catalog name. NonStop SQL/MX automatically qualifies a schema name with the current default catalog name unless you explicitly specify a catalog name with the schema name: catalog.schema The three-part logical name of the form catalog.schema.object is an ANSI name. The parts catalog and schema denote the ANSI-defined catalog and schema.
SQL/MX Language Elements Search Condition Search Condition A search condition is used to choose rows from tables or views, depending on the result of applying the condition to rows. The condition is a Boolean expression consisting of predicates combined together with OR, AND, and NOT operators.
SQL/MX Language Elements Considerations for Search Condition Considerations for Search Condition Order of Evaluation SQL evaluates search conditions in this order: 1. 2. 3. 4. Predicates within parentheses NOT AND OR Column References Within a search condition, a reference to a column refers to the value of that column in the row currently being evaluated by the search condition. Subqueries If a search condition includes a subquery and the subquery returns no values, the predicate evaluates to null.
Rowset Search Condition SQL/MX Language Elements • Select rows by using a search condition composed of three comparison predicates, two of which are joined by an OR operator (within parentheses), and where the result of the OR and the first comparison predicate are joined by an AND operator: SELECT partnum, S.suppnum, suppname FROM invent.supplier S, invent.partsupp PS WHERE S.suppnum = PS.suppnum AND (partnum < 3000 OR partnum = 7102); PARTNUM ------212 244 255 ...
SQL/MX Language Elements SQL/MP Aliases SQL/MP Aliases In product versions prior to SQL/MX Release 2.x, you referenced SQL/MP database objects using their Guardian physical names. In SQL/MX Release 2.x you can create SQL/MP aliases that map logical object names to physical Guardian locations. SQL/MP aliases are simulated ANSI names that represent the underlying Guardian physical names of SQL/MP objects. True ANSI names do not exist for SQL/MP objects.
SQL/MX Language Elements Subquery When you use rowset-search-condition in a subquery, all the individual search-conditions in the rowset are applied successively. The result table is the union of all the rows selected by these successive applications. Using rowsets in a subquery implies that the entire rowset in the subquery is evaluated and the result table passed on the outer query.
SQL/MX Language Elements Tables A subquery within the WHERE clause of another subquery is at a different level, however, so this query has two levels of nesting: SELECT * FROM TABLE1 WHERE A = (SELECT P FROM TABLE2 WHERE Q = (SELECT X FROM TABLE3 WHERE Y = 2)) Correlated Subqueries When Providing Comparison Values In the search condition of a subquery, when you refer to columns of any table or view defined in an outer query, the reference is called an outer reference.
Triggers SQL/MX Language Elements An SQL/MX table is described in an SQL/MX schema and stored in a physical file in the Guardian environment. An SQL/MX table name can be a fully qualified ANSI name of the form catalog-name.schema-name.object-name. Base Tables and Views In some descriptions of SQL, tables created with a CREATE TABLE statement are referred to as base tables to distinguish them from views, which are referred to as logical tables.
SQL/MX Views SQL/MX Language Elements An view is a logical table created with the CREATE VIEW statement and derived by projecting a subset of columns, restricting a subset of rows, or both, from one or more base tables or other views. You cannot create a view that references both an SQL/MP table and an SQL/MX table. SQL/MX Views The distinction between protection and shorthand views does not exist for SQL/MX views. To create a view, you must have SELECT privileges for the objects underlying the view.
SQL/MX Language Elements SQL/MP Views In this sample view, the columns are EMPNUM, FIRST_NAME, LAST_NAME, DEPTNUM, and JOBCODE. The SALARY column in the EMPLOYEE table is not part of the EMPLIST view.
7 SQL/MX Clauses Clauses are used by SQL/MX statements to specify default values, ways to sample or sort data, how to store physical data, how to partition file, and other details. This section describes these clauses for SQL/MX objects: DEFAULT Clause on page 7-2 Specifies a default value for a column being created. PARTITION Clause on page 7-5 Creates one or more secondary partitions for a table or index.
DEFAULT Clause SQL/MX Clauses DEFAULT Clause Considerations for DEFAULT Examples of DEFAULT The DEFAULT option of the CREATE TABLE or ALTER TABLE table-name ADD COLUMN statement specifies a default value for a column being created. The default value is used when a row is inserted in the table without a value for the column.
Considerations for DEFAULT SQL/MX Clauses DEFAULT CURRENT_TIME specifies the default value for the column as the value returned by the CURRENT_TIME function at the time of the operation that assigns a value to the column. This default can occur only with a column whose data type is TIME. DEFAULT CURRENT_TIMESTAMP specifies the default value for the column as the value returned by the CURRENT_TIMESTAMP function at the time of the operation that assigns a value to the column.
Examples of DEFAULT SQL/MX Clauses Examples of DEFAULT • This example uses DEFAULT clauses on CREATE TABLE to specify default column values: CREATE TABLE items ( item_id CHAR(12) NO DEFAULT ,description CHAR(50) DEFAULT NULL ,num_on_hand INTEGER DEFAULT 0 NOT NULL ,PRIMARY KEY (item_id) NOT DROPPABLE ); • This example uses DEFAULT clauses on CREATE TABLE to specify default column values: CREATE TABLE persnl.
PARTITION Clause SQL/MX Clauses PARTITION Clause Considerations for PARTITION Examples of Partitions The PARTITION clause of the CREATE INDEX and CREATE TABLE statements creates one or more secondary partitions for a table or index. NonStop SQL/MX supports range partitioning and hash partitioning. See Partitions on page 6-79 for details. PARTITION is an SQL/MX extension. {[RANGE] PARTITION [BY (partitioning-column [,partitioning-column] ....)] [(ADD range-partn-defn [,ADD range-partn-defn]...
Considerations for PARTITION SQL/MX Clauses col-value is a literal that specifies the first value allowed in the associated partition for that column of the partitioning key. If there are more storage key columns than col-value items, the first key value for each remaining key column is the lowest or highest value for the data type of the column (the lowest value for an ascending column and the highest value for a descending column). col-value must contain only characters from the ISO88591 character set.
Examples of Partitions SQL/MX Clauses Decoupling of Clustering Key and Partitioning Key Decoupling the clustering key from the partitioning key allows those keys to differ. NonStop SQL/MX does not support full decoupling (that is, complete independence of the keys), but does support partial decoupling in which the set of partitioning key columns is allowed to be a subset of the clustering key columns. The composition of the clustering key is described in the STORE BY clause.
SAMPLE Clause SQL/MX Clauses SAMPLE Clause Considerations for SAMPLE Examples of SAMPLE The SAMPLE clause of the SELECT statement specifies the sampling method used to select a subset of the intermediate result table of a SELECT statement. The intermediate result table consists of the rows returned by a WHERE clause or, if there is no WHERE clause, the FROM clause. See SELECT Statement on page 2-174. SAMPLE is an SQL/MX extension.
SAMPLE Clause SQL/MX Clauses You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table. Each row is picked with a probability of r%, where r is the sample size in PERCENT. Therefore, the actual size of the resulting sample is approximately r% of N. The number of rows picked follows a binomial distribution with mean equal to r * N/100.
Considerations for SAMPLE SQL/MX Clauses You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table. If the size s of the sample is specified as a number of rows, the actual size of the resulting sample is the minimum of s and N. PERIODIC rows-size EVERY number-rows ROWS [SORT BY colname [ASC[ENDING] | DESC[ENDING]] [,colname [ASC[ENDING] | DESC[ENDING]]]...] directs NonStop SQL/MX to choose the first rows from each block (or period) of contiguous rows.
Examples of SAMPLE SQL/MX Clauses Cluster sampling can be done only on a base table, not on intermediate results. Cluster sampling is generally faster than sampling individual rows because fewer blocks are read from disk. In random row and periodic sampling, the entire result table being sampled is read, and each row in the table is processed. In cluster sampling, only the disk blocks that are part of the result table are read and processed.
Examples of SAMPLE SQL/MX Clauses • Return the SALARY of the youngest 50 sales people: SELECT salary FROM salesperson SAMPLE FIRST 50 ROWS SORT BY age; SALARY ----------90000.00 90000.00 28000.00 27000.12 136000.00 37000.40 ... --- 50 row(s) selected. • Return the SALARY of 50 sales people. In this case, the table is clustered on EMPID.
Examples of SAMPLE SQL/MX Clauses 36000.00 ... --- 17 row(s) selected. In this example, there are 62 rows in the SALESPERSON table. For each set of 20 rows, the first five rows are selected. The last set consists of two rows, both of which are selected. • Compute the average salary of a random 10 percent of the sales people. You will get a different result each time you run this query because it is based on a random sample.
Examples of SAMPLE SQL/MX Clauses --- 1 row(s) selected. • Compute the average salary of a random 10 percent of sales people belonging to the CORPORATE department. The sample is taken from the join of the SALESPERSON and DEPARTMENT tables. You will get a different result each time you run this query because it is based on a random sample. SELECT AVG(salary) FROM salesperson S, department D WHERE S.DNUM = D.DNUM AND D.NAME = 'CORPORATE' SAMPLE RANDOM 10 PERCENT; (EXPR) --------------------106250.
Examples of SAMPLE SQL/MX Clauses For this query execution, the number of rows returned by the embedded query is limited by the total number of rows in the SALESPERSON table. Therefore, it is possible that no rows satisfy the search condition in the WHERE clause. • In this example, both the tables are sampled first and then joined. This query computes the average salary and the average sale amount generated from a random 10 percent of all the sales people and 20 percent of all the sales transactions.
Examples of SAMPLE SQL/MX Clauses • The BALANCE option enables stratified sampling. Retrieve the age and salary of 1000 sales people such that 50 percent of the result are male and 50 percent female. SELECT age, sex, salary FROM salesperson SAMPLE FIRST BALANCE WHEN sex = 'male' THEN 15 ROWS WHEN sex = 'female' THEN 15 ROWS END ORDER BY age; AGE SEX SALARY ----------22 22 22 22 ... -----male male female male ... ----------28000.00 90000.00 136000.00 37000.40 ... --- 30 row(s) selected.
Examples of SAMPLE SQL/MX Clauses • This query shows an example of stratified sampling where the conditions are not mutually exclusive: SELECT * FROM sales SAMPLE RANDOM BALANCE WHEN amount > 10000 THEN 100 PERCENT WHEN product = 'PCGOLD, 30MB' THEN 25 PERCENT WHEN region = 'W' THEN 40 PERCENT ELSE 10 PERCENT END; EMPID ----1 23 29 32 39 75 ... PRODUCT -------------------PCGOLD, 30MB PCDIAMOND, 60MB GRAPHICPRINTER, M1 GRAPHICPRINTER, M2 GRAPHICPRINTER, M3 LASERPRINTER, X1 ... REGION -----E W N S S W ..
SEQUENCE BY Clause SQL/MX Clauses SEQUENCE BY Clause Considerations for SEQUENCE BY Examples of SEQUENCE BY The SEQUENCE BY clause of the SELECT statement specifies the order in which to sort the rows of the intermediate result table for calculating sequence functions. This option is used for processing time-sequenced rows in data mining applications. See SELECT Statement on page 2-174. SEQUENCE BY is an SQL/MX extension.
Considerations for SEQUENCE BY SQL/MX Clauses ° To use a sequence function as a grouping column, you must use a derived table for the SEQUENCE BY query and use the derived column in the GROUP BY clause: SELECT ordernum, movsum_qty, AVG(unit_price) FROM (SELECT ordernum, MOVINGSUM(qty_ordered, 3), unit_price FROM odetail SEQUENCE BY partnum) AS tab2 (ordernum, movsum_qty, unit_price) GROUP BY ordernum, movsum_qty; ° To use an aggregate function as the argument to a sequence function, you must also use a
Examples of SEQUENCE BY SQL/MX Clauses Examples of SEQUENCE BY • Sequentially number each row for the entire result and also number the rows for each part number: SELECT RUNNINGCOUNT(*) AS RCOUNT, MOVINGCOUNT(*, ROWS SINCE (d.partnum<>THIS(d.partnum))) AS MCOUNT, d.partnum FROM orders o, odetail d WHERE o.ordernum=d.ordernum SEQUENCE BY d.partnum, o.order_date, o.ordernum ORDER BY d.partnum, o.order_date, o.
Examples of SEQUENCE BY SQL/MX Clauses 4000.00 100250 950.00 18000.00 3 18950.00 200300 28000.00 200300 10000.00 200300 14000.00 ... 800660 1650.00 800660 5100.00 1 28000.00 2 38000.00 3 52000.00 ... 18 187360.00 19 192460.00 6500 18000.00 1997-01-23 18950.00 244 1997-02-06 46950.00 2001 1997-02-06 56950.00 2002 1997-02-06 70950.00 ... ... 7102 1997-10-09 1113295.00 7301 1997-10-09 1118395.00 --- 69 row(s) selected.
STORE BY Clause SQL/MX Clauses STORE BY Clause Considerations for STORE BY The STORE BY clause determines the order of rows within the physical file that holds the table, and has an effect on how you can partition the object. STORE BY store-option store-option is: PRIMARY KEY | (key-column-list) key-column-list is: column-name [ASC[ENDING] | DESC[ENDING]] [,column-name [ASC[ENDING] | DESC[ENDING]]]... STORE BY store-option specifies a set of columns on which to base the clustering key.
Considerations for STORE BY SQL/MX Clauses Considerations for STORE BY Storage Order and Partitioning The organization of the physical files that make up a table and the order of rows within those physical files determine the ways you can partition the table and affect the performance of queries on that table.
Effect of Storage Order on Partitioning SQL/MX Clauses This ordering mechanism is the only method that allows you to partition by values of a nonunique key. You cannot specify a STORE BY key-column-list and a NOT DROPPABLE PRIMARY KEY in the same statement.
TRANSPOSE Clause SQL/MX Clauses TRANSPOSE Clause Considerations for TRANSPOSE Examples of TRANSPOSE The TRANSPOSE clause of the SELECT statement generates for each row of the SELECT source table a row for each item in the transpose item list. The result table of the TRANSPOSE clause has all the columns of the source table plus, for each transpose item list, a value column or columns and an optional key column. TRANSPOSE is an SQL/MX extension. TRANSPOSE transpose-set [transpose-set]...
TRANSPOSE Clause SQL/MX Clauses transpose-item-list specifies a list of items. An item is either a value expression or a list of value expressions enclosed in parentheses. expression-list specifies a list of SQL value expressions, separated by commas. The expressions must have compatible data types. For example, in the transpose set TRANSPOSE A,B,C AS V, the expressions A,B, and C have compatible data types. (expression-list) [,(expression-list)]...
Considerations for TRANSPOSE SQL/MX Clauses Considerations for TRANSPOSE Multiple TRANSPOSE Clauses and Sets • Multiple TRANSPOSE clauses can be used in the same query. For example: SELECT KEYCOL1, VALCOL1, KEYCOL2, VALCOL2 FROM MYTABLE TRANSPOSE A, B, C AS VALCOL1 KEY BY KEYCOL1 TRANSPOSE D, E, F AS VALCOL2 KEY BY KEYCOL2 • A TRANSPOSE clause can contain multiple transpose sets.
Considerations for TRANSPOSE SQL/MX Clauses Cardinality of the TRANSPOSE Result The items in each transpose-item-list are enumerated from 1 to N, where N is the total number of items in all the item lists in the transpose sets. In this example with a single transpose set, the value of N is 3: TRANSPOSE (A,X),(B,Y),(C,Z) AS (V1,V2) In this example with two transpose sets, the value of N is 5: TRANSPOSE (A,X),(B,Y),(C,Z) AS (V1,V2) L,M AS V3 The values 1 to N are the key values ki.
Examples of TRANSPOSE SQL/MX Clauses Examples of TRANSPOSE Suppose that MYTABLE has been created as: CREATE TABLE $db.mining.mytable ( A INTEGER, B INTEGER, C INTEGER, D CHAR(2), E CHAR(2), F CHAR(2) ); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.mytable $db.mining.mytable; The table MYTABLE has columns A, B, C, D, E, and F with related data. The columns A, B, and C are type INTEGER, and columns D, E, and F are type CHAR.
Examples of TRANSPOSE SQL/MX Clauses • This query shows that the items in the transpose item list can be any valid scalar expressions: SELECT KEYCOL, VALCOL, A, B, C FROM mytable TRANSPOSE A + B, C + 3, 6 AS VALCOL KEY BY KEYCOL; The result table of the TRANSPOSE query is: • KEYCOL VALCOL A B C 1 11 1 10 100 2 103 1 10 100 3 6 1 10 100 1 22 2 20 200 2 203 2 20 200 3 6 2 20 200 This query shows how the TRANSPOSE clause can be used with a GROUP BY clause.
Examples of TRANSPOSE SQL/MX Clauses • This query shows how to use COUNT applied to VALCOL. The result table of the TRANSPOSE query shows the number of distinct values in VALCOL. SELECT COUNT(DISTINCT VALCOL) FROM mytable TRANSPOSE A, B, C AS VALCOL KEY BY KEYCOL GROUP BY KEYCOL; (EXPR) -------------------2 2 2 --- 3 row(s) selected. • This query shows how multiple TRANSPOSE clauses can be used in the same query.
Examples of TRANSPOSE SQL/MX Clauses • This query shows how a TRANSPOSE clause can contain multiple transpose sets—that is, multiple transpose-item-list AS transpose-col-list. The expressions A, B, and C are of type integer, and expressions D, E, and F are of type character.
Examples of TRANSPOSE SQL/MX Clauses • KEYCOL VALCOL1 VALCOL2 (EXPR) 5 ? e2 1 6 ? f2 1 4 ? d1 1 5 ? e1 1 6 ? f1 1 This query shows how an item in the transpose item list can contain a list of expressions and that the KEY BY clause is optional: SELECT * FROM mytable TRANSPOSE (1, A, 'abc'), (2, B, 'xyz') AS (VALCOL1, VALCOL2, VALCOL3); The result table of the TRANSPOSE query is: A B C D E F VALCOL1 VALCOL2 VALCOL3 1 10 100 d1 e1 f1 1 1 abc 1 10 100 d1 e1 f1
Examples of TRANSPOSE SQL/MX Clauses HP NonStop SQL/MX Reference Manual—540440-003 7- 34
8 SQL/MX File Attributes The ATTRIBUTE file option describes physical characteristics of files (including files that contain tables, indexes, or partitions) that can affect the performance of applications that use the files. File attributes are set when a file (or an object that resides in a file) is created. If you do not specify ATTRIBUTE values in the statement that creates an object (such as CREATE TABLE or CREATE INDEX), NonStop SQL/MX uses default values for file attributes.
ALLOCATE/DEALLOCATE SQL/MX File Attributes ALLOCATE/DEALLOCATE ALLOCATE is a Guardian file attribute that reserves disk space for a file. DEALLOCATE frees disk space previously reserved for the file that does not contain data. ALLOCATE applies to tables and indexes. Allocate disk space in advance to ensure that space is available when needed and to avoid processing errors caused by full or fragmented disks during normal allocation-on-demand.
AUDITCOMPRESS SQL/MX File Attributes AUDITCOMPRESS The AUDITCOMPRESS file attribute controls whether TMF audit records for the file are compressed. Compressed audit records omit unchanged columns from the before and after images of updated rows. Uncompressed audit records allow you to read complete rows in the audit trail but require more space. You set the AUDITCOMPRESS attribute for a table with CREATE TABLE or ALTER TABLE.
BLOCKSIZE SQL/MX File Attributes BLOCKSIZE The BLOCKSIZE file attribute specifies the number of bytes in a block. Set the BLOCKSIZE attribute for a table or index with CREATE TABLE or CREATE INDEX statements. You cannot change the BLOCKSIZE attribute of an existing table or index. BLOCKSIZE number-bytes The default is BLOCKSIZE 4096. number-bytes is an integer that specifies the number of bytes in a block. Block size must be 4096 bytes. If you specify a different block size, an error is returned.
CLEARONPURGE SQL/MX File Attributes CLEARONPURGE The CLEARONPURGE file attribute controls erasure of data from the disk when a file is deleted. You set the CLEARONPURGE attribute for an SQL/MX table with CREATE TABLE or ALTER TABLE. You set the CLEARONPURGE attribute for an SQL/MX index with CREATE INDEX or ALTER INDEX. CLEARONPURGE | NO CLEARONPURGE The table default is NO CLEARONPURGE. The index default for the CLEARONPURGE attribute is the table value at index creation.
EXTENT SQL/MX File Attributes EXTENT EXTENT is a Guardian file attribute that sets the size of the extents (units of contiguous disk space) that will be allocated for a file or partition of a file. EXTENT applies to tables and indexes and is set when a file or partition is created. EXTENT ext-size | (pri-ext-size [, sec-ext-size ]) ext-size, pri-ext-size, sec-ext-size is: integer [PAGE[S] ] The default is 16 pages for the primary extent and 64 pages for each secondary extent.
MAXEXTENTS SQL/MX File Attributes contains only a small amount of data. You can maximize the use of disk space by specifying smaller extent sizes if performance is not an issue. MAXEXTENTS MAXEXTENTS is a file attribute that specifies the maximum number of extents that you can allocate for an unpartitioned file or for each partition of a partitioned file. MAXEXTENTS applies to tables and to indexes. You set the MAXEXTENTS attribute for a table with CREATE TABLE or ALTER TABLE.
SQL/MX File Attributes Considerations for MAXEXTENTS HP NonStop SQL/MX Reference Manual—540440-003 8 -8
9 SQL/MX Functions and Expressions This section describes the syntax and semantics of specific functions and expressions that you can use in NonStop SQL/MX statements. The functions and expressions are categorized according to their functionality.
Character String Functions SQL/MX Functions and Expressions Note that columns and expressions can be arguments of an aggregate function. The expressions cannot contain aggregate functions or subqueries. An aggregate function can accept an argument specified as DISTINCT, which eliminates duplicate values before the aggregate function is applied. Only one DISTINCT aggregate function is allowed at each level of a SELECT statement.
Character String Functions SQL/MX Functions and Expressions LPAD Function on page 9-79 Replaces the leftmost specified number of characters in a character expression with a padding character. LTRIM Function on page 9-80 Removes leading spaces from a character string. OCTET_LENGTH Function on page 9-101 Returns the length of a character string in bytes. POSITION Function on page 9-105 Returns the position of a specified substring within a character string. You can also use LOCATE.
Datetime Functions SQL/MX Functions and Expressions Datetime Functions These functions use either a datetime value expression as an argument or return a result of datetime data type: CONVERTTIMESTAMP Function on page 9-30 Converts a Julian timestamp to a TIMESTAMP value. CURRENT Function on page 9-34 Returns the current timestamp. You can also use the CURRENT_TIMESTAMP Function. CURRENT_DATE Function on page 9-35 Returns the current date. CURRENT_TIME Function on page 9-36 Returns the current time.
Mathematical Functions SQL/MX Functions and Expressions MONTH Function on page 9-85 Returns an integer value in the range 1 through 12 that represents the corresponding month of the year. MONTHNAME Function on page 9-86 Returns a character literal that is the name of the month of the year (January, February, and so on). QUARTER Function on page 9-107 Returns an integer value in the range 1 through 4 that represents the corresponding quarter of the year.
SQL/MX Functions and Expressions Mathematical Functions EXP Function on page 9-51 Returns the exponential value (to the base e) of a numeric value expression. FLOOR Function on page 9-60 Returns the largest integer less than or equal to a numeric value expression. LOG Function on page 9-73 Returns the natural logarithm of a numeric value expression. LOG10 Function on page 9-73 Returns the base 10 logarithm of a numeric value expression.
Sequence Functions SQL/MX Functions and Expressions Sequence Functions Sequence functions operate on ordered rows of the intermediate result table of a SELECT statement that includes a SEQUENCE BY clause. Sequence functions are categorized generally as difference, moving, offset, or running. Difference sequence functions: DIFF1 Function on page 9-45 Calculates differences between values of a column expression in the current row and previous rows.
Other Functions and Expressions SQL/MX Functions and Expressions RUNNINGSUM Function on page 9-134 Returns the sum of nonnull values of a column expression up to and including the current row. RUNNINGVARIANCE Function on page 9-136 Returns the variance of nonnull values of a column expression up to and including the current row. Other sequence functions: LASTNOTNULL Function on page 9-68 Returns the last nonnull value for the specified column expression.
SQL/MX Functions and Expressions Table-Valued Stored Functions Table-Valued Stored Functions Table-valued stored functions are system-defined functions that generate a result table. Use these functions anywhere a table reference can be used in a SELECT statement or the SELECT form of a subquery: EXPLAIN Function on page 9-52 Builds a result table that describes the access plan of a DML statement, which can then be queried by a SELECT statement.
SQL/MX Functions and Expressions ABS Function ABS Function The ABS function returns the absolute value of a numeric value expression. ABS is an SQL/MX extension. ABS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the ABS function. The result is returned as an unsigned numeric value if the precision of the argument is less than 10 or as a LARGEINT if the precision of the argument is greater than or equal to 10.
ASCII Function SQL/MX Functions and Expressions ASCII Function The ASCII function returns the integer that is the ASCII code of the first character in a character string expression associated with the ISO8891 character set. ASCII is an SQL/MX extension. ASCII (character-expression) character-expression is an SQL character value expression that specifies a string of characters. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions ASIN Function ASIN Function The ASIN function returns the arcsine of a numeric value expression as an angle expressed in radians. ASIN is an SQL/MX extension. ASIN (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the ASIN function. The range for the value of the argument is from -1 to +1. See Numeric Value Expressions on page 6-48. Examples of ASIN • This function returns the value 3.
SQL/MX Functions and Expressions ATAN Function ATAN Function The ATAN function returns the arctangent of a numeric value expression as an angle expressed in radians. ATAN is an SQL/MX extension. ATAN (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the ATAN function. See Numeric Value Expressions on page 6-48. Examples of ATAN • This function returns the value 8.72766423249958400E-001 or approximately 0.
SQL/MX Functions and Expressions AVG Function AVG Function AVG is an aggregate function that returns the average of a set of numbers. AVG ([ALL | DISTINCT] expression) ALL | DISTINCT specifies whether duplicate values are included in the computation of the AVG of the expression. The default option is ALL, which causes duplicate values to be included. If you specify DISTINCT, duplicate values are eliminated before the AVG function is applied.
SQL/MX Functions and Expressions Examples of AVG • Return the average value of the SALARY column: SELECT AVG (salary) FROM persnl.employee; (EXPR) --------------------49441.52 --- 1 row(s) selected. • Return the average value of the set of unique SALARY values: SELECT AVG(DISTINCT salary) AS Avg_Distinct_Salary FROM persnl.employee; AVG_DISTINCT_SALARY --------------------53609.89 --- 1 row(s) selected.
SQL/MX Functions and Expressions CASE (Conditional) Expression CASE (Conditional) Expression Considerations for CASE Examples of CASE The CASE expression is a conditional expression with two forms: simple and searched. In a simple CASE expression, NonStop SQL/MX compares a value to a sequence of values and sets the CASE expression to the value associated with the first match—if there is a match. If there is no match, NonStop SQL/MX returns the value specified in the ELSE clause (which can be null).
SQL/MX Functions and Expressions Considerations for CASE result-expression-1 ... result-expression-n specifies the result value expression associated with each expression in a WHEN clause of a simple CASE, or with each condition in a WHEN clause of a searched CASE. All of the result-expressions must have comparable data types, and at least one of the result-expressions must return nonnull.
Examples of CASE SQL/MX Functions and Expressions For example, if result-expression-1 and result-expression-2 have data type NUMERIC(5) and result-expression-3 has data type NUMERIC(8,5), the result data type is NUMERIC(10,5). If any data type of the result expressions is approximate numeric, the result data type is approximate numeric with precision equal to the maximum of the precisions of the result expressions.
Examples of CASE SQL/MX Functions and Expressions HALL ... KATHRYN SYSTEM ANALYST --- 62 row(s) selected. • Use a searched CASE to return LAST_NAME, FIRST_NAME and a value based on SALARY that depends on the value of DEPTNUM: SELECT last_name, first_name, deptnum, CASE WHEN deptnum = 9000 THEN salary * 1.10 WHEN deptnum = 1000 THEN salary * 1.12 ELSE salary END FROM persnl.employee; LAST_NAME FIRST_NAME ---------------- -----------GREEN ROGER HOWARD JERRY RAYMOND JANE ... --- 62 row(s) selected.
SQL/MX Functions and Expressions CAST Expression CAST Expression Considerations for CAST Valid Conversions for CAST Examples of CAST The CAST expression converts data to the data type you specify. CAST ({expression | NULL} AS data-type) expression | NULL specifies the operand to convert to the data type data-type. If the operand is an expression, then data-type depends on the data type of expression and follows the rules outlined in Valid Conversions for CAST.
Examples of CAST SQL/MX Functions and Expressions • • • • • A date value to a character string or to a TIMESTAMP (NonStop SQL/MX fills in the time part with 00:00:00.00). A time value to a character string or to a TIMESTAMP (NonStop SQL/MX fills in the date part with the current date). A timestamp value to a character string, a DATE, a TIME, or another TIMESTAMP with different fractional seconds precision.
SQL/MX Functions and Expressions CEILING Function VALUES (001, 'User JBrook, executed at ' || CAST (CURRENT_TIMESTAMP AS CHAR(26))); CEILING Function The CEILING function returns the smallest integer, represented as a FLOAT data type, greater than or equal to a numeric value expression. CEILING is an SQL/MX extension. CEILING (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the CEILING function.
CHAR Function SQL/MX Functions and Expressions CHAR Function The CHAR function returns the character that has the specified code value, which must be of exact numeric with scale 0. CHAR is an SQL/MX extension. CHAR(code-value, [,char-set-name]) code-value is a valid code value in the character set in use. char-set-name can be ISO88591, KANJI, KSC5601, or UCS2. The returned character will be associated with the character set specified by char-set-name with the DEFAULT collation. The default is ISO88591.
SQL/MX Functions and Expressions CHAR_LENGTH Function CHAR_LENGTH Function Considerations for CHAR_LENGTH SQL/MP Considerations for CHAR_LENGTH Examples of CHAR_LENGTH The CHAR_LENGTH function returns the number of characters in a string. You can also use CHARACTER_LENGTH. CHAR[ACTER]_LENGTH (string-value-expression) string-value-expression specifies the string value expression for which to return the length in characters.
Examples of CHAR_LENGTH SQL/MX Functions and Expressions This SELECT statement returns the same values for the character length and the octet length of the ISO88591 column. One character of an ISO88591 character set is equivalent to one byte. SELECT CHAR_LENGTH(col_char) AS CHARLENGTH_CHAR, OCTET_LENGTH(col_char) AS OCTETLENGTH_CHAR FROM tab; CHARLENGTH_CHAR --------------- OCTETLENGTH_CHAR ---------------- 10 10 --- 1 row(s) selected.
SQL/MX Functions and Expressions • Examples of CHAR_LENGTH The PROJDESC column in the PROJECT table has data type VARCHAR(18). This function returns the actual length of the column value—not 18 for shorter strings— because it is a VARCHAR value: SELECT CHAR_LENGTH (projdesc) FROM persnl.project; (EXPR) ---------14 13 13 17 9 9 --- 6 row(s) selected.
SQL/MX Functions and Expressions CODE_VALUE Function CODE_VALUE Function The CODE_VALUE function returns an unsigned integer (INTEGER UNSIGNED) that is the code point of the first character in a character value expression that can be associated with any character sets allowed. CODE_VALUE is an SQL/MX extension. CODE_VALUE(character-value-expression) character-value-expression is a character string.
SQL/MX Functions and Expressions CONCAT Function CONCAT Function The CONCAT function returns the concatenation of two character value expressions as a character string value. You can also use the concatenation operator (||). CONCAT is an SQL/MX extension. CONCAT (character-expr-1, character-expr-2) character-expr-1, character-expr-2 are SQL character value expressions (of data type CHAR or VARCHAR) that specify two strings of characters.
SQL/MX Functions and Expressions Examples of CONCAT To specify the type assignment of the parameter, use the CAST expression on the parameter as: CAST(?p AS CHAR(7)) || '2002' In this example, the parameter is not truncated, and the result of the concatenation is 5 March 2002. Examples of CONCAT Suppose that the LOGFILE table has been created in NonStop SQL/MP as: CREATE TABLE $sys.stats.
SQL/MX Functions and Expressions CONVERTTIMESTAMP Function CONVERTTIMESTAMP Function The CONVERTTIMESTAMP function converts a Julian timestamp to a value with data type TIMESTAMP. CONVERTTIMESTAMP is an SQL/MX extension. CONVERTTIMESTAMP (julian-timestamp) julian-timestamp is an expression that evaluates to a Julian timestamp, which is a LARGEINT value.
SQL/MX Functions and Expressions COS Function COS Function The COS function returns the cosine of a numeric value expression, where the expression is an angle expressed in radians. COS is an SQL/MX extension. COS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the COS function. See Numeric Value Expressions on page 6-48. Examples of COS • This function returns the value 9.39680940386503936E-001, or approximately 0.
SQL/MX Functions and Expressions COUNT Function COUNT Function The COUNT function counts the number of rows that result from a query or the number of rows that contain a distinct value in a specific column. The result of COUNT is data type LARGEINT. The result can never be NULL. COUNT {(*) | ([ALL | DISTINCT] expression)} COUNT (*) returns the number of rows in the table specified in the FROM clause of the SELECT statement that contains COUNT (*).
SQL/MX Functions and Expressions Examples of COUNT Nulls COUNT is evaluated after eliminating all nulls from the one-column table specified by the operand. If the table has no rows, COUNT returns zero. COUNT(*) does not eliminate null rows from the table specified in the FROM clause of the SELECT statement. If all rows in a table are null, COUNT(*) returns the number of rows in the table. Examples of COUNT • Count the number of rows in the EMPLOYEE table: SELECT COUNT (*) FROM persnl.
SQL/MX Functions and Expressions CURRENT Function CURRENT Function The CURRENT function returns a value of type TIMESTAMP based on the current local date and time. You can also use CURRENT_TIMESTAMP Function on page 9-37. CURRENT [(precision)] precision is an integer value in the range 0 to 6 that specifies the precision of (the number of decimal places in) the fractional seconds in the returned value. The default is 6.
CURRENT_DATE Function SQL/MX Functions and Expressions CURRENT_DATE Function The CURRENT_DATE function returns the local current date as a value of type DATE. CURRENT_DATE The CURRENT_DATE function returns the current date, such as 1997-09-28. The value returned is a value of type DATE, not a string value. Examples of CURRENT_DATE • Select rows from the ORDERS table based on the current date: SELECT * FROM sales.
SQL/MX Functions and Expressions CURRENT_TIME Function CURRENT_TIME Function The CURRENT_TIME function returns the current local time as a value of type TIME. CURRENT_TIME [(precision)] precision is an integer value in the range 0 to 6 that specifies the precision of (the number of decimal places in) the fractional seconds in the returned value. The default is 0.
SQL/MX Functions and Expressions CURRENT_TIMESTAMP Function CURRENT_TIMESTAMP Function The CURRENT_TIMESTAMP function returns a value of type TIMESTAMP based on the current local date and time. You can also use the CURRENT Function on page 9-34. CURRENT_TIMESTAMP [(precision)] precision is an integer value in the range 0 to 6 that specifies the precision of (the number of decimal places in) the fractional seconds in the returned value. The default is 6.
SQL/MX Functions and Expressions DATEFORMAT Function DATEFORMAT Function The DATEFORMAT function returns a datetime value as a character string literal in the DEFAULT, USA, or EUROPEAN format. The data type of the result is CHAR. DATEFORMAT is an SQL/MX extension. DATEFORMAT (datetime-expression,{DEFAULT | USA | EUROPEAN}) datetime-expression is an expression that evaluates to a datetime value of type DATE, TIME, or TIMESTAMP. See Datetime Value Expressions on page 6-39.
DAY Function SQL/MX Functions and Expressions DAY Function The DAY function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 31 that represents the corresponding day of the month. The result returned by the DAY function is equal to the result returned by the DAYOFMONTH function. DAY is an SQL/MX extension. DAY (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP.
DAYNAME Function SQL/MX Functions and Expressions DAYNAME Function The DAYNAME function converts a DATE or TIMESTAMP expression into a character literal that is the name of the day of the week (Sunday, Monday, and so on). DAYNAME is an SQL/MX extension. DAYNAME (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
DAYOFMONTH Function SQL/MX Functions and Expressions DAYOFMONTH Function The DAYOFMONTH function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 31 that represents the corresponding day of the month. The result returned by the DAYOFMONTH function is equal to the result returned by the DAY function. DAYOFMONTH is an SQL/MX extension. DAYOFMONTH (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP.
DAYOFWEEK Function SQL/MX Functions and Expressions DAYOFWEEK Function The DAYOFWEEK function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 7 that represents the corresponding day of the week. The value 1 represents Sunday, 2 represents Monday, and so forth. DAYOFWEEK is an SQL/MX extension. DAYOFWEEK (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions DAYOFYEAR Function DAYOFYEAR Function The DAYOFYEAR function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 366 that represents the corresponding day of the year. DAYOFYEAR is an SQL/MX extension. DAYOFYEAR (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions DEGREES Function DEGREES Function The DEGREES function converts a numeric value expression expressed in radians to the number of degrees. DEGREES is an SQL/MX extension. DEGREES (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the DEGREES function. See Numeric Value Expressions on page 6-48. Examples of DEGREES • This function returns the value 45 in degrees: DEGREES (0.
SQL/MX Functions and Expressions DIFF1 Function DIFF1 Function Considerations for DIFF1 Examples of DIFF1 The DIFF1 function is a sequence function that calculates the amount of change in an expression from row to row in an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. DIFF1 is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of DIFF1 dates, NonStop SQL/MX relaxes this restriction and allows division by a value of INTERVAL data type. Examples of DIFF1 Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions • Examples of DIFF1 Retrieve the difference between the TS column in the current row and the TS column in the previous row: SELECT DIFF1 (TS) AS DIFF1_TS FROM mining.seqfcn SEQUENCE BY TS; DIFF1_TS -------------------? 30002620.000000 134157861.000000 168588029.000000 114055223.000000 --- 5 row(s) selected. Note that the results are expressed as the number of seconds.
SQL/MX Functions and Expressions DIFF2 Function DIFF2 Function Considerations for DIFF2 Examples of DIFF2 The DIFF2 function is a sequence function that calculates the amount of change in a DIFF1 value from row to row in an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. DIFF2 is an SQL/MX extension.
Examples of DIFF2 SQL/MX Functions and Expressions dates, NonStop SQL/MX relaxes this restriction and allows division by a value of INTERVAL data type. Examples of DIFF2 Suppose that SEQFCN has been created as: CREATE TABLE mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions • Examples of DIFF2 Retrieve the difference in consecutive values of DIFF1(I1) divided by the difference in consecutive values of TS: SELECT DIFF2 (I1,TS) AS DIFF2_I1TS FROM mining.seqfcn SEQUENCE BY TS; DIFF2_I1TS --------------------? ? -.000231 -.000031 .000191 --- 5 row(s) selected.
SQL/MX Functions and Expressions EXP Function EXP Function This function returns the exponential value (to the base e) of a numeric value expression. EXP is an SQL/MX extension. EXP (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the EXP function. See Numeric Value Expressions on page 6-48. The minimum input value must be between -744.4400719 and -744.4400720. The maximum input value must be between 709.78271289338404 and 709.
SQL/MX Functions and Expressions EXPLAIN Function EXPLAIN Function Considerations for EXPLAIN Examples of EXPLAIN The EXPLAIN function is a table-valued stored function that generates a result table describing an access plan for a SELECT, INSERT, DELETE, UPDATE, or CALL statement. See Result of the EXPLAIN Function on page 9-53. The EXPLAIN function can be specified as a table reference (table) in the FROM clause of a SELECT statement if it is preceded by the keyword TABLE and surrounded by parentheses.
SQL/MX Functions and Expressions Considerations for EXPLAIN Considerations for EXPLAIN Using a Statement Pattern Using a statement pattern is analogous to using a LIKE pattern. For example, this statement returns the EXPLAIN result for all statements prepared within the current MXCI session: SELECT * FROM TABLE (EXPLAIN (NULL,'%')) This statement returns the EXPLAIN result for all statements prepared within the embedded SQL module named MYCAT.MYSCH.MYPROG: SELECT * FROM TABLE (EXPLAIN ('MYCAT.MYSCH.
Considerations for EXPLAIN SQL/MX Functions and Expressions A node of an operator tree is a point in the tree that represents an event (involving an operator) in a plan. Each node might have subordinate nodes—that is, each event might generate a subordinate event or events in the plan. Column Name Data Type Description MODULE_NAME CHAR(60) Module name as specified in the argument to the EXPLAIN function; if NULL, the name of the current module.
Considerations for EXPLAIN SQL/MX Functions and Expressions Column Name Data Type Description OPERATOR CHAR(30) Current node type; one of these: Operator CALL CURSOR_DELETE CURSOR_UPDATE ESP_EXCHANGE EXPLAIN EXPR FILE_SCAN FILE_SCAN_UNIQUE HASH_GROUPBY HASH_PARTIAL_GR..._LEAF HASH_PARTIAL_GR...
Examples of EXPLAIN SQL/MX Functions and Expressions Column Name Data Type Description SUBSET_DELETE SUBSET_UPDATE TRANSPOSE TUPLE_FLOW TUPLELIST UNIQUE_DELETE UNIQUE_UPDATE UNPACK VALUES DAM subset DAM subset Data mining Join Tuple DAM unique DAM unique Rowset Tuple LEFT_CHILD_ SEQ_NUM INT Sequence number for the first child operator of the current node (or operator); null if node has no child operators.
Examples of EXPLAIN SQL/MX Functions and Expressions The DISPLAY_EXPLAIN command display for the prepared statement named FINDEMP is identical to the DISPLAY_EXPLAIN command display shown under DISPLAY_EXPLAIN Command on page 4-13.
Examples of EXPLAIN SQL/MX Functions and Expressions --- 7 row(s) selected. The second plan is forced by this CONTROL QUERY SHAPE statement: control query shape nested_join( partition_access(scan), partition_access(scan('JOB'))); PREPARE FINDEMP2 FROM SELECT last_name, first_name, deptnum, employee.jobcode, jobdesc FROM employee, job WHERE deptnum = 3100 AND employee.jobcode = job.
SQL/MX Functions and Expressions EXTRACT Function EXTRACT Function The EXTRACT function extracts a datetime field from a datetime or interval value expression. It returns an exact numeric value. EXTRACT (datetime-field FROM extract-source) datetime-field is: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND extract-source is: datetime-expression | interval-expression See Datetime Value Expressions on page 6-39 and Interval Value Expressions on page 6-43.
SQL/MX Functions and Expressions FLOOR Function FLOOR Function The FLOOR function returns the largest integer, represented as a FLOAT data type, less than or equal to a numeric value expression. FLOOR is an SQL/MX extension. FLOOR (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the FLOOR function. See Numeric Value Expressions on page 6-48. Examples of FLOOR • This function returns the integer value 2.
SQL/MX Functions and Expressions HASHPARTFUNC Function HASHPARTFUNC Function HashPartFunc is the function NonStop SQL/MX uses to hash partition data. HashPartFunc returns the number of the partition to which a row identified by the specified partitioning key would belong if the table were hash partitioned. HashPartFunc is an SQL/MX extension. HashPartFunc(partitioning-key FOR num-partitions) partitioning-key is the prospective partitioning key value of a row from a partitioned or nonpartitioned table.
Examples of HashPartFunc SQL/MX Functions and Expressions • This example uses the EMPLOYEE table from the sample database to show the partition number of each row based on the EMPNUM for four partitions and ordered by partition and EMPNUM. This example shows how HashPartFunc can reveal data skew.
Examples of HashPartFunc SQL/MX Functions and Expressions 23 32 65 87 104 178 180 202 205 207 211 212 214 215 216 218 222 227 993 72 111 206 213 220 231 234 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 --- 62 row(s) selected. • This example shows the number of rows that will reside in each partition if you create a new table that is hash-partitioned with four partitions, using the EMPNUM column from the EMPLOYEE table.
Examples of HashPartFunc SQL/MX Functions and Expressions b as the partitioning key) and populate it with the 1000 data rows that currently reside in cat.sch.table1: >>SELECT partitionNum, count(*) +>FROM (SELECT HashPartFunc(CAST(a AS INT NOT NULL), CAST(b AS CHAR(3) NOT NULL) FOR 4) +> FROM cat.sch.table1) AS Tmp(partitionNum) +>GROUP BY partitionNum +>ORDER BY partitionNum; PARTITIONNUM (EXPR) ------------ -------------------0 1 2 3 264 265 230 241 --- 4 row(s) selected.
HOUR Function SQL/MX Functions and Expressions HOUR Function The HOUR function converts a TIME or TIMESTAMP expression into an INTEGER value in the range 0 through 23 that represents the corresponding hour of the day. HOUR is an SQL/MX extension. HOUR (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type TIME or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions INSERT Function INSERT Function The INSERT function returns a character string where a specified number of characters within the character string have been deleted beginning at a specified start position and then another character string has been inserted at the start position. INSERT is an SQL/MX extension.
JULIANTIMESTAMP Function SQL/MX Functions and Expressions JULIANTIMESTAMP Function The JULIANTIMESTAMP function converts a datetime value into a 64-bit Julian timestamp value that represents the number of microseconds that have elapsed between 4713 B.C., January 1, 00:00, and the specified datetime value. JULIANTIMESTAMP returns a value of data type LARGEINT. JULIANTIMESTAMP is an SQL/MX extension.
SQL/MX Functions and Expressions LASTNOTNULL Function LASTNOTNULL Function The LASTNOTNULL function is a sequence function that returns the last nonnull value of a column in an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. LASTNOTNULL is an SQL/MX extension. LASTNOTNULL (column-expression) column-expression specifies a derived column determined by the evaluation of the column expression.
LCASE Function SQL/MX Functions and Expressions LCASE Function The LCASE function downshifts characters. LCASE can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the LCASE function is equal to the result returned by the LOWER function.
SQL/MX Functions and Expressions LEFT Function LEFT Function The LEFT function returns the leftmost specified number of characters from a character expression. LEFT is an SQL/MX extension. LEFT (character-expr, count) character-expr specifies the source string from which to return the leftmost specified number of characters. The source string is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions LOCATE Function LOCATE Function The LOCATE function searches for a given substring in a character string. If the substring is found, NonStop SQL/MX returns the character position of the substring within the string. The result returned by the LOCATE function is equal to the result returned by the POSITION function. LOCATE is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of LOCATE Examples of LOCATE • Return the value 8 for the position of the substring ‘John’ within the string: LOCATE ('John','Robert John Smith') • Suppose that the EMPLOYEE table has an EMPNAME column that contains both the first and last names. This SELECT statement returns all records in table EMPLOYEE that contain the substring 'SMITH', regardless of whether the column value is in uppercase or lowercase characters: SELECT * FROM persnl.
SQL/MX Functions and Expressions LOG Function LOG Function The LOG function returns the natural logarithm of a numeric value expression. LOG is an SQL/MX extension. LOG (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the LOG function. The value of the argument must be greater than zero. See Numeric Value Expressions on page 6-48. Examples of LOG • This function returns the value 6.93147180559945504E-001, or approximately 0.
LOWER Function SQL/MX Functions and Expressions LOWER Function Considerations for LOWER Examples of LOWER The LOWER function downshifts characters. LOWER can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the LOWER function is equal to the result returned by the LCASE function.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Examples of LOWER SQL/MX Functions and Expressions Examples of LOWER • Suppose that your CUSTOMER table includes an entry for Hotel Oregon. Select the column CUSTNAME and return the result in uppercase and lowercase letters by using the UPPER and LOWER functions: SELECT custname,UPPER(custname),LOWER(custname) FROM sales.customer; (EXPR) ----------------... Hotel Oregon (EXPR) ------------------... HOTEL OREGON (EXPR) -----------------... hotel oregon --- 17 row(s) selected.
SQL/MX Functions and Expressions LPAD Function LPAD Function The LPAD function replaces the leftmost specified number of characters in a character expression with a padding character. LPAD is an SQL/MX extension. LPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-37. count specifies the number of characters to be replaced in character-expr.
LTRIM Function SQL/MX Functions and Expressions LTRIM Function The LTRIM function removes leading spaces from a character string. LTRIM is an SQL/MX extension. LTRIM (character-expression) character-expression is an SQL character value expression and specifies the string from which to trim leading spaces. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions MAX Function MAX Function MAX is an aggregate function that returns the maximum value within a set of values. The data type of the result is the same as the data type of the argument. MAX ([ALL | DISTINCT] expression) ALL | DISTINCT specifies whether duplicate values are included in the computation of the maximum of the expression. The default option is ALL, which causes duplicate values to be included.
SQL/MX Functions and Expressions MIN Function MIN Function MIN is an aggregate function that returns the minimum value within a set of values. The data type of the result is the same as the data type of the argument. MIN ([ALL | DISTINCT] expression) ALL | DISTINCT specifies whether duplicate values are included in the computation of the minimum of the expression. The default option is ALL, which causes duplicate values to be included.
MINUTE Function SQL/MX Functions and Expressions MINUTE Function The MINUTE function converts a TIME or TIMESTAMP expression into an INTEGER value, in the range 0 through 59, that represents the corresponding minute of the hour. MINUTE is an SQL/MX extension. MINUTE (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type TIME or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions MOD Function MOD Function The MOD function returns the remainder (modulus) of an integer value expression divided by an integer value expression. MOD is an SQL/MX extension. MOD (integer-expression-1,integer-expression-2) integer-expression-1 is an SQL numeric value expression of data type SMALLINT, INTEGER, or LARGEINT that specifies the value for the dividend argument of the MOD function.
MONTH Function SQL/MX Functions and Expressions MONTH Function The MONTH function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 12 that represents the corresponding month of the year. MONTH is an SQL/MX extension. MONTH (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
MONTHNAME Function SQL/MX Functions and Expressions MONTHNAME Function The MONTHNAME function converts a DATE or TIMESTAMP expression into a character literal that is the name of the month of the year (January, February, and so on). MONTHNAME is an SQL/MX extension. MONTHNAME (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions MOVINGAVG Function MOVINGAVG Function The MOVINGAVG function is a sequence function that returns the average of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGAVG is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of MOVINGAVG Examples of MOVINGAVG Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions MOVINGCOUNT Function MOVINGCOUNT Function The MOVINGCOUNT function is a sequence function that returns the number of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGCOUNT is an SQL/MX extension.
SQL/MX Functions and Expressions Considerations for MOVINGCOUNT Considerations for MOVINGCOUNT No DISTINCT Clause The MOVINGCOUNT sequence function is defined differently from the COUNT aggregate function. If you specify DISTINCT for the COUNT aggregate function, duplicate values are eliminated before COUNT is applied. Note that you cannot specify DISTINCT for the MOVINGCOUNT sequence function; duplicate values are counted.
SQL/MX Functions and Expressions MOVINGMAX Function MOVINGMAX Function The MOVINGMAX function is a sequence function that returns the maximum of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGMAX is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of MOVINGMAX Examples of MOVINGMAX Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions MOVINGMIN Function MOVINGMIN Function The MOVINGMIN function is a sequence function that returns the minimum of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGMIN is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of MOVINGMIN Examples of MOVINGMIN Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions MOVINGSTDDEV Function MOVINGSTDDEV Function The MOVINGSTDDEV function is a sequence function that returns the standard deviation of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGSTDDEV is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of MOVINGSTDDEV Examples of MOVINGSTDDEV Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions MOVINGSUM Function MOVINGSUM Function The MOVINGSUM function is a sequence function that returns the sum of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGSUM is an SQL/MX extension. MOVINGSUM (column-expression,integer-expression [,max-rows]) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions Examples of MOVINGSUM Examples of MOVINGSUM Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions MOVINGVARIANCE Function MOVINGVARIANCE Function The MOVINGVARIANCE function is a sequence function that returns the variance of nonnull values of a column in the current window of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. MOVINGVARIANCE is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of MOVINGVARIANCE Examples of MOVINGVARIANCE Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions OCTET_LENGTH Function OCTET_LENGTH Function The OCTET_LENGTH function returns the length of a character string in bytes. OCTET_LENGTH (string-value-expression) string-value-expression specifies the string value expression for which to return the length in bytes. NonStop SQL/MX returns the result as a 2-byte signed integer with a scale of zero. If string-value-expression is null, NonStop SQL/MX returns a length of zero. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions OFFSET Function OFFSET Function The OFFSET function is a sequence function that retrieves columns from previous rows of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. OFFSET is an SQL/MX extension. OFFSET (column-expression,number-rows [,max-rows]) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions • Examples of OFFSET Retrieve the I1 column offset by three rows: SELECT OFFSET (I1,3) AS OFFSET3 FROM mining.seqfcn SEQUENCE BY TS; OFFSET3 -----------? ? ? 6215 28174 --- 5 row(s) selected. Note that the first three rows retrieved display null because the offset from the current row does not fall within the result table.
SQL/MX Functions and Expressions PI Function The PI function returns the constant value of pi as a floating-point value. PI is an SQL/MX extension. PI() Examples of PI • This constant function returns the value 3.
SQL/MX Functions and Expressions POSITION Function POSITION Function The POSITION function searches for a given substring in a character string. If the substring is found, NonStop SQL/MX returns the character position of the substring within the string. The result returned by the POSITION function is equal to the result returned by the LOCATE function.
SQL/MX Functions and Expressions Examples of POSITION Examples of POSITION • This function returns the value 8 for the position of the substring ‘John’ within the string: POSITION ('John' IN 'Robert John Smith') • Suppose that the EMPLOYEE table has an EMPNAME column that contains both the first and last names. Return all records in table EMPLOYEE that contain the substring 'Smith' regardless of whether the column value is in uppercase or lowercase characters: SELECT * FROM persnl.
QUARTER Function SQL/MX Functions and Expressions QUARTER Function The QUARTER function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 4 that represents the corresponding quarter of the year. Quarter 1 represents January 1 through March 31, and so on. QUARTER is an SQL/MX extension. QUARTER (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
QUERYCACHE Function SQL/MX Functions and Expressions QUERYCACHE Function Considerations for QUERYCACHE Examples of QUERYCACHE The query plan cache automatically collects statistics regarding its use. When invoked, the QUERYCACHE table-valued stored function collects and returns the current state of these statistics in a single row table. The statistics are reinitialized when an mxcmp session is started and each mxcmp session maintains an independent set of statistics.
Considerations for QUERYCACHE SQL/MX Functions and Expressions Column Name Data Type Description MAX_NUM_VICTIMS INT Maximum number of plans that can be removed from the cache to make room for a new entry. NUM_ENTRIES INT Total number of entries in the cache. NUM_PINNED INT Total number of pinned entries. NUM_COMPILES INT Total number of complete compile requests (excludes DESCRIBE and SHOWSHAPE commands). NUM_RECOMPILES INT Total number of recompilations.
Examples of QUERYCACHE SQL/MX Functions and Expressions Column Name Data Type Description NUM_DISPLACED INT Number of entries removed from the cache to make room for new entries or as a consequence of a resizing of the cache or a recompilation. OPTIMIZATION_LEVEL CHAR(10) Indicates the current level of query optimization. Can be 0, 1, 2, 3, 4, or 5. PINNING_STATE CHAR(4) Current state of pinning, ON or OFF.
SQL/MX Functions and Expressions • Examples of QUERYCACHE Display selected query plan caching statistics from the same query: SELECT NUM_RETRIES, OPTIMIZATION_LEVEL FROM TABLE (QUERYCACHE ()); NUM_RETRIES OPTIMIZATION_LEVEL ---------- -----------------0 3 --- 1 row(s) selected.
SQL/MX Functions and Expressions QUERYCACHEENTRIES Function QUERYCACHEENTRIES Function The query plan cache automatically collects statistics on each entry of the cache. When invoked, the QUERYCACHEENTRIES table-valued function collects and returns these statistics in a table with one row for each entry of the cache. The statistics are reinitialized when an mxcmp session is started. Each mxcmp session maintains an independent set of statistics. The QUERYCACHEENTRIES function is an SQL/MX extension.
Considerations for QUERYCACHEENTRIES SQL/MX Functions and Expressions Result of the QUERYCACHEENTRIES Function The result table of the QUERYCACHEENTRIES function describes the query plan caching information for each entry in the query plan cache. For more information about the types of statements that are appropriate candidates for query plan caching, see the SQL/MX Query Guide. Column Name Data Type Description ROW_ID INT A zero-based sequential number.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions Column Name Data Type Description SHAPE CHAR(1024) Required CONTROL QUERY SHAPE of the query associated with this entry. Blank if no required shape. ISOLATION_LEVEL CHAR(20) Transaction isolation level for this entry. Can be READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE, or NOT SPECIFIED. ACCESS_MODE CHAR(20) Transaction access mode value associated with this entry. Can be READ ONLY, READ WRITE, or NOT SPECIFIED.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions 100 200 250 MANAGER PRODUCTION SUPV ASSEMBLER . . . --- 10 row(s) selected.
SQL/MX Functions and Expressions RADIANS Function RADIANS Function The RADIANS function converts a numeric value expression expressed in degrees to the number of radians. RADIANS is an SQL/MX extension. RADIANS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the RADIANS function. See Numeric Value Expressions on page 6-48. Examples of RADIANS • Return the value 7.85398150000000160E-001, or approximately 0.
SQL/MX Functions and Expressions REPEAT Function REPEAT Function The REPEAT function returns a character string composed of the evaluation of a character expression repeated a specified number of times. REPEAT is an SQL/MX extension. REPEAT (character-expr, count) character-expr specifies the source string from which to return the specified number of repeated strings. The source string is an SQL character value expression. The operand is the result of evaluating character-expr.
SQL/MX Functions and Expressions REPLACE Function REPLACE Function The REPLACE function returns a character string where all occurrences of a specified character string in the original string are replaced with another character string. REPLACE is an SQL/MX extension. REPLACE (char-expr-1, char-expr-2, char-expr-3) char-expr-1, char-expr-2, char-expr-3 are SQL character value expressions. The operands are the result of evaluating the character expressions.
SQL/MX Functions and Expressions RIGHT Function RIGHT Function The RIGHT function returns the rightmost specified number of characters from a character expression. RIGHT is an SQL/MX extension. RIGHT (character-expr, count) character-expr specifies the source string from which to return the rightmost specified number of characters. The source string is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions ROWS SINCE Function ROWS SINCE Function The ROWS SINCE function is a sequence function that returns the number of rows counted since the specified condition was last true in the intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. ROWS SINCE is an SQL/MX extension. ROWS SINCE [INCLUSIVE] (condition [,max-rows]) INCLUSIVE specifies the current row is to be considered.
Examples of ROWS SINCE SQL/MX Functions and Expressions Examples of ROWS SINCE Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,I2 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions RPAD Function RPAD Function The RPAD function replaces the rightmost specified number of characters in a character expression with a padding character. RPAD is an SQL/MX extension. RPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-37. count specifies the number of characters to be replaced in character-expr.
RTRIM Function SQL/MX Functions and Expressions RTRIM Function The RTRIM function removes trailing spaces from a character string. RTRIM is an SQL/MX extension. RTRIM (character-expression) character-expression is an SQL character value expression and specifies the string from which to trim trailing spaces. See Character Value Expressions on page 6-37.
SQL/MX Functions and Expressions RUNNINGAVG Function RUNNINGAVG Function The RUNNINGAVG function is a sequence function that returns the average of nonnull values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGAVG is an SQL/MX extension. RUNNINGAVG (column-expression) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions • Examples of RUNNINGAVG Return the average of nonnull values of I1 up to and including the current row: SELECT RUNNINGAVG (I1) AS AVG_I1 FROM mining.seqfcn SEQUENCE BY TS; AVG_I1 -------------------6215 17194 11463 9746 10190 --- 5 row(s) selected.
SQL/MX Functions and Expressions RUNNINGCOUNT Function RUNNINGCOUNT Function The RUNNINGCOUNT function is a sequence function that returns the number of rows up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGCOUNT is an SQL/MX extension.
SQL/MX Functions and Expressions Examples of RUNNINGCOUNT The table SEQFCN has columns I1 and TS with data that is sequenced by column TS: I1 TS 6215 TIMESTAMP '1950-03-05 08:32:09' 28174 TIMESTAMP '1951-02-15 14:35:49' null TIMESTAMP '1955-05-18 08:40:10' 4597 TIMESTAMP '1960-09-19 14:40:39' 11966 TIMESTAMP '1964-05-01 16:41:02' • Return the number of rows up to and including the current row: SELECT RUNNINGCOUNT (*) AS COUNT_ROWS FROM mining.
SQL/MX Functions and Expressions RUNNINGMAX Function RUNNINGMAX Function The RUNNINGMAX function is a sequence function that returns the maximum of values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGMAX is an SQL/MX extension. RUNNINGMAX (column-expression) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions • Examples of RUNNINGMAX Return the maximum of values of I1 up to and including the current row: SELECT RUNNINGMAX (I1) AS MAX_I1 FROM mining.seqfcn SEQUENCE BY TS; MAX_I1 -----------6215 28174 28174 28174 28174 --- 5 row(s) selected.
SQL/MX Functions and Expressions RUNNINGMIN Function RUNNINGMIN Function The RUNNINGMIN function is a sequence function that returns the minimum of values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGMIN is an SQL/MX extension. RUNNINGMIN (column-expression) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions • Examples of RUNNINGMIN Return the minimum of values of I1 up to and including the current row: SELECT RUNNINGMIN (I1) AS MIN_I1 FROM mining.seqfcn SEQUENCE BY TS; MIN_I1 -----------6215 6215 6215 4597 4597 --- 5 row(s) selected.
SQL/MX Functions and Expressions RUNNINGSTDDEV Function RUNNINGSTDDEV Function The RUNNINGSTDDEV function is a sequence function that returns the standard deviation of nonnull values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGSTDDEV is an SQL/MX extension.
SQL/MX Functions and Expressions • Examples of RUNNINGSTDDEV Return the standard deviation of nonnull values of I1 up to and including the current row: SELECT RUNNINGSTDDEV (I1) AS STDDEV_I1 FROM mining.seqfcn SEQUENCE BY TS; STDDEV_I1 ------------------------0.00000000000000000E+000 1.55273578080753976E+004 1.48020166531456112E+004 1.25639147428923072E+004 1.09258501408357232E+004 --- 5 row(s) selected. Note that you can use the CAST function for display purposes.
SQL/MX Functions and Expressions RUNNINGSUM Function RUNNINGSUM Function The RUNNINGSUM function is a sequence function that returns the sum of nonnull values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGSUM is an SQL/MX extension. RUNNINGSUM (column-expression) column-expression specifies a derived column determined by the evaluation of the column expression.
SQL/MX Functions and Expressions • Examples of RUNNINGSUM Return the sum of nonnull values of I1 up to and including the current row: SELECT RUNNINGSUM (I1) AS SUM_I1 FROM mining.seqfcn SEQUENCE BY TS; SUM_I1 -------------------6215 34389 34389 38986 50952 --- 5 row(s) selected.
SQL/MX Functions and Expressions RUNNINGVARIANCE Function RUNNINGVARIANCE Function The RUNNINGVARIANCE function is a sequence function that returns the variance of nonnull values of a column up to and including the current row of an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. RUNNINGVARIANCE is an SQL/MX extension.
SQL/MX Functions and Expressions • Examples of RUNNINGVARIANCE Return the variance of nonnull values of I1 up to and including the current row: SELECT RUNNINGVARIANCE (I1) AS VARIANCE_I1 FROM mining.seqfcn SEQUENCE BY TS; VARIANCE_I1 ------------------------0.00000000000000000E+000 2.41098840499999960E+008 2.19099696999999968E+008 1.57851953666666640E+008 1.19374201299999980E+008 --- 5 row(s) selected. Note that you can use the CAST function for display purposes.
SECOND Function SQL/MX Functions and Expressions SECOND Function The SECOND function converts a TIME or TIMESTAMP expression into an INTEGER value in the range 0 through 59 that represents the corresponding second of the hour. SECOND is an SQL/MX extension. SECOND (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type TIME or TIMESTAMP. See Datetime Value Expressions on page 6-39.
SQL/MX Functions and Expressions SESSION_USER Function SESSION_USER Function The SESSION_USER function returns the current Guardian user ID as variable-length character data in the form group.name. SESSION_USER The SESSION_USER function is equivalent to the CURRENT_USER Function on page 9-37 and the USER Function on page 9-165 Examples of SESSION_USER • Use SESSION_USER to display the current session user: SELECT SESSION_USER FROM logfile; (EXPR) ----------------------DCS.TSHAW ...
SQL/MX Functions and Expressions SIN Function SIN Function The SIN function returns the sine of a numeric value expression, where the expression is an angle expressed in radians. SIN is an SQL/MX extension. SIN (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the SIN function. See Numeric Value Expressions on page 6-48. Examples of SIN • This function returns the value 3.42052233254419920E-001, or approximately 0.
SQL/MX Functions and Expressions SPACE Function SPACE Function The SPACE function returns a character string consisting of a specified number of spaces. SPACE is an SQL/MX extension. SPACE (length [,char-set-name]) length specifies the number of characters to be returned. The number count must be a value greater than or equal to zero of exact numeric data type and with a scale of zero. length cannot exceed 4096. char-set-name can be ISO88591, KANJI, KSC5601, or UCS2. The default is ISO88591.
SQL/MX Functions and Expressions STDDEV Function STDDEV Function Considerations for STDDEV Examples of STDDEV STDDEV is an aggregate function that returns the standard deviation of a set of numbers. STDDEV is an SQL/MX extension. STDDEV ([ALL | DISTINCT] expression [,weight]) ALL | DISTINCT specifies whether duplicate values are included in the computation of the STDDEV of the expression. The default option is ALL, which causes duplicate values to be included.
SQL/MX Functions and Expressions Examples of STDDEV Data Type of the Result The data type of the result is always DOUBLE PRECISION. Operands of the Expression The expression includes columns from the rows of the SELECT result table but cannot include an aggregate function. These are valid: STDDEV (SALARY) STDDEV (SALARY * 1.1) STDDEV (PARTCOST * QTY_ORDERED) Nulls STDDEV is evaluated after eliminating all nulls from the set. If the result table is empty, STDDEV returns NULL.
Examples of STDDEV SQL/MX Functions and Expressions • Suppose that your database includes a WEATHER table, which is created by using SQLCI in this way: CREATE TABLE $db.mining.weather ( city VARCHAR (20) NO DEFAULT NOT NULL ,state CHAR (2) NO DEFAULT NOT NULL ,date_weather DATE NO DEFAULT NOT NULL ,temperature NUMERIC (3) SIGNED ,weight NUMERIC (2) UNSIGNED ,PRIMARY KEY (city, state, date_weather) ) CATALOG $db.
SQL/MX Functions and Expressions SUBSTRING Function SUBSTRING Function The SUBSTRING function extracts a substring out of a given character expression. It returns a character string of data type VARCHAR, with maximum length equal to the fixed length or maximum variable length of the character expression. SUBSTRING (character-expr FROM start-position [FOR length]) or: SUBSTRING (character-expr,start-position,length) character-expr specifies the source string from which to extract the substring.
SQL/MX Functions and Expressions • The resulting substring is always of type VARCHAR. If the source character string is an upshifted CHAR or VARCHAR string, the result is an upshifted VARCHAR type.
SQL/MX Functions and Expressions SUM Function SUM Function SUM is an aggregate function that returns the sum of a set of numbers. SUM ([ALL | DISTINCT] expression) ALL | DISTINCT specifies whether duplicate values are included in the computation of the SUM of the expression. The default option is ALL, which causes duplicate values to be included. If you specify DISTINCT, duplicate values are eliminated before the SUM function is applied.
SQL/MX Functions and Expressions Examples of SUM • Compute the total value of parts in the current inventory: SELECT SUM (price * qty_available) FROM sales.parts; (EXPR) --------------------117683505.96 --- 1 row(s) selected.
SQL/MX Functions and Expressions TAN Function TAN Function The TAN function returns the tangent of a numeric value expression, where the expression is an angle expressed in radians. TAN is an SQL/MX extension. TAN (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the TAN function. See Numeric Value Expressions on page 6-48. Examples of TAN • This function returns the value 3.64008908293626896E-001, or approximately 0.
SQL/MX Functions and Expressions THIS Function THIS Function The THIS function is a sequence function that is used in the ROWS SINCE function to distinguish between the value of the column in the current row and the value of the column in previous rows (in an intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement). See ROWS SINCE Function on page 9-120. THIS is an SQL/MX extension.
SQL/MX Functions and Expressions Example of THIS The table SEQFCN has columns I1 and TS with data that is sequenced by column TS: I1 TS 6215 TIMESTAMP '1950-03-05 08:32:09' 28174 TIMESTAMP '1951-02-15 14:35:49' 19058 TIMESTAMP '1955-05-18 08:40:10' 4597 TIMESTAMP '1960-09-19 14:40:39' 31966 TIMESTAMP '1964-05-01 16:41:02' • Return the number of rows since the condition I1 less than a previous row became true: SELECT ROWS SINCE (THIS(I1) < I1) AS ROWS_SINCE_THIS FROM mining.
TRANSLATE Function SQL/MX Functions and Expressions TRANSLATE Function The TRANSLATE function translates a character string from a source character set to a target character set. TRANSLATE(character-value-expression USING translation-name) character-value-expression is a character string. translation-name is one of these translation names: Translation Name Source Character Set Target Character Set Comments ISO8859XToUCS2 (X in 1) ISO8859X UCS2 No data loss is possible.
SQL/MX Functions and Expressions TRANSLATE Function translation and the maximum length equal to the fix length or maximum variable length of the source character-value-expression. If you enter an illegal translation-name, NonStop SQL/MX returns an error. If the character set for character-value-expression is different from the source character set as specified in the translation-name, NonStop SQL/MX returns an error.
TRIM Function SQL/MX Functions and Expressions TRIM Function The TRIM function removes leading and trailing characters from a character string. TRIM ([[trim-type] [trim-char] FROM] trim-source) trim-type is: LEADING | TRAILING | BOTH trim-type specifies whether characters are to be trimmed from the leading end (LEADING), trailing end (TRAILING), or both ends (BOTH) of trim-source. If you omit trimtype, the default is BOTH.
SQL/MX Functions and Expressions UCASE Function UCASE Function Considerations for UCASE Examples of UCASE The UCASE function upshifts characters. UCASE can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UCASE function is equal to the result returned by the UPPER or UPSHIFT function.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
SQL/MX Functions and Expressions Table 9-3.
SQL/MX Functions and Expressions Table 9-3.
SQL/MX Functions and Expressions Table 9-3.
Examples of UCASE SQL/MX Functions and Expressions Table 9-4. Three-Character UCS2 Mapping (page 2 of 2) Titlecase characters Three-Character Uppercase Expansions 0x1FE7 0x03A5 0x0308 0x0342 0x1FF7 0x03A9 0x0342 0x0399 0xFB03 0x0046 0x0046 0x0049 Examples of UCASE • Suppose that your CUSTOMER table includes an entry for Hotel Oregon.
UPPER Function SQL/MX Functions and Expressions UPPER Function The UPPER function upshifts characters. UPPER can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UPPER function is equal to the result returned by the UPSHIFT or UCASE function.
UPSHIFT Function SQL/MX Functions and Expressions UPSHIFT Function The UPSHIFT function upshifts characters. UPSHIFT can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UPSHIFT function is equal to the result returned by the UPPER or UCASE function.
SQL/MX Functions and Expressions • USER Function Suppose that your database includes two department tables: DEPT1 and DEPT2. Return all rows from the two tables in which the department names have the same value regardless of case: SELECT * FROM persnl.dept1 D1, persnl.dept2 D2 WHERE UPSHIFT(D1.deptname) = UPSHIFT(D2.deptname); USER Function The USER function returns the current Guardian user ID as variable-length character data in the form group.name.
SQL/MX Functions and Expressions VARIANCE Function VARIANCE Function Considerations for VARIANCE Examples of VARIANCE VARIANCE is an aggregate function that returns the statistical variance of a set of numbers. VARIANCE is an SQL/MX extension. VARIANCE ([ALL | DISTINCT] expression [,weight]) ALL | DISTINCT specifies whether duplicate values are included in the computation of the VARIANCE of the expression. The default option is ALL, which causes duplicate values to be included.
Considerations for VARIANCE SQL/MX Functions and Expressions Definition When Weight Is Not Specified If weight is not specified, the statistical variance of the values in the one-column result table is defined as: N ∑ (v i i =1 − v )2 N −1 where vi is the i-th value of expression, v is the average value expressed in the common data type, and N is the cardinality of the result table.
Considerations for VARIANCE SQL/MX Functions and Expressions Weighted Average The weighted average vw of vi and wi is defined as: N ∑ vi ⋅ wi i =1 N ∑ wi i =1 where vi is the i-th value of expression, wi is the i-th value of weight, and N is the cardinality of the result table. Data Type of the Result The data type of the result is always DOUBLE PRECISION. Operands of the Expression The expression includes columns from the rows of the SELECT result table—but cannot include an aggregate function.
Examples of VARIANCE SQL/MX Functions and Expressions Examples of VARIANCE • Compute the variance of the salary of the current employees: SELECT VARIANCE(salary) AS Variance_Salary FROM persnl.employee; VARIANCE_SALARY ------------------------1.27573263588496116E+009 --- 1 row(s) selected. • Compute the variance of the cost of parts in the current inventory: SELECT VARIANCE (price * qty_available) FROM sales.parts; (EXPR) ------------------------5.09652410092950336E+013 --- 1 row(s) selected.
SQL/MX Functions and Expressions ° Examples of VARIANCE Find the variance of the TEMPERATURE column: SELECT VARIANCE(temperature) FROM weather; (EXPR) ------------------------1.64500000000000024E+002 --- 1 row(s) selected. ° Find the variance of the TEMPERATURE column by CITY: SELECT city, VARIANCE (temperature) FROM weather GROUP BY city; CITY ---------Austin Cupertino (EXPR) ------------------------3.55666666666666720E+002 0.00000000000000000E+000 --- 2 row(s) selected.
WEEK Function SQL/MX Functions and Expressions WEEK Function The WEEK function converts a DATE or TIMESTAMP expression into an INTEGER value in the range 1 through 54 that represents the corresponding week of the year. WEEK is an SQL/MX extension. WEEK (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
YEAR Function SQL/MX Functions and Expressions YEAR Function The YEAR function converts a DATE or TIMESTAMP expression into an INTEGER value that represents the year. YEAR is an SQL/MX extension. YEAR (datetime-expression) datetime-expression is an expression that evaluates to a datetime value of type DATE or TIMESTAMP. See Datetime Value Expressions on page 6-39.
10 Metadata Tables This section describes: Migrating SQL/MP Metadata on page 10-2 SQL/MX Metadata Catalogs on page 10-3 SQL/MX Metadata Schemas and Tables on page 10-3 System Schema Tables on page 10-8 Definition Schema Tables on page 10-11 System Defaults Table on page 10-30 User Metadata Tables (UMD): Histogram Tables on page 10-70 MXCS Metadata Tables on page 10-79 NonStop SQL/MX stores system metadata for all objects in SQL/MX tables, automatically creating and maintaining metadata as users create, al
Migrating SQL/MP Metadata Metadata Tables without the surrounding double quotes, and with two consecutive double quotes collapsed into one double quote. • Unless otherwise stated, CHAR(n) in the data type field without a character set qualifier is associated with the ISO88591 character set. All character types are searched or sorted with the DEFAULT (binary) collation with the PAD SPACE characteristic. For SQL/MX Release 2.
SQL/MX Metadata Catalogs Metadata Tables SQL/MX Metadata Catalogs There is one system catalog per node where NonStop SQL/MX has been initialized. It is stored in NONSTOP_SQLMX_nodename on the Data Access Manager volume specified as the system metadata volume during installation.There are five schemas in the system catalog: • • • • • DEFINITION_SCHEMA_VERSION_vernum. MXCS_SCHEMA SYSTEM_DEFAULTS_SCHEMA SYSTEM_SCHEMA SYSTEM_SQLJ_SCHEMA You can create as many user catalogs as you wish on a node.
Definition Schema Tables: Schema DEFINITION_SCHEMA_VERSION_vernum Metadata Tables Definition Schema Tables: Schema DEFINITION_SCHEMA_VERSION_vernum Additional system metadata for each object is stored in schema DEFINITION_SCHEMA_VERSION_vernum in the catalog that contains the object. NonStop SQL/MX automatically creates this schema and all its tables when you execute the first CREATE SCHEMA statement for that catalog.
System Defaults Tables (User Metadata Tables): Schema SYSTEM_DEFAULTS_SCHEMA Metadata Tables TBL_PRIVILEGES Table on page 10-24 Grant information for a table in the catalog TEXT Table on page 10-25 Text associated with objects TRIGGERS Table on page 10-25 Information about triggers TRIGGERS_CAT_USAGE Table on page 10-26 How triggers use objects in other catalogs TRIGGER_USED Table on page 10-27 Describes how triggers use objects VWS Table on page 10-28 Views in the catalog VW_COL_TBLS Table on
MXCS Metadata Tables: Schema MXCS_SCHEMA Metadata Tables MXCS Metadata Tables: Schema MXCS_SCHEMA This table lists MXCS tables in MXCS_SCHEMA*: ASSOC2DS Table on page 10-79 Associates MXCS service to a data source DATASOURCES Table on page 10-80 Data source information ENVIRONMENTVALUES Table on page 10-81 Sets, controls and defines environment values NAME2ID Table on page 10-81 Associates service or data source name to ID RESOURCEPOLICIES Table on page 10-82 Governing information *In addition,
Metadata Tables VALIDATEROUTINE: Schema SYSTEM_SQLJ_SCHEMA For detailed descriptions of histogram tables, see User Metadata Tables (UMD): Histogram Tables on page 10-70. VALIDATEROUTINE: Schema SYSTEM_SQLJ_SCHEMA This schema contains only the stored procedure VALIDATEROUTINE, which is for internal use.
System Schema Tables Metadata Tables System Schema Tables ALL_UIDS Table ALL_UIDS is a metadata table in NONSTOP_SQLMX_nodename.
CATSYS Table Metadata Tables CATSYS Table CATSYS is a metadata table in NONSTOP_SQLMX_nodename.
SCHEMATA Table Metadata Tables SCHEMATA Table SCHEMATA is a metadata table in NONSTOP_SQLMX_nodename.SYSTEM_SCHEMA that lists all schemas that have definitions on the node.
Definition Schema Tables Metadata Tables Definition Schema Tables ACCESS_PATHS Table ACCESS_PATHS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes physical instances of data in the catalog. (A physical instance of data is a simple table, an index, or a partition of a table or index.
ACCESS_PATH_COLS Table Metadata Tables Column Name Data Type Description 15 LOCK_LENGTH INT Reserved for future use 16 AUDITED CHAR(2) Y if this path is audited N if not 17 AUDIT_COMPRESS CHAR(2) Y if audit is compressed N if not 18 CLEAR_ON_PURGE CHAR(2) Y if deleted records are cleared N if not 19 BUFFERED CHAR(2) Reserved for future use 20 RECORD_PACKED CHAR(2) Reserved for future use 21 DATA_COMPRESSED CHAR(2) Reserved for future use 22 INDEX_COMPRESSED CHAR(2) Reserved for f
CK_COL_USAGE Table Metadata Tables CK_COL_USAGE Table CK_COL_USAGE is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that lists columns referenced by search conditions of check constraints in the catalog.
COLS Table Metadata Tables Column Name Data Type Description 5 COLUMN_NAME CHAR(128) Column name 6 COLUMN_SIZE LARGEINT Data bytes in column 7 SQL_DATA_TYPE CHAR(18) One of these SQL data types: CHARACTER DATE DATETIME SIGNED DECIMAL UNSIGNED DECIMAL DOUBLE FLOAT SIGNED INTEGER INTERVAL UNSIGNED BP INT UNSIGNED INTEGER SIGNED LARGEINT SIGNED NUMERIC UNSIGNED NUMERIC REAL SIGNED SMALLINT UNSIGNED SMALLINT TIME TIMESTAMP VARCHAR LONG VARCHAR 8 CHARACTER_SET CHAR(40) Character set 9 ENCODING
COLS Table Metadata Tables Column Name Data Type Description 11 FS_DATA_TYPE INT File system data type.
COLS Table Metadata Tables Column Name Data Type Description 17 DEFAULT_CLASS CHAR(2) Default defined by: Blank No default CD Current default ND Null default UD User default UF User defined function default If CD, the value of the column depends on its data type: DATE Current date TIME Current time TIMESTAMP Current timestamp 18 LOGGABLE CHAR(2) Reserved for future use 19 DATETIME_START_ FIELD INT First field if type datetime or INTERVAL: 1 if year 2 if month 3 if day 4 if hour 5 if minute 6 if
COL_PRIVILEGES Table Metadata Tables COL_PRIVILEGES Table COL_PRIVILEGES is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores grant information for columns in the catalog: Column Name Data Type Description *1 TABLE_UID LARGEINT UID of table *2 COLUMN_NUMBER INT Position within table (first column is 0) *3 GRANTOR INT Security ID of grantor (or of owner if grantor is super ID acting for owner) *4 GRANTOR_TYPE CHAR(2) S if system grant U if user grant *5 GRANTEE INT If GRANTE
DDL_LOCKS Table Metadata Tables DDL_LOCKS Table DDL_LOCKS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that is used for control locking of the base table so that utility operations in progress are protected against conflicting DDL operations: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of lock 2 BASE_OBJECT_UID LARGEINT UID of locked object 3 TIME_LOCK_REQUESTED LARGEINT Lock creation time 4 TIME_LOCK_ALTERED LARGEINT Time when the lock was last altered 5 OPERATI
MP_PARTITIONS Table Metadata Tables MP_PARTITIONS Table MP_PARTITIONS is a metadata table in DEFINITION_SCHEMA that stores partition names of SQL/MP tables that have SQL/MX aliases: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of table; link to OBJECTS 2 MPPARTITION_NAME CHAR(36) Name of NonStop SQL/MP partition system.volume.subvolume.
PARTITIONS Table Metadata Tables Column Name Data Type Description 6 CREATE_TIME LARGEINT Julian timestamp of creation time 7 REDEF_TIME LARGEINT Julian timestamp of redefinition time 8 CACHE_TIME LARGEINT Julian timestamp of cache time 9 OBJECT_FEATURE_VERSION INT Version of object 10 VALID_DEF CHAR(2) Y if definition valid N if not 11 OBJECT_SECURITY_CLASS CHAR(2) UM User metadata table UT User-defined table SM System metadata table 12 OBJECT_OWNER INT The integer representation o
REF_CONSTRAINTS Table Metadata Tables Column Name Data Type Description 12 EOF LARGEINT End of file indication at last UPDATE STATISTICS 13 PARTITION_STATUS CHAR(2) Status defined by: AV Available UO Unavailable, offline UC Unavailable, corrupt UD Unavailable, dropped UR Unavailable, re-created 14 DDL_IN_PROGRESS CHAR(2) Reserved for future use 15 FIRST_KEY VARCHAR(3000) User-specified first key in normalized form; otherwise, zero-length. If hash partitioned, a logical partition number.
REPLICAS Table Metadata Tables Column Name Data Type Description 7 DELETE_RULE CHAR(2) RE NA SD SN RESTRICT NO ACTION SET DEFAULT SET NULL * Indicates primary key REPLICAS Table REPLICAS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores the locations of views in the catalog.
ROUTINES Table Metadata Tables ROUTINES Table ROUTINES is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains SPJ-level attributes, one row for each stored procedure in Java (SPJ) created in this catalog. VARCHAR columns store letters as is (not converted to uppercase).
TBL_CONSTRAINTS Table Metadata Tables TBL_CONSTRAINTS Table TBL_CONSTRAINTS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains one entry for each unique, primary key, foreign, or check constraint on a table in the catalog: Column Name Data Type Description *1 CONSTRAINT_UID LARGEINT UID of constraint *2 CONSTRAINT_TYPE CHAR(2) Constraint type: C Check F Foreign P Primary key U Unique *3 TABLE_UID LARGEINT UID of table 4 DISABLED CHAR(2) Y if not enforced N if enforced 5 D
TEXT Table Metadata Tables Column Name Data Type Description *6 PRIVILEGE_TYPE CHAR(2) Privilege type: S SELECT I INSERT D DELETE U UPDATE R REFERENCES 7 IS_GRANTABLE CHAR(2) Y if granted with grant option N if not * Indicates primary key Grant information for individual columns is stored separately in the COL_PRIVILEGES table. All character columns store letters in uppercase except for GRANTOR and GRANTEE.
TRIGGERS_CAT_USAGE Table Metadata Tables Column Name Data Type Description 4 SUBJECT_UID LARGEINT UID of the table on which the trigger is defined 5 ACTIVATION_TIME CHAR(2) Activation time: B Before A After 6 OPERATION CHAR(2) Operation that fires the trigger: I INSERT D DELETE U UPDATE 7 GRANULARITY CHAR(2) Granularity: R Row S Statement 8 COLUMNS_IMPLICIT CHAR(2) Relevant only for UPDATE trigger: Y Yes N No 9 ENABLED CHAR(2) Current status of trigger: Y if enabled N if not 10 TRIGGE
TRIGGER_USED Table Metadata Tables TRIGGER_USED Table TRIGGER_USED is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains Information on how triggers use objects. It serves three purposes: • • • Given a table, return all the triggers of a certain operation that are defined on that table. Those triggers might be in other catalogs. For every local object (table or view), check if a trigger anywhere is using it.
VWS Table Metadata Tables VWS Table VWS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that lists views in the catalog: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of view 2 CHECK_OPTION CHAR(2) C if CASCADE L if LOCAL N if None 3 IS_UPDATABLE CHAR(2) Y if updating allowed N if not 4 IS_INSERTABLE CHAR(2) Y if inserting allowed N if not * Indicates primary key Text for views is stored separately in the TEXT table on the master node for the catalog.
VW_COL_TBL_COLS Table Metadata Tables VW_COL_TBL_COLS Table VW_COL_TBL_COLS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that records the base table columns referenced by each column of a view in the catalog: Column Name Data Type Description *1 VIEW_UID LARGEINT UID of referencing view *2 VIEW_COL_NUM INT Column number of referencing column (first is 0) *3 UNDERLYING_CAT_UID LARGEINT UID of catalog of referenced table *4 UNDERLYING_SCH_UID LARGEINT UID of schema of referenced tab
System Defaults Table Metadata Tables System Defaults Table SYSTEM_DEFAULTS Table Overriding System-Defined Default Settings Default Attributes Examples of SYSTEM_DEFAULTS Table SYSTEM_DEFAULTS is a metadata table in the SYSTEM_DEFAULTS_SCHEMA of catalog NONSTOP_SQLMX_nodename. that you use to store system-level default settings that override some of the system-defined default settings.
Overriding System-Defined Default Settings Metadata Tables For some attributes, you can override a default setting by specifying an option within a statement or command. For example, you can set the transaction isolation level with the SELECT statement. If you do not enter an option when entering a command or do not provide some attribute associated with the execution of queries, NonStop SQL/MX uses a default setting.
Default Attributes Metadata Tables Default Attributes Default attributes control these activities: Constraint Droppable Options Data Types Function Control Histograms Isolation Level Locking Module Management National Character Set Nonaudited Tables Object Naming Partition Management Query Optimization and Performance Query Plan Caching Referential Action Row Maintenance Scratch Disk Management Sequence Functions Statement Atomicity Statement Recompilation Stored Procedures in Java Stream Access Table Man
Default Attributes Metadata Tables Attribute Description Category CATALOG Default ANSI catalog name. Object Naming on page 10-48 CROSS_PRODUCT_CONTROL Determines whether plans are eliminated that contain unnecessary cross-products. Query Optimization and Performance on page 10-54 DATA_FLOW_OPTIMIZATION Controls whether query plans are considered that have high data flow rates.
Default Attributes Metadata Tables Attribute Description Category GENERATE_EXPLAIN Controls whether EXPLAIN output is generated. Query Optimization and Performance on page 10-54 GEN_EIDR_BUFFER_SIZE Buffer size for partition access. Query Optimization and Performance on page 10-54 GEN_MAX_NUM_PART_ DISK_ENTRIES Controls the size of a partition list prepared by the compiler and used by the executor.
Default Attributes Metadata Tables Attribute Description Category HIST_ROWCOUNT_ REQUIRING_STATS Minimum row count that determines when warnings are issued to update statistics. Histograms on page 10-41 HIST_SAME_TABLE_PRED_ REDUCTION Controls overlap amount in predicate selectivity when multicolumn predicates are used. Histograms on page 10-41 HIST_SCRATCH_VOL Sets the physical volume for UPDATE STATISTICS temporary tables.
Default Attributes Metadata Tables Attribute Description Category MAX_ROWS_LOCKED_ FOR_STABLE_ACCESS Maximum number of rows that are locked in STABLE ACCESS mode. Locking on page 10-46 MDAM_SCAN_METHOD Enables or disables the MultiDimensional Access Method. Query Optimization and Performance on page 10-54 MIN_MAX_OPTIMIZATION Enables or disables MINMAX optimization. Query Optimization and Performance on page 10-54 MP_SUBVOLUME Default NonStop operating system Guardian subvolume.
Default Attributes Metadata Tables Attribute Description Category OPTS_PUSH_DOWN_DAM Controls whether NonStop SQL/MX considers pushdown plans. Query Optimization and Performance on page 10-54 PARALLEL_NUM_ESPS Maximum number of parallel ESPs that work on a particular type of operator, like a join. Query Optimization and Performance on page 10-54 PM_OFFLINE_ TRANSACTION_ GRANULARITY Number of rows to be copied in an offline MODIFY transaction.
Default Attributes Metadata Tables Attribute Description Category QUERY_CACHE_REQUIRED_ PREFIX_KEYS Determines how many and which columns of a composite primary or partition key are required for an equality key predicate to be considered cacheable. Query Plan Caching on page 10-59 QUERY_CACHE_STATEMENT_ PINNING Controls the pinning and unpinning of query cache entries.
Default Attributes Metadata Tables Attribute Description Category SCRATCH_FREESPACE_ THRESHOLD_PERCENT Amount of scratch space left on disks as a threshold. Scratch Disk Management on page 10-62 SIMILARITY_CHECK Determines whether similarity checks are made to either keep or recompile an access plan. Statement Recompilation on page 10-64 SORT_MAX_HEAP_SIZE_MB Allocates a default value to the heap memory size for operations involving the sort operator.
Constraint Droppable Options Metadata Tables Attribute Description Category UPD_SAVEPOINT_ON_ERROR Controls whether DP2 savepoints should be used and if the transaction should be aborted in case of an error. Statement Atomicity on page 10-64 VARCHAR_PARAM_ DEFAULT_SIZE Controls the allowable length of a LIKE predicate. Table Management on page 10-67 ZIG_ZAG_TREES Enables or disables the optimizer to consider zigzag trees in addition to linear trees.
Data Types Metadata Tables Data Types This attribute controls whether the output of dynamic SELECT statements and dynamic parameters that are FLOAT data types should be treated as Tandem FLOAT format or IEEE FLOAT format: Attribute Setting FLOATTYPE Set to IEEE or TANDEM. The default is TANDEM. Function Control This attribute controls how NonStop SQL/MX handles functions: Attribute Setting PRESERVE_MIN_SCALE An arithmetic operation on numeric columns might give a wrong result.
Histograms Metadata Tables Attribute Setting CACHE_HISTOGRAMS_ REFRESH_INTERVAL Controls the time interval, in seconds, at which histograms in the histogram cache are refreshed. This is the maximum time a histogram in the cache can be out of date. Allowable values: 0 through 4294967040. The default value is 3600 seconds. DYNAMIC_HISTOGRAM_ COMPRESSION Set to ON or OFF. When set to ON, NonStop SQL/MX reduces compile time by reducing the number of histogram intervals.
Histograms Metadata Tables Attribute Setting HIST_NO_STATS_REFRESH_ INTERVAL Specifies the time interval, in seconds, at which default statistics are refreshed. Default statistics are compiler generated statistics for tables for which no UPDATE STATISTICS has been performed. You can change the value of HIST_NO_STATS_REFRESH_INTERVAL if you do frequent inserts and deletes on such tables, for example, a temporary table.
Histograms Metadata Tables Attribute Setting HIST_ROWCOUNT_ REQUIRING_STATS Row count that determines when SQLCODE 6007/6008 warnings are issued, which mean statistics have not been updated for all table columns in a query. Only columns from tables that have more rows than this count force these warnings. To avoid these warnings, set this value to a very large number, provided no tables exist with that number of rows in the database.
Isolation Level Metadata Tables Attribute Setting HIST_SECURITY_WARNINGS Controls whether MXCMP displays a warning if the user does not have access permissions to statistics tables and the user table's estimated rowcount is greater than the HIST_ROWCOUNT_REQUIRING_STATS value. If set to ON, the compiler reports this warning. If set to OFF, the compiler does not report a warning. The default is ON. For more information about histogram statistics, see the SQL/MX Query Guide.
Locking Metadata Tables Locking These attributes determine how NonStop SQL/MX locks objects: Attribute Setting MAX_ROWS_LOCKED_ FOR_STABLE_ACCESS The maximum number of rows locked by DP2 in STABLE ACCESS mode before the buffer is returned to the file system. The number of rows which are actually locked depends on this number and the size of the buffer. To increase concurrency, you can decrease this value so that more messages are used to return the same amount of data. The default value is 1.
Module Management Metadata Tables Module Management This attribute determines where globally placed modules are generated: Attribute Setting MXCMP_PLACES_LOCAL_ MODULES Set to ON or OFF. If OFF, NonStop SQL/MX generates global modules in the USERMODULES directory. If ON and you do not specify mxcmp -g moduleLocal=OSS-dir on the command line, compiled modules are placed in the current OSS directory.
Nonaudited Tables Metadata Tables Nonaudited Tables This attribute enables NonStop SQL/MX to handle inserts, updates, and deletes against nonaudited SQL/MP tables: Caution. If the IUD_NONAUDITED_INDEX_MAINT is set to ON, NonStop SQL/MX allows DML operations on nonaudited tables without error or warning. Before you set this attribute, see the SQL/MX Comparison Guide for SQL/MP Users to understand index maintenance of nonaudited tables.
Object Naming Metadata Tables Attribute Setting SCHEMA Default schema (without catalog) name, used if no second part is specified in a three-part logical name. The schema name can be qualified by a catalog name, in which case this catalog name supersedes any settings for the CATALOG attribute. If not set, the user name of the current user becomes the default second part of the logical name. In SQL/MX Release 2.0, the three-part name is an ANSI name.
Object Naming Metadata Tables 2. For SQL statements issued through MXCI and embedded SQL, the compiler uses the SYSTEM_DEFAULTS table entry (if it exists). 3. For SQL statements issued through MXCI and embedded SQL, if these values are not set, the system-defined default setting for the NAMETYPE attribute is ANSI. Attribute Value ANSI for Logical Names If the NAMETYPE attribute is ANSI or is not specified, object names are determined according to rules applied in this order: 1.
Partition Management Metadata Tables the current physical location. SET MPLOC changes the values for default attributes MP_SYSTEM, MP_VOLUME and MP_SUBVOLUME. Use the SET MPLOC statement in MXCI. For embedded SQL, the SET MPLOC statement affects only dynamic embedded SQL. The DECLARE MPLOC statement affects only static embedded SQL.
Partition Management Metadata Tables Attribute Setting GEN_MAX_NUM_PART_ DISK_ENTRIES When a statically compiled statement references partitioned objects, this default is used to control the size of a partition list prepared by the compiler and is used by the executor when it first opens the object, to support node and disk autonomy.
Partition Management Metadata Tables Attribute Setting POS_LOCATIONS Physical locations of nonprimary partitions to be automatically created, specified as [\node.]$volume. You can specify multiple locations separated by commas. If you enter a space (“ “), NonStop SQL/MX chooses the locations of the second through last partitions at random. NonStop SQL/MX does not place partitions on these types of disks: audit trail volumes, nonaudited disks, optical disks, phantom disks, or SMS virtual disks.
Query Optimization and Performance Metadata Tables Query Optimization and Performance These attributes enable NonStop SQL/MX to optimize query execution: Attribute Setting ATTEMPT_ASYNCHRONOUS_ ACCESS Set to ON or OFF. When set to ON, the optimizer generates plans that access multiple partitions asynchronously (that is, at the same time). With asynchronous access, the optimizer does not use ESPs to access the partitions in parallel.
Query Optimization and Performance Metadata Tables Attribute Setting DP2_CACHE_4096_BLOCKS Specifies the number of 4 KB blocks allocated for the disk cache. This value is used by the compiler to determine the cost of a table/index scan operator. You should set the value of this attribute to the average value of 4 KB block disk cache settings for all volumes in the system. The current value for the number of 4 KB blocks allocated to a disk cache can be determined by using SCF.
Query Optimization and Performance Metadata Tables Attribute Setting GEN_PA_BUFFER_SIZE Combined with GEN_EIDR_BUFFER_SIZE, determines the buffer size for partition access operations. The two default settings must be equal. For OLTP applications, reducing buffer size to 4 KB can improve performance by reducing memory usage. For DSS applications, use the default. For additional information about this setting, see the SQL/MX Query Guide. The default buffer size is 31 KB.
Query Optimization and Performance Metadata Tables Attribute Setting MSCF_ET_REMOTE_MSG_ TRANSFER The value of this default is used to factor in the cost of transferring messages to and from a remote node. It reflects the bandwidth of the physical communication link. You should set it to a value greater than the cost factor of transferring messages to or from a local node, which is 0.000046. Allowable values: 1.17549e-038 through 3.40282e+38. The default value is 0.00005.
Query Optimization and Performance Metadata Tables Attribute Setting PARALLEL_NUM_ESPS Set to the keyword SYSTEM or to the maximum number of ESPs (an unsigned positive integer) that should be used for a particular operator. If set to SYSTEM, NonStop SQL/MX calculates the value. If set to a number, the value must be less than the number of CPUs in the cluster. For additional information about this setting, see the SQL/MX Query Guide. Allowable values: 1 through 4294967040.
Query Plan Caching Metadata Tables Attribute Setting SORT_MAX_HEAP_SIZE_MB The default value is used for allocating the heap memory size for operations involving the sort operator. The minimum and maximum values are 0 and 1024 respectively. The default value is 20. UPD_ORDERED Set to ON or OFF. If ON, the optimizer generates and considers plans where the rows must be inserted, updated, or deleted in clustering key order.
Query Plan Caching Metadata Tables Attribute Setting QUERY_CACHE_REQUIRED_ PREFIX_KEYS Set to a value between 0 and 255. Specifies how many and which columns of a composite primary or partition key are required for an equality predicate to be considered cacheable. If the attribute is set to a value greater than the number of columns in a composite key, all columns of the key are required.
Referential Action Metadata Tables Referential Action This attribute determines how NonStop SQL/MX handles referential action in ALTER TABLE and CREATE TABLE statements: Attribute Setting REF_CONSTRAINT_NO_ ACTION_LIKE_RESTRICT Controls how NO ACTION referential action is treated. Set to OFF, SYSTEM, or ON. OFF means that SQL issues error 1301 SYSTEM means that SQL issues warning 1302 saying that it behaves like RESTRICT. ON means that NO ACTION behaves like RESTRICT, without warning or errors.
Scratch Disk Management Metadata Tables Scratch Disk Management These attributes determine how NonStop SQL/MX manages scratch disks for the sort operation: Attribute Setting SCRATCH_DISKS Set to a list of scratch disk volumes, where each item in the list has the form [\node.]$volume, and the items in the list are separated by a comma (,). Use this default to restrict scratch disks to the volumes specified.
Sequence Functions Metadata Tables The value in parentheses indicates the weighting of that criterion. The rank is the ordinal rank of that disk among all the disks in the pool based on the criterion. The inverted rank is the inverted ordinal rank. In the case of the biggest available fragment criterion, if the pool contains 20 disks, the disk with the biggest available fragment would have an inverted rank of 20.
Statement Atomicity Metadata Tables Statement Atomicity These attributes affect NonStop SQL/MX’s ability to undo the effects of an insert, update, or delete operation, when an error occurs during the operation, without having to abort the entire transaction: Attribute Setting DOOM_USERTRANSACTION Controls whether NonStop SQL/MX dooms a transaction when it encounters an unrecoverable error and the transaction cannot be rolled back to a savepoint.
Statement Recompilation Metadata Tables Attribute Setting INTERACTIVE_ACCESS Set to ON or OFF. If set to ON, the compiler selects the most appropriate index-based access plan. If OFF, the compiler follows normal behavior and does not emphasize index-based access plans. The default is OFF. RECOMPILATION_ WARNINGS Set to ON or OFF. If set to ON, when a statement is automatically recompiled in an application (because of various factors), NonStop SQL/MX returns a warning message.
Stored Procedures in Java Metadata Tables Stored Procedures in Java This attribute specifies the Java Virtual Machine (JVM) startup options for the Java environment of a stored procedure in Java (SPJ): Attribute Setting UDR_JAVA_OPTIONS Set the attribute value to one or more Java options within single quotes (for example, 'java-option1 java-option2'). Each Java option can be any Java option supported by the HP NonStop Server for Java.
Table Management Metadata Tables Attribute Setting STREAM_TIMEOUT The time in hundredths of seconds for a cursor fetch operation using stream access to wait for more rows before timing out. Setting this default directs NonStop SQL/MX to not wait for more rows beyond the specified time but to return with error code 8006. This default is valid for compile-time stream timeout. For run-time stream timeout, see SET TABLE TIMEOUT Statement on page 2-214.
Trigger Management Metadata Tables Attribute Setting If the 3-part ANSI name exceeds the maximum OSS file name length of 248, it is truncated to 248 characters. Despite similarities in the resulting file names because of character replacement or file name truncation, the files are always distinguishable by the trailing timestamp portion of the name and the contents of the file, which always indicates the full ANSI name of the table. NonStop SQL/MX does not remove saved DDL files.
Examples of SYSTEM_DEFAULTS Table Metadata Tables Control query default TEMPORARY_TABLE_HASH_PARTITIONS '$data01,$data02:$data03'; If you specify more than one volume, the temporary table is hash partitioned over all those partitions. Range partitioning is not supported. If no system default is specified, NonStop SQL/MX uses the default location of the creator of the first trigger. If the default is changed, the change affects temporary tables created after the change.
User Metadata Tables (UMD): Histogram Tables Metadata Tables User Metadata Tables (UMD): Histogram Tables HISTOGRAMS Table HISTOGRAM_INTERVALS Table HISTOGRM Table HISTINTS Table Examples of Histogram Tables A histogram is a representation of a relationship in which each value of some dependent variable corresponds to a range of values of the associated independent variable or variables. For example, a histogram might be a chart showing the number of people in New York in various age ranges.
Creating Histogram Tables Metadata Tables reside in the same HISTOGRAMS and HISTOGRAM_INTERVAL or HISTINTS and HISTOGRM tables. You can specify the number of intervals for the table statistics in the UPDATE STATISTICS statement. If you do not specify the number of intervals, NonStop SQL/MX provides a default number based on the table size and other factors. The histogram tables are not automatically updated when you alter a table for which statistics are stored.
HISTOGRAMS Table Metadata Tables SQL/MX Objects SQL/MP Objects File name: catalog.schema.SQLMX _tablename File name: \node.$vol.ZZMXTEMP.tablename Size limits: Because files are always format 2, the temporary table is limited to 1 TB or the amount of available space on each volume. Size limits: File format is determined by format of the base table’s primary partition. If it is format 1, the temporary table is limited to 2 GB.
HISTOGRAM_INTERVALS Table Metadata Tables HISTOGRAM_INTERVALS Table The SQL/MX HISTOGRAM_INTERVALS table describes for each interval, the number of rows and number of unique rows in the interval and the value of the upper boundary for the interval: Column Name Data Type Description *1 TABLE_UID LARGEINT The UID of the table for which this histogram is generated. *2 HISTOGRAM_ID INT UNSIGNED System-generated ID for the histogram. Each HISTOGRAM_ID has a corresponding ID in the HISTOGRAMS table.
HISTOGRM Table Metadata Tables HISTOGRM Table The SQL/MP HISTOGRM table is a user table registered in the catalog of the primary partition of the table specified in the UPDATE STATISTICS statement that created the histogram tables. It describes columns, interval count, total number of rows and unique rows, and the low and high values of column distribution for the table for which the histogram is created. Caution.
HISTINTS Table Metadata Tables HISTINTS Table The SQL/MP table HISTINTS table is a user table registered in the catalog of the primary partition of the table specified in the UPDATE STATISTICS statement that created the histogram tables. It describes, for each interval of the table for which the histogram is created, the number of rows and unique rows in the interval and the value of the interval upper boundary. Caution.
Examples of Histogram Tables Metadata Tables Examples of Histogram Tables • Update the histogram statistics on the EMPNUM column for the EMPLOYEE table: UPDATE STATISTICS FOR TABLE persnl.employee ON (empnum); --- SQL operation complete. • Use the SELECT statement to retrieve the statistics in the SQL/MX HISTOGRAMS table generated by the UPDATE STATISTICS statement, based on table and column names: SELECT O.OBJECT_NAME TABLE_UID, C.COLUMN_NAME, H.HISTOGRAM_ID, H.INTERVAL_COUNT, H.ROWCOUNT, H.
Examples of Histogram Tables Metadata Tables • Use the SELECT statement to retrieve the statistics in the HISTINTS table generated by the preceding UPDATE STATISTICS statement (the columns are arranged horizontally): SELECT * FROM HISTINTS; TABLE_UID INTERVAL_ROWCOUNT --------------------------------------211813264440965573 0 211813264440965573 4 211813264440965573 4 211813264440965573 3 211813264440965573 3 211813264440965573 3 211813264440965573 3 211813264440965573 3 211813264440965573 3 211813264440
Metadata Tables Examples of Histogram Tables The data in the EMPLOYEE table is not distributed evenly with respect to the primary key because most of the rows in this table are in the EMPNUM equal to 200 range. The SQL/MX optimizer uses the histogram statistics, which divide the rows into intervals with approximately the same number of rows, to devise plans for efficient data access.
MXCS Metadata Tables Metadata Tables MXCS Metadata Tables ASSOC2DS Table ASSOC2DS is a metadata table in NONSTOP_SQL_nodename.MXCS_SCHEMA that associates the MXCS service to a data source: Column Name Data Type Description *1 ASSOC_ID INT Unique identifier for association service description. *2 DS_ID INT Unique identifier for datasource description. 3 AUTOMATION SMALLINT 0 data source is started manually. 1 data source is started automatically.
DATASOURCES Table Metadata Tables DATASOURCES Table DATASOURCES is a metadata table in NONSTOP_SQL_nodename.MXCS_SCHEMA that contains data source information: Column Name Data Type Description *1 DS_ID INT Unique identifier for this datasource description. 2 MAX_SRVR_CNT INT Maximum number of server instances that must be kept available for association requests. 3 AVAIL_SRVR_CNT INT Minimum number of server instances that must be kept available for association requests.
ENVIRONMENTVALUES Table Metadata Tables ENVIRONMENTVALUES Table ENVIRONMENTVALUES is a metadata table in NONSTOP_SQL_nodename.
RESOURCEPOLICIES Table Metadata Tables RESOURCEPOLICIES Table RESOURCEPOLICIES is a metadata table in NONSTOP_SQL_nodename.MXCS_SCHEMA that contains governing information.
A Quick Reference This appendix provides a quick, alphabetic reference to commands, statements, and utilities. For other topics, see the Index.
D Quick Reference CREATE VIEW Statement on page 2-104 D DEALLOCATE DESCRIPTOR Statement on page 3-16 DEALLOCATE PREPARE Statement on page 3-18 DECLARE CATALOG Declaration on page 3-21 DECLARE CURSOR Declaration on page 3-22 DECLARE MPLOC Declaration on page 3-28 DECLARE NAMETYPE Declaration on page 3-31 DECLARE SCHEMA Declaration on page 3-32 DELETE DEFINE Command on page 4-8 DELETE Statement on page 2-109 DESCRIBE Statement on page 3-33 DISPLAY STATISTICS Command on page 4-22 DISPLAY_EXPLAIN Command on
F Quick Reference EXEC SQL Directive on page 3-37 EXECUTE IMMEDIATE Statement on page 3-38 EXECUTE Statement on page 2-131 EXIT Command on page 4-28 mxexportddl Utility on page 5-63 F FC Command on page 4-29 FETCH Statement on page 3-39 FIXUP Operation on page 5-11 G GET DESCRIPTOR Statement on page 3-45 GET DIAGNOSTICS Statement on page 3-54 GOAWAY Operation on page 5-16 GRANT Statement on page 2-138 GRANT EXECUTE Statement on page 2-141 H HISTORY Command on page 4-31 I IF Statement on page 3-60 impo
M Quick Reference M migrate Utility on page 5-42 MODIFY Utility on page 5-47 MODULE Directive on page 3-69 MXCI Command on page 4-40 MXGNAMES Utility on page 5-65 mxtool Utility on page 5-72 O OBEY Command on page 4-41 OPEN Statement on page 3-71 P POPULATE INDEX Utility on page 5-73 PREPARE Statement on page 2-159 PURGEDATA Utility on page 5-76 PURGEDATA Utility on page 5-76 R RECOVER Utility on page 5-80 REGISTER CATALOG Statement on page 2-164 REPEAT Command on page 4-43 RESET PARAM Command on page
T Quick Reference SET MPLOC Statement on page 2-210 SET NAMETYPE Statement on page 2-211 SET PARAM Command on page 4-47 SET SCHEMA Statement on page 2-212 SET SHOWSHAPE Command on page 4-50 SET STATISTICS Command on page 4-53 SET TABLE TIMEOUT Statement on page 2-214 SET TRANSACTION Statement on page 2-218 SET WARNINGS Command on page 4-55 SH Command on page 4-56 SHOW PARAM Command on page 4-57 SHOW PREPARED Command on page 4-58 SHOW SESSION Command on page 4-59 SHOWCONTROL Command on page 4-61 SHOWDDL Co
W Quick Reference HP NonStop SQL/MX Reference Manual—540440-003 A- 6
B Reserved Words The words listed in this appendix are reserved for use by NonStop SQL/MX. To prevent syntax errors, avoid using these words as identifiers in NonStop SQL/MP and in NonStop SQL/MX. In NonStop SQL/MX, if a Guardian name contains a reserved word, you must enclose the reserved word in double quotes (") to access that column or object. See Using SQL/MX Reserved Words in SQL/MP Names on page 6-53. In these lists, an asterisk (*) indicates reserved words that are SQL/MX extensions.
Reserved SQL/MX and SQL/MP Identifiers Reserved Words Table B-1.
Reserved SQL/MX and SQL/MP Identifiers Reserved Words Table B-1.
Reserved SQL/MX and SQL/MP Identifiers Reserved Words Table B-1.
SQL/MP Identifiers to Avoid Reserved Words SQL/MP Identifiers to Avoid Words in this list are not reserved in NonStop SQL/MP; however, NonStop SQL/MX considers these words to be reserved in SQL/MX text and in SQL/MP stored text. To prevent problems accessing or manipulating data, avoid using these words as identifiers for SQL/MP objects.
SQL/MP Identifiers to Avoid Reserved Words HP NonStop SQL/MX Reference Manual—540440-003 B- 6
C Limits This appendix lists limits for various parts of NonStop SQL/MX: Catalog names 128 characters in length. Column names 128 characters in length. Constraints The maximum combined length of the columns for a REFERENCE, PRIMARY KEY, or UNIQUE constraint is 255 bytes. DROP SCHEMA CASCADE transactions You might need to increase the number of locks per volume, or DROP SCHEMA CASCADE can fail. EXTENTS Limited only by size of disk.
Limits Referential constraints A table can have an unlimited number of referential constraints, and you can specify the same foreign key in more than one referential constraint, but you must define each referential constraint separately. Schema names 128 characters in length. Tables ANSI names are three-part name of the form catalog.schema.object, where each part can be up to 128 characters long. The maximum length of a row is 4040 bytes, but not all of that is available.
D Sample Database To help you become familiar with its features, NonStop SQL/MX includes a sample database, which you can access by using SQL/MX statements. The sample database is used as the basis for many examples in this manual and other SQL/MX manuals. The DDL statements in the sample database use SQL/MX tables. If you are using SQL/MP tables, you need to use the SQL/MX Release 1.8 sample database, which uses SQL/MP tables. Note. The SQL/MX Release 2.x sample database uses SQL/MX format tables.
Sample Database Entity-Relationship Diagram Sample Database Sample Database Entity-Relationship Diagram Figure D-1 shows the names of columns and tables and the relationships between the tables in the sample database. Figure D-1.
DDL Statements for the Sample Database Sample Database DDL Statements for the Sample Database The data definition language statements that create sample database objects are listed next. For more information on the setmxdb script and how to install the sample database, see the SQL/MX Quick Start. EMPLOYEE Table This statement creates the EMPLOYEE table: CREATE TABLE samdbcat.persnl.
DEPT Table Sample Database deptnum ); This statement creates the EMPLIST view: CREATE VIEW emplist AS SELECT empnum , first_name , last_name , deptnum , jobcode FROM employee; DEPT Table This statement creates the DEPT table: CREATE TABLE samdbcat.persnl.
JOB Table Sample Database CHECK (deptnum IN ( 1000 ,1500 ,2000 ,2500 ,3000 ,3100 ,3200 ,3300 ,3500 ,4000 ,4100 ,9000 )); This statement creates the XDEPTMGR index: CREATE INDEX xdeptmgr ON dept ( manager ); This statement creates the XDEPTRPT index: CREATE INDEX xdeptrpt ON dept ( rptdept ); This statement creates the MGRLIST view: CREATE VIEW mgrlist ( first_name ,last_name ,department ) AS SELECT first_name ,last_name ,deptname FROM dept ,employee WHERE dept.manager = employee.
PROJECT Table Sample Database ,jobdesc ,PRIMARY KEY ); VARCHAR (18) DEFAULT 0 NOT NULL NOT DROPPABLE HEADING 'Job Description' (jobcode) NOT DROPPABLE PROJECT Table This statement creates the PROJECT table: CREATE TABLE samdbcat.persnl.
ORDERS Table Sample Database ,city ,state ,postcode ,credit ,PRIMARY KEY ); CHARACTER (14) NO DEFAULT NOT NULL NOT DROPPABLE HEADING 'City' CHARACTER (12) DEFAULT 0 NOT NULL NOT DROPPABLE HEADING 'State' CHARACTER (10) NO DEFAULT NOT NULL NOT DROPPABLE HEADING 'Post Code' CHARACTER (2) DEFAULT 'C1' NOT NULL NOT DROPPABLE HEADING 'CR' (custnum) NOT DROPPABLE This statement creates the XCUSTNAM index: CREATE INDEX xcustnam ON customer ( custname ); This statement creates the CUSTLIST view: CREATE VI
DATE_CONSTRNT Constraint Sample Database ,deliv_date ,salesrep ,custnum ,PRIMARY KEY ); DATE DEFAULT DATE '2002-08-01' NOT NULL NOT DROPPABLE HEADING 'Deliv/Date' NUMERIC (4) UNSIGNED DEFAULT 0 NOT NULL NOT DROPPABLE HEADING 'Sales/Rep' NUMERIC (4) UNSIGNED NO DEFAULT NOT NULL NOT DROPPABLE HEADING 'Cust/Num' (ordernum) NOT DROPPABLE DATE_CONSTRNT Constraint This statement creates the DATE_CONSTRNT constraint: ALTER TABLE orders ADD CONSTRAINT date_constrnt CHECK (deliv_date >= order_date); This sta
ODETAIL Table Sample Database ODETAIL Table This statement creates the ODETAIL table: CREATE TABLE samdbcat.sales.
SUPPLIER Table Sample Database This statement creates the XPARTDES index: CREATE INDEX xpartdes ON parts ( partdesc ); SUPPLIER Table This statement creates the SUPPLIER table: CREATE TABLE samdbcat.invent.
PARTSUPP Table Sample Database PARTSUPP Table This statement creates the PARTSUPP table: CREATE TABLE samdbcat.invent.
PARTSUPP Table Sample Database x.partnum = p.partnum AND x.suppnum = s.suppnum; This statement creates the VIEW207N view: CREATE VIEW view207n ( partnumber ,partdescrpt ,suppnumber ,supplrname ,partprice ,qtyreceived ) AS SELECT x.partnum ,p.partdesc ,s.suppnum ,s.suppname ,x.partcost ,x.qty_received FROM samdbcat.invent.supplier s LEFT JOIN samdbcat.invent.partsupp x ON s.suppnum = x.suppnum LEFT JOIN samdbcat.sales.parts p ON x.partnum = p.
PARTLOC Table Sample Database PARTLOC Table When you install the sample database, you can choose to partition the PARTLOC. If you do not specify partitions when you run setmxdb, the unpartitioned PARTLOC table is created: CREATE TABLE samdbcat.invent.
PARTLOC Table Sample Database HP NonStop SQL/MX Reference Manual—540440-003 D -14
E Standard SQL and SQL/MX This appendix describes NonStop SQL/MX conformance to the SQL standards established by the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO).
ISO Standards Standard SQL and SQL/MX ISO Standards These ISO documents govern SQL: • • • • ISO/IEC 9075-1:1999, Information technology—Database languages—SQL—Part 1: Framework (SQL/Framework) ISO/IEC 9075-1:1999/Amd.
SQL/MX Compliance Standard SQL and SQL/MX ID Feature F181 Multiple module support F201 CAST function F471 Scalar subquery values F481 Expanded NULL predicate B012 Embedded C B013 Embedded COBOL This table lists the Core SQL:1999 features for which NonStop SQL/MX offers partial support: ID, Feature Level of Support E071 Basic query expressions NonStop SQL/MX fully supports this subfeature: E071-02 UNION ALL table operator NonStop SQL/MX partially supports these subfeatures: E071-01 UNION [
SQL/MX Compliance Standard SQL and SQL/MX ID, Feature Level of Support NonStop SQL/MX does not support this subfeature: E121-03 Value expressions in ORDER BY clause E141 Basic integrity constraints NonStop SQL/MX fully supports these subfeatures: E141-01 NOT NULL constraints E141-02 UNIQUE constraint of NOT NULL columns E141-03 PRIMARY KEY constraints E141-06 CHECK constraints NonStop SQL/MX partially supports these subfeatures: E141-04 Basic FOREIGN KEY constraint with the NO ACTION default for refere
SQL/MX Compliance Standard SQL and SQL/MX ID, Feature Level of Support NonStop SQL/MX does not support these subfeatures: F051-07 LOCALTIME (equivalent to CAST (CURRENT_TIME AS TIME WITHOUT TIME ZONE)) F051-08 LOCALTIMESTAMP (equivalent to CAST(CURRENT_TIMESTAMP AS TIMESTAMP WITHOUT TIME ZONE)) F081 UNION and EXCEPT in views NonStop SQL/MX supports UNION but not EXCEPT in views F221 Explicit defaults NonStop SQL/MX supports use of DEFAULT in INSERT, but not in UPDATE F261 CASE expressions NonStop S
SQL/MX Extensions to Standard SQL Standard SQL and SQL/MX NonStop SQL/MX does not support these Core SQL:1999 features: ID Feature E153 Updatable queries with subqueries F021 Basic information schema F501 Features and conformance views F812 Basic flagging S011 Distinct data types NonStop SQL/MX supports embedded language. NonStop SQL/MX does not support E182, module language.
Character Set Support Standard SQL and SQL/MX ID Feature T211 Basic trigger capability (except for T211-07 Trigger privilege) T212 Enhanced trigger capability T441 ABS and MOD functions T621 Enhanced numeric functions Character Set Support NonStop SQL/MX supports a limited number of national, international, and vendor-specific encoded character set standards: ISO88591, UCS2, KANJI and KSC5601. Note. KANJI and KSC5601 are valid character sets for SQL/MP tables but not SQL/MX tables.
Character Set Support Standard SQL and SQL/MX HP NonStop SQL/MX Reference Manual—540440-003 E- 8
Index A ABS function examples of 9-10 syntax diagram of 9-10 Access options summary of 1-7 DELETE statement use of 2-111 DML statements use of 1-7 INSERT statement use of 2-145 READ COMMITTED 1-8 READ UNCOMMITTED 1-8 REPEATABLE READ 1-8 SELECT statement use of 2-188 SERIALIZABLE 1-8, 1-10, 1-22 SKIP CONFLICT 1-8 SQL/MP considerations 1-30 STABLE 1-9 UPDATE statement use of 2-230 Access privileges ALL PRIVILEGES 2-138 DELETE 2-138 INSERT 2-138 REFERENCES 2-138 SELECT 2-138 tables 2-138 UPDATE 2-138 views 2-1
A Index ALLOCATE DESCRIPTOR statement (continued) syntax diagram of 3-6 ALLOCATE file attribute 8-2 ALL_UIDS metadata table 10-8 ALTER DEFINE command examples of 4-6 syntax diagram of 4-5 ALTER INDEX statement ALLOCATE within 8-2 authorization and availability requirements 2-8 CLEARONPURGE within 8-5 DEALLOCATE within 8-2 examples of 2-8 file attributes 2-7 MAXEXTENTS within 8-7 syntax diagram of 2-7 ALTER SQLMP ALIAS statement examples of 2-9 syntax diagram of 2-8 ALTER TABLE statement ALLOCATE within 8-
B Index AUDITCOMPRESS file attribute (continued) CREATE TABLE use of 8-3 syntax diagram of 8-3 Audited tables CREATE TABLE considerations 2-88 DELETE considerations 2-113 INSERT considerations 2-152 transaction management 1-15 UPDATE considerations 2-234 Authorization ID 1-5 AUTOMATIC_RECOMPILATION default 10-64 AVG function DISTINCT clause use of 9-14 examples of 9-15 operand requirements 9-14 syntax diagram of 9-14 B BEGIN DECLARE SECTION C examples of 3-9 COBOL examples of 3-10 C++ examples of 3-9 BEG
C Index CEILING function examples of 9-22 syntax diagram of 9-22 CHAR data type 6-20, 6-21 CHAR function examples of 9-23 syntax diagram of 9-23 CHAR VARYING data type 6-20 Character sets description of 6-3 ISO88591 6-3 KANJI 6-3 KSC5601 6-3 setting default 6-60, 6-61, 6-62, 10-64 support standards E-7 UCS2 6-3 Character string data types CHAR and VARCHAR, differences 6-21 examples of literals 6-63 maximum storage lengths 6-21 Character string functions summary of 9-2 ASCII 9-11 CHAR 9-23 CHAR_LENGTH 9-24
C Index CLOSE statement (continued) syntax diagram of 3-11 Cluster sampling 7-10 Clustering key description of 6-56 limits C-2 NONDROPPABLE PRIMARY KEY specification 2-79 STORE BY clause 7-22 STORE BY clause, CREATE TABLE 2-81 system-defined SYSKEY 6-59 CODE_VALUE function, syntax diagram of 9-27 Collations description of 6-5 SQL/MP considerations 1-31 COLS metadata table 10-13 Columns column reference 6-6 default values 6-7 qualified name 6-6 COL_PRIVILEGES metadata table 10-17 Comment (--), examples of
C Index CONTROL QUERY DEFAULT statement (continued) examples of 2-34 syntax diagram of 2-33 CONTROL QUERY SHAPE statement examples of 2-41 syntax diagram of 2-35 CONTROL TABLE statement examples of 2-49 syntax diagram of 2-46 CONVERTTIMESTAMP function examples of 9-30 JULIANTIMESTAMP inverse relationship to 9-30 syntax diagram of 9-30 Correlation names examples of 6-10 purpose of 6-10 table reference use of 6-10 COS function examples of 9-31 syntax diagram of 9-31 COSH function examples of 9-31 syntax dia
D Index CREATE VIEW statement (continued) syntax diagram of 2-104 updatability requirements 2-107 WITH CHECK OPTION within 2-107 CROSS join, description of 2-183 CROSS_PRODUCT_CONTROL default 10-54 Ctrl-c, effect on queries 1-5 Ctrl-Y, effect on MXCI session 4-28 CURRENT_DATE function examples of 9-35 syntax diagram of 9-35 CURRENT_TIME function examples of 9-36 precision specification within 9-36 syntax diagram of 9-36 CURRENT_TIMESTAMP function examples of 9-34, 9-37 precision specification within 9-34,
D Index Data types (continued) comparable and compatible 6-16 datetime DATE 6-23 TIME 6-23 TIMESTAMP 6-23 exact numeric DECIMAL 6-32 descriptions of 6-31 INTEGER 6-32 LARGEINT 6-32 NUMERIC 6-32 PICTURE 6-33 SMALLINT 6-32 fixed length character CHAR 6-20 NATIONAL CHAR 6-20 NCHAR 6-20 PIC 6-20 interval 6-28 Java 2-61 literals, examples of character string literals 6-63 datetime literals 6-66 interval literals 6-71 numeric literals 6-72 varying-length character CHAR VARYING 6-20 NATIONAL CHAR VARYING 6-20 NC
D Index DAY function examples of 9-39 syntax diagram of 9-39 DAYNAME function examples of 9-40 syntax diagram of 9-40 DAYOFMONTH function examples of 9-41 syntax diagram of 9-41 DAYOFWEEK function examples of 9-42 syntax diagram of 9-42 DAYOFYEAR function examples of 9-43 syntax diagram of 9-43 DDL statements See Data Definition Language (DDL) statements DDL_DEFAULT_LOCATIONS default 10-51 DDL_LOCKS metadata table 10-18 DEALLOCATE DESCRIPTOR statement examples of 3-17 syntax diagram of 3-16 DEALLOCATE fil
D Index Default settings (continued) CACHE_HISTOGRAMS_REFRESH_IN TERVALS 10-42 CATALOG 10-48 CROSS_PRODUCT_CONTROL 10-54 DATA_FLOW_OPTIMIZATION 10-54 DDL_DEFAULT_LOCATIONS 10-51 DEF_MAX_HISTORY_ROWS 10-63 DOOM_USERTRANSACTION 10-64 DP2_CACHE_4096_BLOCKS 10-55 DYNAMIC_HISTOGRAM_COMPRESS ION 10-42 FFDC_DIALOUTS_FOR_MXCMP 10-5 5 FLOATTYPE 10-41 GENERATE_EXPLAIN 10-55 GEN_EIDR_BUFFER_SIZE 10-55 GEN_MAX_NUM_PART_DISK_ENTRI ES 10-52 GEN_MAX_NUM_PART_NODE_ENTR IES 10-52 GEN_PA_BUFFER_SIZE 10-56 HIST_DEFAULT_SEL_
D Index Default settings (continued) QUERY_CACHE 10-59 QUERY_CACHE_MAX_VICTIMS 10-5 9 QUERY_CACHE_REQUIRED_PREFIX _KEYS 10-60 QUERY_CACHE_STATEMENT_PINNI NG 10-60 READONLY_CURSOR 10-61 RECOMPILATION_WARNINGS 10-65 REF_CONSTRAINT_NO_ACTION_LIK E_RESTRICT 10-61 REMOTE_ESP_ALLOCATION 10-58 SAVE_DROPPED_TABLE_DDL 10-67 SCHEMA 10-49 SCRATCH_DISKS 10-62 SCRATCH_DISKS_EXCLUDED 10-62 SCRATCH_DISKS_PREFERRED 10-6 2 SCRATCH_FREESPACE_THRESHOL D_PERCENT 10-62 SIMILARITY_CHECK 10-65 SORT_MAX_HEAP_SIZE_MB 10-59 STREAM
D Index DESCRIBE statement (continued) OUTPUT form 3-33 scope of 3-34 syntax diagram of 3-33 DIFF1 function equivalent definitions 9-45 examples of 9-46 syntax diagram of 9-45 DIFF2 function equivalent definitions 9-48 examples of 9-49 syntax diagram of 9-48 DISPLAY STATISTICS command examples of 4-23 syntax diagram of 4-22 DISPLAY USE OF command examples of 4-11 syntax diagram 4-9 DISPLAY_EXPLAIN command examples of 4-14 EXPLAIN function and 4-13 purpose of 4-14 syntax diagram of 4-13 DISPLAY_QC command
E Index DROP TABLE statement authorization and availability requirements 2-127 examples of 2-128 syntax diagram of 2-127 DROP TRIGGER statement authorization and availability requirements 2-129 syntax diagram of 2-129 DROP VIEW statement authorization and availability requirements 2-130 examples of 2-130 syntax diagram of 2-130 DUP utility 5-4 Dynamic SQL, parameter restrictions 2-160 DYNAMIC_HISTOGRAM_COMPRESSION default 10-42 E Embedded SQL data manipulation statements CLOSE 3-11 FETCH 3-39 OPEN 3-71 E
F Index EXECUTE statement (continued) scope of 2-132, 2-134 syntax diagram of 2-131 EXISTS predicate correlated subquery within 6-88 examples of 6-88 syntax diagram of 6-88 EXIT command active transaction, effect on 4-28 examples of 4-28 syntax diagram of 4-28 EXP function examples of 9-51 syntax diagram of 9-51 EXPLAIN function columns in result 9-53 DISPLAY_EXPLAIN command 9-53 examples of 9-56 operator tree 9-53 syntax diagram of 9-52 Expression character (or string) value 6-37 datetime value 6-39, 6-4
G Index FLOATTYPE default 10-41 FLOOR function examples of 9-60 syntax diagram of 9-60 Foreign key, ALTER TABLE statement 2-15 Functions, ANSI compliant 1-34 G GENERATE_EXPLAIN default 10-55 GEN_EIDR_BUFFER_SIZE default 10-55 GEN_MAX_NUM_PART_DISK_ENTRIES default 10-52 GEN_MAX_NUM_PART_NODE_ENTRIES default 10-52 GEN_PA_BUFFER_SIZE default 10-56 GET DESCRIPTOR statement C examples of 3-52 COBOL examples of 3-53 retrieving item count and values 3-46 syntax diagram of 3-45 GET DIAGNOSTICS statement C exampl
I Index HIST_NO_STATS_REFRESH_INTERVAL default 10-43 HIST_NO_STATS_ROWCOUNT default 10-43 HIST_NO_STATS_UEC default 10-43 HIST_PREFETCH default 10-43 HIST_ROWCOUNT_REQUIRING_STATS default 10-44 HIST_SAME_TABLE_PRED_REDUCTION default 10-44 HIST_SCRATCH_VOL default 10-44 HIST_SECURITY_WARNINGS default 10-45 Host variable arrays, INSERT statement 2-148 Host variables, INSERT statement 2-151 HOUR function examples of 9-65 syntax diagram of 9-65 I Identifiers 6-52 ID, authorization 1-5 IF statement examples o
J Index INTERVAL data inserting into SQL/MP columns 6-69 selecting from SQL/MP tables 6-30 Interval data type description of 6-28 examples of literals 6-71 Interval literals description of 6-67 examples of 6-71 Interval value expression examples of 6-45 syntax diagram of 6-43 INVOKE command examples of 4-33 syntax diagram of 4-33 INVOKE directive examples of 3-66 syntax diagram of 3-63 whether preprocessor preserves or overrides 3-29, 3-65 ISO standards E-2 ISO88591 character set 6-3 Isolation levels READ
L Index LIKE predicate CREATE TABLE 2-87 escape character within 6-94 examples of 6-95 NOT within 6-93 syntax diagram of 6-93 wild-card characters within 6-94 Limits constraints C-1 DROP SCHEMA C-1 extents C-1 IN predicate 6-91, C-1 indexes 2-58, C-1 INSERT C-1 INSERT statement 2-149 joins 2-192, C-1 MAXEXTENTS C-1 partitions C-1 referential constraints 2-19, C-2 SELECT statement, FROM clause C-1 tables 2-89, C-2 Literals character string, examples of 6-63 datetime, examples of 6-66 description of 6-60 ex
M Index LOG command concurrent MXCI sessions 4-34 examples of 4-35 log file, contents of 4-34 syntax diagram of 4-34 Log file 4-34 LOG function examples of 9-73 syntax diagram of 9-73 LOG10 function examples of 9-73 syntax diagram of 9-73 Logical name SQL/MP objects 6-13 SQL/MX objects 6-12 Logical operators NOT, AND, OR 6-102 search condition use of 6-102 LOWER function examples of 9-78 syntax diagram of 9-74 LPAD function examples of 9-79 syntax diagram of 9-79 LS command examples of 4-37 options 4-36 L
M Index Metadata schemas (continued) SYSTEM_SCHEMA 10-3 SYSTEM_SQLJ_SCHEMA 10-7 Metadata tables ACCESS_PATHS 10-11 ACCESS_PATH_COLS 10-12 ALL_UIDS 10-8 ASSOC2DS 10-79 CATSYS 10-9 CAT_REFERENCES 10-9 CK_COL_USAGE 10-13 CK_TBL_USAGE 10-13 COLS 10-13 COL_PRIVILEGES 10-17 DATASOURCES 10-80 DDL_LOCKS 10-18 ENVIRONMENTVALUES 10-81 HISTINTS 10-75 HISTOGRAMS_nodename 10-72 HISTOGRAM_INTERVALS 10-73 HISTOGRM 10-74 KEY_COL_USAGE 10-18 MP_PARTITIONS 10-19 NAME2ID 10-81 OBJECTS 10-19 PARTITIONS 10-20 REF_CONSTRAINTS
N Index MONTHNAME function examples of 9-86 syntax diagram of 9-86 MOVINGAVG function examples of 9-88 syntax diagram of 9-87 MOVINGCOUNT function examples of 9-90 syntax diagram of 9-89 MOVINGMAX function examples of 9-92 syntax diagram of 9-91 MOVINGMIN function examples of 9-94 syntax diagram of 9-93 MOVINGSTDDEV function examples of 9-96 syntax diagram of 9-95 MOVINGSUM function examples of 9-98 syntax diagram of 9-97 MOVINGVARIANCE function examples of 9-100 syntax diagram of 9-99 MP_PARTITIONS metad
O Index NCHAR data inserting into SQL/MP columns 6-62, 6-63 selecting from SQL/MP tables 6-22 NCHAR data type associated character sets 6-4 description of 6-20 SQL/MP considerations 1-29, 6-22, 6-62 NCHAR VARYING data type 6-20 Nonaudited tables CREATE TABLE considerations 2-88 DELETE considerations 2-113 transaction management 1-15 NONSTOP_SQLMX_nodename.
P Index P PARALLEL_NUM_ESPS default 10-58 Parameter specification examples of 6-75 names 6-74 type assignments 6-73 Parameters in dynamic SQL, restrictions on use 2-160 PARTITION clause examples 7-7 syntax diagram of 7-5 Partition Overlay Specification (POS) default attributes 10-51 description of 2-89 Partitioning key CREATE INDEX, FIRST KEY specification 2-55 CREATE TABLE, FIRST KEY specification 2-84 Partitions automatic creation 2-89 description of 6-79 hash 6-79 hash, MODIFY utility 5-53 limits C-1 m
Q Index Precision, description of 6-49 Predicates summary of 6-81 BETWEEN 6-82 comparison 6-84 description of 6-81 EXISTS 6-88 IN 6-90 LIKE 6-93 NULL 6-95 quantified comparison 6-97 PREFERRED_PROBING_ORDER_FOR_N ESTED_JOIN default 10-58 PREPARE statement availability 2-160 C examples of 2-162 COBOL examples of 2-163 MXCI examples of 2-161 naming statements 2-161 scope of 2-160 syntax diagram of 2-159 Prepared SQL, statements for 2-3 PRESERVE_MIN_SCALE default 10-41 Primary key ALTER TABLE statement 2-14 d
R Index QUERY_CACHE_REQUIRED_PREFIX_KE YS default 10-60 QUERY_CACHE_STATEMENT_PINNING default 10-60 Quick reference A-1 R RADIANS function examples of 9-116 syntax diagram of 9-116 Range partitioning description of 6-79 MODIFY utility 5-47, 5-49 READ COMMITTED 1-7 READ UNCOMMITTED 1-7 READONLY_CURSOR default 10-61 REAL data type 6-33 RECOMPILATION_WARNINGS default 10-65 RECOVER utility 5-80 REFERENCES access privilege 2-138, 2-167 References column constraint, ALTER TABLE statement 2-15, 2-18 References
S Index ROLLBACK WORK statement C examples of 2-173 COBOL examples of 2-173 MXCI examples of 2-172 syntax diagram of 2-172 ROUTINES metadata table 10-23 Row value constructor BETWEEN predicate use of 6-82 comparison predicates use of 6-84 IN predicate use of 6-90 NULL predicate use of 6-95 quantified comparison predicates use of 6-97 ROWS SINCE function examples of 9-121 syntax diagram of 9-120 Rowsets DELETE statement 2-110, 2-111 expressions 6-51 GET DESCRIPTOR items 3-49 INSERT statement 2-146, 2-148 p
S Index Savepoints (continued) INSERT statement 2-149 UPDATE statement 2-231 UPD_SAVEPOINT_ON_ERROR default 10-64 SAVE_DROPPED_TABLE_DDL default 10-67 Scale 6-49 SCHEMA default 10-49 Schemas, description of 6-101 SCHEMATA metadata table 10-10 SCHEMA_REPLICAS metadata table 10-10 Scope ALLOCATE CURSOR use of 3-3 ALLOCATE DESCRIPTOR use of 3-6 CLOSE use of 3-11 DEALLOCATE DESCRIPTOR use of 3-16 DEALLOCATE PREPARE use of 3-18 DECLARE CURSOR use of 3-24 DESCRIBE use of 3-34 EXECUTE use of 2-132 FETCH use of 3
S Index SELECT statement (embedded) (continued) syntax diagram of 2-174 table reference within 2-178 SEQUENCE BY clause examples of 7-20 SELECT statement use of 7-18 syntax diagram of 7-18 Sequence functions summary of 9-7 DIFF1 9-45 DIFF2 9-48 LASTNOTNULL 9-68 MOVINGAVG 9-87 MOVINGCOUNT 9-89 MOVINGMAX 9-91 MOVINGMIN 9-93 MOVINGSTDDEV 9-95 MOVINGSUM 9-97 MOVINGVARIANCE 9-99 OFFSET 9-102 ROWS SINCE 9-120 RUNNINGAVG 9-124 RUNNINGCOUNT 9-126 RUNNINGMAX 9-128 RUNNINGMIN 9-130 RUNNINGSTDDEV 9-132 RUNNINGSUM 9-
S Index SET TABLE TIMEOUT statement (continued) MXCI examples of 2-216 syntax diagram of 2-214 SET TERMINAL_CHARSET command syntax diagram of 4-54 SET TRANSACTION statement C examples of 2-221 COBOL examples of 2-221 MXCI examples of 2-221 syntax diagram of 2-218 transaction modes set by 2-218 SET WARNINGS command examples of 4-55 syntax diagram of 4-55 SH command examples of 4-56 syntax diagram of 4-56 SHARE lock mode 1-11 Shorthand view 6-109 SHOW PARAM command examples of 4-57 syntax diagram of 4-57 SH
S Index SQL descriptor area (continued) SET DESCRIPTOR statement use of 3-78 specifying size 3-6 SQL statement names, specifying with comment 2-160 SQL statements ANSI compliant 1-32 interruption of 1-5 SQL/MX extensions 1-33 SQL value expression 6-37 SQLCODE, using ERROR command 1-35 SQLMP objects, logical names 6-13 SQLMX objects, logical names 6-12 SQLSTATE, in SQL/MX messages 1-35 SQL/MP aliases ALTER SQLMP ALIAS statement 2-8 catalogs 10-49 CREATE SQLMP ALIAS statement 2-70 description of 6-105 DROP
S Index Statistics (continued) syntax diagram 4-22 HISINTS SQL/MP table 10-75 Histogram attributes in SYSTEM_DEFAULTS table 10-41 HISTOGRAMS_nodename table 10-72 HISTOGRAM_INTERVALS table 10-73 HISTOGRM table 10-74 LS command 4-36 query cache 4-18 query plan 4-20 QUERYCACHE function 9-108 QUERYCACHEENTRIES function 9-112 SET STATISTICS command 4-53 SQL/MP histogram tables 10-69 stored in PARTITIONS table 10-20 UPDATE STATISTICS statement considerations 2-243 examples of 2-246 syntax diagram 2-239 STDDEV f
T Index Super ID, privileges for executing utilities 5-2 SYSKEY description of 6-59 INVOKE statement 3-65 system-clustered tables 5-57 SYSKEY column, from INVOKE directive 3-65 SYSKEY, column 2-194 System-clustered tables 5-57 SYSTEM_DEFAULTS metadata table 10-30 SYSTEM_DEFAULTS table constraint droppable option 10-40 data types 10-41 examples of 10-69 histograms 10-41 isolation level 10-45 locking 10-46 national character set 10-47 nonaudited tables 10-48 object naming 10-48 partition management 10-51 qu
U Index Transaction isolation levels (continued) REPEATABLE READ 1-22 SERIALIZABLE 1-22 Transaction management AUTOCOMMIT, effect of 1-15, 2-157 MODIFY TABLE use of 1-15 rules for DML statements 1-15 Transaction Management Facility (TMF) 1-12 Transaction management statements BEGIN WORK 2-25 COMMIT WORK 2-30 ROLLBACK WORK 2-172 SET TRANSACTION statement 2-218 Transactions 1-14 TRANSLATE function, syntax diagram of 9-152 TRANSPOSE clause cardinality of result 7-28 degree of result 7-27 examples of 7-29 SEL
V Index UPDATE statement (continued) SKIP CONFLICT access 2-230 syntax diagram of 2-226 WHERE clause 2-230 UPDATE statement (embedded) C examples of 2-237 COBOL examples of 2-237 positioned form 2-226 searched form 2-226 UPDATE STATISTICS statement column groups 2-240 column lists 2-240 examples of 2-246 histogram tables 2-240 row distribution 2-241 sample size 2-241 syntax diagram of 2-239 table row count 2-242 UPD_ABORT_ON_ERROR default 10-64 UPD_ORDERED default 10-59 UPD_SAVEPOINT_ON_ERROR default 10-6
W Index Views (continued) relationship to tables 6-108 SQL/MP considerations 1-30 updatability requirements 2-107 VWS metadata table 10-28 VW_COL_TBLS metadata table 10-28 VW_COL_TBL_COLS metadata table 10-29 VW_COL_USAGE metadata table 10-29 VW_TBL_USAGE metadata table 10-29 W WEEK function examples of 9-171 syntax diagram of 9-171 WHENEVER declaration actions within 3-86 C examples of 3-87 COBOL examples of 3-87 conditions within 3-85 syntax diagram of 3-85 Y YEAR function examples of 9-172 syntax dia
Special Characters Index HP NonStop SQL/MX Reference Manual—540440-003 Index -36