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 Release 3.0 Supported Release Version Updates (RVUs) This publication supports J06.
Document History Part Number Product Version 640322-001 NonStop SQL/MX Release 3.
Legal Notices © Copyright 2011 Hewlett-Packard Development Company L.P. Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. The information contained herein is subject to change without notice.
HP NonStop SQL/MX Reference Manual Index Figures Tables Legal Notices What’s New in This Manual xxxiii Manual Information xxxiii New and Changed Information About This Manual xxxix Audience xxxix Organization xxxix Related Documentation xli Notation Conventions xliv HP Encourages Your Comments xxxiv xlvii 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.
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.
4. MXCI Commands (continued) Contents 4. MXCI Commands (continued) Considerations for SHOWLABEL 4-96 Examples of SHOWLABEL 4-98 SHOWSHAPE Command 4-106 Considerations for SHOWSHAPE 4-106 Examples of SHOWSHAPE 4-106 5.
5. SQL/MX Utilities (continued) Contents 5.
5. SQL/MX Utilities (continued) Contents 5. SQL/MX Utilities (continued) Examples of VERIFY 5-126 6.
Contents 6. SQL/MX Language Elements (continued) 6.
6. SQL/MX Language Elements (continued) Contents 6.
7. SQL/MX Clauses (continued) Contents 7. SQL/MX Clauses (continued) Examples of SEQUENCE BY 7-20 STORE BY Clause 7-22 Considerations for STORE BY 7-23 Effect of Storage Order on Partitioning 7-24 TRANSPOSE Clause 7-25 Considerations for TRANSPOSE 7-27 Examples of TRANSPOSE 7-29 8.
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 (continued) Contents A. Quick Reference (continued) C D E F G H I L M O P R S T U V W A-1 A-2 A-2 A-3 A-3 A-3 A-3 A-4 A-4 A-4 A-4 A-4 A-5 A-5 A-6 A-6 A-6 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) 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 2-1. Table 2-2. Table 2-3. Table 2-4. Table 2-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.
Tables (continued) Contents Tables (continued) Table 9-8. Table 9-9. Table B-1.
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 Release 3.
New and Changed Information What’s New in This Manual New and Changed Information Changes to the 640322-001 manual: • • • • • • • • • • • • Updated the description of Begin and End a Transaction on page 2-31. Updated the maximum combined length of the columns for the following: ° ° ° UNIQUE contraint on page 2-81 PRIMARY KEY constraint on page 2-82 REFERENCES contraint on page 2-83 Added Table 2-1, Maximum Key Sizes Available, on page 2-83. Updated the description of key-column-list on page 2-86.
New and Changed Information What’s New in This Manual • • • • • • • • • • • • • • • • • ° ° ° ° GET VERSION OF Object Command on page 4-40 GET VERSION OF MODULE Command on page 4-41 GET VERSION OF PROCEDURE Command on page 4-42 GET VERSION OF STATEMENT Command on page 4-43 Updated the default value of HIST_NO_STATS_UEC on page 4-80 and on page 10-51. Added the following utilities: ° ° DOWNGRADE Utility on page 5-4 UPGRADE Utility on page 5-121 Added FIXRCB Operation on page 5-20.
New and Changed Information What’s New in This Manual • • • • • • • • • • • • • • Added a note for the following tables: ° ° ALL_UIDS Table on page 10-8 VW_COL_TBLS Table on page 10-32 Updated the description of the existing column names in the following tables: ° ° ° ° ° ° ° SCHEMATA Table on page 10-10 COL_PRIVILEGES Table on page 10-18 DDL_LOCKS Table on page 10-19 OBJECTS Table on page 10-21 REF_CONSTRAINTS Table on page 10-23 TBL_CONSTRAINTS Table on page 10-26 TBL_PRIVILEGES Table on page 10
New and Changed Information What’s New in This Manual • • Added the following commands and utilities under A, Quick Reference: ° ° ° DOWNGRADE Utility on page A-2 GET VERSION OF and GET NAMES OF MXCI commands on page A-3 UPGRADE Utility A-6 Updated the maximum limit for the following: ° ° ° Constraints on page C-1 Indexes on page C-1 Tables on page C-2 HP NonStop SQL/MX Reference Manual—640322-001 xxxvii
What’s New in This Manual New and Changed Information HP NonStop SQL/MX Reference Manual—640322-001 xxxviii
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 For more information about downloading online help, see the SQL/MX Installation and Management Guide. 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.
General Syntax Notation About This Manual General Syntax Notation The following list summarizes the notation conventions for syntax presentation in 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.
General Syntax Notation About This Manual | Vertical Line. A vertical line separates alternatives in a horizontal list that is enclosed in brackets or braces. For example: INSPECT { OFF | ON | SAVEABEND } … 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.
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).
About This Manual HP Encourages Your Comments HP NonStop SQL/MX Reference Manual—640322-001 xlviii
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 SQL/MX language elements are part of statements and commands and include data types, expressions, functions, identifiers, literals, and predicates. For more information, see Section 6, SQL/MX Language Elements. For more information on specific functions and expressions, see Section 9, SQL/MX Functions and Expressions.
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-74. 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) DDL operations 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.*** Not allowed.
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-244. 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-77 and the CREATE INDEX Statement on page 2-54 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-83 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-59. 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-38. 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-28. 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-33.
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—640322-001 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 PROCEDURE Statement on page 2-61 Defines an existing Java method as an SPJ and registers it in NonStop SQL/MX. CREATE SCHEMA Statement on page 2-69 Creates a schema. CREATE SQLMP ALIAS Statement on page 2-73 Creates mappings from logical names to physical names for SQL/MP database objects. CREATE TABLE Statement on page 2-77 Creates a table. CREATE TRIGGER Statement on page 2-101 Creates a trigger.
Data Manipulation Language (DML) Statements SQL/MX Statements REVOKE EXECUTE Statement on page 2-193 Revokes access privileges for a procedure to specified users. SET Statement on page 2-233 Controls the action of a BEFORE trigger. SIGNAL SQLSTATE Statement on page 2-249 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 Use these statements to compile an SQL statement and then execute the statement any number of times within the current session: EXECUTE Statement on page 2-138 Executes an SQL statement previously compiled by the PREPARE statement. PREPARE Statement on page 2-183 Compiles an SQL statement for later execution with EXECUTE.
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-234 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-25 Alters a trigger. CREATE TRIGGER Statement on page 2-101 Creates a trigger. DROP TRIGGER Statement on page 2-136 Drops a trigger. SET Statement on page 2-233 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-13. 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-13.
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-13. 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 2010 bytes for 4K blocks and 2048 bytes for 32K blocks.
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 When SET NULL is specified with the ON UPDATE referential triggered action, and a row in the referencing table matches the row in the referenced-table, the referencing column(s) of the referencing row from the referencing table is set to NULL.
Syntax Description of ALTER TABLE SQL/MX Statements If you do not specify a constraint name, NonStop SQL/MX constructs an SQL identifier as the name for the constraint in the catalog and schema for table.The identifier consists of the fully qualified table name concatenated with a systemgenerated unique identifier. For example, a constraint on table A.B.C might be assigned a name such as A.B.C_971..._01... .
Syntax Description of ALTER TABLE SQL/MX Statements When a PRIMARY KEY constraint is created on a table, all the index columns must have a NOT NULL clause in the CREATE TABLE statement for the table. The value of the PRIMARY_KEY_CONSTRAINT_DROPPABLE_OPTION attribute in the DEFAULTS Table has no affect on a PRIMARY KEY constraint added by using the ALTER TABLE statement because in this case the PRIMARY KEY is always droppable.
Considerations for ALTER TABLE SQL/MX Statements the column list associated with FOREIGN KEY. If column-list is omitted, the referenced table’s PRIMARY KEY columns are the referenced columns. 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.
Considerations for ALTER TABLE SQL/MX Statements ALTER TABLE works only on user-created tables. You cannot use it to modify a metadata table even if you are the owner of the metadata tables or a SUPER user. Adding a Constraint To add a constraint that refers to a column in another table, you must have REFERENCES privileges on that column. Dropping a Constraint To drop a constraint, you must be owner of the table on which the constraint has been defined or be the super ID.
Examples of ALTER TABLE SQL/MX Statements Indexes used to enforce constraints can require significant amounts of disk space, and NonStop SQL/MX might be unable to create the supporting index when you add the constraint. Consequently, the add constraint operation fails. Note. When using a large table, you should create the supporting index before you create a constraint. As a result, you can create the index as needed (for example, with partitions) so that you have better control over use of disk volumes.
Examples of ALTER TABLE SQL/MX Statements • This example drops a constraint: ALTER TABLE persnl.project DROP CONSTRAINT projtimestamp_uc; • This example adds a column with a foreign key constraint: ALTER TABLE persnl.project ADD COLUMN projlead NUMERIC (4) UNSIGNED HEADING 'Project/Lead' CONSTRAINT projlead_fk REFERENCES persnl.employee; • This example adds a foreign key table constraint.
Examples of ALTER TABLE SQL/MX Statements EMPNUM CHAR(3) CHARACTER SET ISO88591 COLLATE DEFAULT NO DEFAULT -- NOT NULL NOT DROPPABLE , EMPNAME CHAR(20) CHARACTER SET ISO88591 COLLATE DEFAULT DEFAULT NULL , GRADE DECIMAL(4, 0) DEFAULT NULL , CITY CHAR(15) CHARACTER SET ISO88591 COLLATE DEFAULT DEFAULT NULL , PRI_WK CHAR(3) CHARACTER SET ISO88591 COLLATE DEFAULT DEFAULT NULL , CONSTRAINT NIST_EMB_CAT.SUN.STAFF_M_452683997_9541 CHECK (NIST_EMB_CAT.SUN.STAFF_M.
ALTER TRIGGER Statement SQL/MX Statements ALTER TRIGGER Statement Considerations for ALTER TRIGGER The ALTER TRIGGER statement is used to enable or disable triggers, individually or by SQL/MX table. ALTER TRIGGER { ENABLE trigger-name | ENABLE ALL OF table-name | DISABLE trigger-name | DISABLE ALL OF table-name}; Syntax Description of ALTER TRIGGER trigger-name specifies the ANSI logical name of the trigger to be altered, of the form: [[catalog-name.]schema-name.
Considerations for BEGIN WORK SQL/MX Statements BEGIN WORK is an SQL/MX extension. BEGIN WORK Considerations for BEGIN WORK Effect on Audited Tables A user-defined transaction groups together a set of operations on audited tables so that changes made by the operations can be committed (with the COMMIT statement) or rolled back (with the ROLLBACK statement) as a unit. That is, the sequence of SQL statements that make up the transaction either completely executes or has no effect.
COBOL Examples of BEGIN WORK SQL/MX Statements CHAR SQLSTATE[6]; ... EXEC SQL END DECLARE SECTION; ... EXEC SQL BEGIN WORK; /* Start a transaction. ... EXEC SQL UPDATE ... ; /* Change the database. ... if (strcmp(SQLSTATE, SQLSTATE_OK) == 0) EXEC SQL COMMIT WORK; /* Commit the changes. else EXEC SQL ROLLBACK WORK; /* Roll back the changes. */ */ */ */ COBOL Examples of BEGIN WORK • Begin a transaction, execute an UPDATE statement, and test SQLSTATE.
CALL Statement SQL/MX Statements 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}...] procedure-ref specifies an ANSI logical name of the form: [[catalog-name.]schema-name.
Considerations for CALL SQL/MX Statements 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. Required Privileges To execute the CALL statement, you must have EXECUTE privilege on the procedure. For more information, see the GRANT EXECUTE Statement on page 2-165.
Examples of CALL SQL/MX Statements 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. For more information on handling null input and output, see the SQL/MX Guide to Stored Procedures in Java.
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 Considerations for CONTROL QUERY DEFAULT Examples of CONTROL QUERY DEFAULT 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-34. 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 SHORTCUT_GROUPBY Replaces an AGGREGATE (set) operation node in operator tree. EXPR Replaces a map value IDs node in operator tree. SORT Replaces a SORT node in operator tree. EXCHANGE Replaces any of three nodes—PARTITION ACCESS, SPLIT TOP / PARTITION ACCESS, and REPARTITION—in operator tree. PARTITION_ACCESS Replaces a PARTITION ACCESS node in operator tree. SPLIT_TOP_PA Replaces a SPLIT TOP / PARTITION ACCESS node pair in operator tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements join-shape (shape,shape [,{TYPE1 | TYPE2}] [,num-of-esps]) | INDEXJOIN specifies the join type and the number of ESPs that you can use with JOIN, NESTED_JOIN, MERGE_JOIN, HASH_JOIN, HYBRID_HASH_JOIN, or ORDERED_HASH_JOIN as follows: Note.
CONTROL QUERY SHAPE Statement SQL/MX Statements 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'. Use this option to force the scan to be on that particular index or base table. The specified access-path must cover all of the predicates defined on the table columns for a plan to be generated. access-path for an MP index can contain only the last part of the filename.
CONTROL QUERY SHAPE Statement SQL/MX Statements 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. >>explain options 'f' xx; LC -7 4 5 . 3 2 1 . RC -. 6 . . . . . .
Examples of CONTROL QUERY SHAPE SQL/MX Statements 4 3 2 1 . . . . . . 5 4 3 2 1 shortcut_scalar_aggr firstn split_top partition_access index_scan fr 1:72(logph) PSX2 (s) --- SQL operation complete. >>log; HP NonStop SQL/MX Reference Manual—640322-001 2- 47 1.00E+000 1.00E+000 8.00E+007 8.00E+007 8.
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-240. '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-34.
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-3. 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—640322-001 2- 53
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-13. 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-83 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 data is to be moved. Fore more information about creating and populating indexes, see the SQL/MX Installation and Management Guide. 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.
CREATE PROCEDURE Statement SQL/MX Statements LOCATION $data1 ATTRIBUTE NO AUDITCOMPRESS PARTITION (ADD FIRST KEY 'E' ADD FIRST KEY 'J' ADD FIRST KEY 'O' ADD FIRST KEY 'T' LOCATION LOCATION LOCATION LOCATION $data1, $data2, $data2, $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.
CREATE PROCEDURE Statement SQL/MX Statements Note. Delimited variables in this syntax diagram are case-sensitive. Case-sensitive variables include java-method-name, java-signature, class-or-JAR-file-path, and delimited parts of the procedure-name. The remaining syntax is not case-sensitive. The max-result-set can have a value in the range 0–255 from J06.05 and later J-series RVUs and H06.16 and later H-series RVUs. procedure-ref([sql-parameter[{, sql-parameter}...
CREATE PROCEDURE Statement SQL/MX Statements INOUT specifies a parameter that passes data to and accepts data from an SPJ. 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-56. 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 SQL/MX Data Type Maps to Java Data Type... FLOAT double (or java.lang.Double if specified)*** REAL float (or java.lang.Float if specified)*** DOUBLE PRECISION double (or java.lang.Double if specified)*** * The character set for character string data types can be ISO88591 or UCS2. ** Numeric data types can be only SIGNED, which is the default in NonStop SQL/MX. *** By default, the SQL/MX data type maps to a Java primitive data type.
CREATE PROCEDURE Statement SQL/MX Statements Java method definition within the class file. Each Java data type that corresponds to an OUT or INOUT parameter must be followed by empty square brackets ([ ]), such as java.lang.Integer[]. java-datatype specifies a mappable Java data type. For the mapping of the Java data types to SQL/MX data types, see sql-datatype on page 2-63.
Considerations for CREATE PROCEDURE SQL/MX Statements Any Guardian file name you specify must match the designated schema subvolume name for the schema in which the SPJ is being created. Otherwise, NonStop SQL/MX returns an error. filename is an optional Guardian file name. The name must be eight characters long in length and must end with the digits “00” (zero zero). NO SQL specifies that the SPJ cannot perform SQL operations.
Examples of CREATE PROCEDURE SQL/MX Statements Examples of CREATE PROCEDURE • This CREATE PROCEDURE statement registers the SPJ named LOWERPRICE, which does not accept any arguments: SET CATALOG samdbcat; SET SCHEMA sales; CREATE PROCEDURE lowerprice() EXTERNAL NAME 'Sales.lowerPrice()' EXTERNAL PATH '/usr/mydir/myclasses' LANGUAGE JAVA PARAMETER STYLE JAVA; The statement verifies the existence of the SPJ method, lowerprice, in the /usr/mydir/myclasses/Sales.class.
Examples of CREATE PROCEDURE SQL/MX Statements EXTERNAL PATH '/usr/mydir/myclasses' LANGUAGE JAVA PARAMETER STYLE JAVA; Because the OUT parameter is supposed to map to the Java wrapper class, java.lang.Integer, you must specify the Java signature in the EXTERNAL NAME clause. To call this SPJ, use this statement: CALL samdbcat.sales.monthlyorders(3, ?); NUMBER ----------4 • This CREATE PROCEDURE statement registers the SPJ named SALES.ORDER_SUMMARY and returns two result sets. CREATE PROCEDURE SAMDBCAT.
CREATE SCHEMA Statement SQL/MX Statements CREATE SCHEMA Statement Considerations for CREATE SCHEMA Examples of CREATE SCHEMA CREATE SCHEMA creates an SQL/MX schema. See Schemas on page 6-105. 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 LOCATION subvolume optionally specifies the designated subvolume name for the schema. Ordinarily, NonStop SQL/MX generates a subvolume name for the schema. However, in some instances, you might need to specify the subvolume, such as when creating an RDF backup database.
Considerations for CREATE SCHEMA SQL/MX Statements table-definition is a CREATE TABLE statement. view-definition is a CREATE VIEW statement. grant-statement is a GRANT statement. index-definition is a CREATE INDEX statement. index-definition cannot be the only schema-element. Considerations for CREATE SCHEMA Duplicate Schema Subvolume One use of the schema subvolume is to identify all Guardian files in a schema for use with Guardian-based commands for TMF, RDF or other subsystems.
Examples of CREATE SCHEMA SQL/MX Statements • 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-20. 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-13. 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 file-option is: STORE BY store-option | LOCATION [\node.]$volume[.subvolume.file-name] [NAME partition-name] | partn-file-option | ATTRIBUTE[S] attribute [,attribute]... 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]...
Syntax Description of CREATE TABLE SQL/MX Statements column data-type specifies the name and data type for a column in the table. At least one column definition is required in a CREATE TABLE statement. 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.
Syntax Description of CREATE TABLE SQL/MX Statements NOT NULL [[NOT] DROPPABLE] is a column constraint that specifies that the column cannot contain nulls. If you omit NOT NULL, nulls are allowed in the column. If you specify both NOT NULL and NO DEFAULT, each row inserted in the table must include a value for the column. See MXCI Parameters on page 6-77 and Null on page 6-80. DROPPABLE specifies that you can drop the NOT NULL constraint by using ALTER TABLE at some later time.
SQL/MX Statements Syntax Description of CREATE TABLE ASCENDING and DESCENDING specify the direction for entries in one 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. You can specify PRIMARY KEY only once on any CREATE TABLE statement.
Syntax Description of CREATE TABLE SQL/MX Statements • • You do not specify a PRIMARY KEY constraint within the CREATE TABLE statement. The PRIMARY KEY defined in the CREATE TABLE statement is droppable. In any of these cases, NonStop SQL/MX implements the PRIMARY KEY as a separate unique index. In the scenario described by the first bullet, NonStop SQL/MX does not allow the primary key constraint to have the NOT DROPPABLE clause.
Syntax Description of CREATE TABLE SQL/MX Statements 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. Without the FOREIGN KEY clause, the foreign key in table is the column being defined; with the FOREIGN KEY clause, the foreign key is the column or set of columns specified in the FOREIGN KEY clause.
Syntax Description of CREATE TABLE SQL/MX Statements REF_CONSTRAINT_NO_ACTION_LIKE_RESTRICT. Options for this attribute are: OFF SQL issues an error. SYSTEM SQL issues warning 1302, indicating that it will behave like RESTRICT. This is the default value. ON Makes NO ACTION behave like RESTRICT, without warnings or errors. When CASCADE is specified with the ON DELETE referential triggered action, a row in the referencing table and its corresponding row in the referenced-table is deleted.
Syntax Description of CREATE TABLE SQL/MX Statements 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. You cannot create self-referencing foreign key constraints.
Syntax Description of CREATE TABLE SQL/MX Statements If you do not specify a LOCATION clause and your system does not have a value for the DDL_DEFAULT_LOCATIONS default (either in your environment or at the system level) and your environment does not have a =_DEFAULTS value, the CREATE statement will fail with an error. subvolume is the name of the schema subvolume for the schema in which the table is being created.
Syntax Description of CREATE TABLE SQL/MX Statements BY (partitioning-column [,partitioning-column]...) specifies the columns that make up the partitioning key. If you do not specify this clause, the partitioning key is the same as the clustering key of the table. Partitioning columns cannot be floating-point data columns. ADD range-partn-defn defines a single secondary partition and includes the FIRST KEY and a partn-defn. range-partn-defn is: FIRST KEY {col-value | (col-value [,col-value]...
Syntax Description of CREATE TABLE SQL/MX Statements 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. volume is the name of an audited, non-SMF DAM volume on the specified node (or the Guardian volume named in the =_DEFAULTS define if none is specified). If you do not specify a LOCATION clause, NonStop SQL/MX uses the default volume named in the =_DEFAULTS define.
Syntax Description of CREATE TABLE SQL/MX Statements space. In ATTRIBUTES clauses in other places, you can separate attributes with either a space or a comma. You can specify these file attributes: ALLOCATE/DEALLOCATE on page 8-2 Controls amount of disk space allocated. AUDITCOMPRESS on page 8-3 Controls whether unchanged columns are included in audit records. BLOCKSIZE on page 8-4 Sets size of data blocks. CLEARONPURGE on page 8-5 Controls disk erasure when table is dropped.
Considerations for CREATE TABLE SQL/MX Statements This table show the results of specifying or not specifying WITH CONSTRAINTS on primary key constraints: WITH CONSTRAINTS clause? Source table has... Target table will have... No DROPPABLE primary key constraint No primary key constraint. Yes DROPPABLE primary key constraint The same DROPPABLE primary key constraint with a different name.
Considerations for CREATE TABLE SQL/MX Statements Partitions If there is a possibility that you might need to partition a table in the future, you should create it with at least one partition. This avoids recompilation if you add more partitions later. The LIKE specification The CREATE TABLE LIKE statement does not create views, owner information, or privileges for the new table based on the source table.
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 POS_RAISE_ERROR attribute controls how errors are displayed. For values and syntax of these attributes, see Partition Management on page 10-60. To enable POS, set the POS_NUM_OF_PARTNS attribute to a value greater than 1. To activate POS, ensure that the following conditions are true: • • • • The POS feature is enabled during execution of a CREATE TABLE statement.
Considerations for CREATE TABLE 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. Creating a Table Without STORE BY Clause or Primary Key NonStop SQL/MX bases table partitioning on clustering key columns, specified by the STORE BY clause or, if there is no STORE BY clause, the primary key columns.
Considerations for CREATE TABLE SQL/MX Statements Conflicting Constraints • • The two constraints in a table conflict if the referenced table is the same and the referencing columns overlap or The two constraints of a table conflict if the referenced table and the referencing columns are the same and are in the same order, but the RI actions are different.
Examples of CREATE TABLE SQL/MX Statements Consider an RI with an RI action other than NO ACTION or RESTRICT. When the primary table is deleted and the delete action in the RI of the foreign table is CASCADE, the row trigger on the foreign table with DELETE as the trigger operation is fired if there are matching rows in the foreign table.
Examples of CREATE TABLE SQL/MX Statements range partition by (a) (add first key 2 location $HIJO NAME partition1 , add first key 512 location $CHINA NAME partition2 ) attribute extent (1024, 1024), maxextents 16; --- SQL operation complete. • Create tab2: >>create table tab2 like tab1 with partitions; --- SQL operation complete. • Perform SHOWDDL to display tab1’s properties: >>showddl tab1; CREATE TABLE J1.SCH1.TAB1 ( A INT NO DEFAULT -- NOT NULL NOT DROPPABLE , B INT DEFAULT NULL , CONSTRAINT J1.
Examples of CREATE TABLE SQL/MX Statements 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.A IS NOT NULL) NOT DROPPABLE ) LOCATION \CARNAG.$SARA.ZSDCL87P.H5V45W00 NAME CARNAG_SARA_ZSDCL87P_H5V45W00 ATTRIBUTES EXTENT (1024, 1024), MAXEXTENTS 16 PARTITION ( ADD FIRST KEY (2) LOCATION \CARNAG.$HIJO.ZSDCL87P.
CREATE TRIGGER Statement SQL/MX Statements • 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.
Syntax Description of CREATE TRIGGER SQL/MX Statements 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 [[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.]table-name where each part of the name is a valid SQL identifier with a maximum of 128 characters. Triggers can be defined only on SQL/MX tables.
Considerations for CREATE TRIGGER SQL/MX Statements 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. Use the GET DIAGNOSTICS command to retrieve quoted-string-expr (as message-text) and quoted-sqlstate. quoted-string-expr is a string expression.
Considerations for CREATE TRIGGER SQL/MX Statements 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. BEFORE triggered statements Triggering statement Referential actions AFTER triggered statements Execution of a statement is considered to be complete only when all cascaded triggers are complete.
Considerations for CREATE TRIGGER SQL/MX Statements the action of the trigger. Because BEFORE-triggers can only be row triggers, they use transition variables to access old and new states of the row. Before-type triggers do not modify tables. However, by using a SET statement, they can assign new values only to the NEW ROW transition variables. As a result, a BEFORE-type trigger can override the effect of the original triggering statement.
Considerations for CREATE TRIGGER SQL/MX Statements 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. User applications do not require an SQL compilation when a trigger is changed from DISABLED to ENABLED, or from ENABLED to DISABLED, using the ALTER TRIGGER statement.
Examples of CREATE TRIGGER SQL/MX Statements 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. UPDATE and DELETE statement triggers behave as a sequence of statement triggers that are triggered once for each value in the array of values in the rowset.
Examples of CREATE TRIGGER SQL/MX Statements 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.drug) IN (SELECT upshift(generic_drugs.drug) FROM generic_drugs)) SET newdrug.
SQL/MX Statements Examples of CREATE TRIGGER 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-112. 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-56. (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 string literals. For the syntax description of query-expr, see SELECT Statement on page 2-198. 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 To define an updatable view, a query expression must also meet these requirements: • • • • • • It cannot contain a JOIN, UNION, or EXCEPT clause. 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.
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 avoid dynamic recompilation because of a change in the transaction mode, consider specifying access options for individual DML statements instead of using SET TRANSACTION. Audited and Nonaudited Tables SQL/MX tables can only be audited. You can run NonStop SQL/MX against nonaudited SQL/MP tables. The TMF product works only on audited tables, so a transaction does not protect operations on nonaudited tables.
C Examples of DELETE SQL/MX Statements • Remove the row for TIM WALKER from the EMPLOYEE table: DELETE FROM persnl.employee WHERE first_name = 'TIM' AND last_name = 'WALKER'; --- 1 row(s) deleted. • Remove from the table ORDERS any orders placed with sales representative 220 by any customer except customer number 1234: DELETE FROM sales.orders WHERE salesrep = 220 AND custnum <> 1234; --- 2 row(s) deleted. • Remove from the table PARTSUPP all suppliers who charge more than $1,600.
COBOL Examples of DELETE SQL/MX Statements • 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; ... EXEC SQL OPEN emp_cursor; ... EXEC SQL FETCH emp_cursor INTO :hv_empnum, :hv_deptnum, :hv_jobcode, :hv_salary; ... /* Process fetched row. */ if (hv_jobcode == 1234) EXEC SQL DELETE FROM PERSNL.
Publish/Subscribe Examples of DELETE SQL/MX Statements Publish/Subscribe Examples of DELETE Suppose that these SQL/MP tables and index (and the metadata mappings) have been created: CREATE TABLE $db.dbtab.tab1 (a INT NOT NULL, 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.tab2; • This example shows the SET ON ROLLBACK clause.
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-3. 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-13. 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-105.
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-13. 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-112. 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.
EXPLAIN Statement SQL/MX Statements EXPLAIN Statement Considerations for EXPLAIN Examples of EXPLAIN The EXPLAIN statement generates and displays the result of the EXPLAIN function, describing an access plan for a SELECT, INSERT, DELETE, UPDATE, or CALL statement. It displays the query execution plans in a readable format. It can display plans from modules created by the SQL/MX compiler. The EXPLAIN statement can also be used from JDBC or ODBC application like any other SQL/MX Statement.
Considerations for EXPLAIN SQL/MX Statements stmt-name is the statement pattern that includes name or %, or S%, and so on with single quotes. The syntax for the EXPLAIN statement supports four output options. Table 2-3 summarizes the options. Table 2-3. EXPLAIN Statement Options Syntax Option Type Purpose OPTIONS 'f' Formatted Provides the basic information contained in the query execution plan. This information is formatted for readability and limited to 79 characters (one line) per operator.
Considerations for EXPLAIN SQL/MX Statements Machine-readable [OPTIONS 'm'] Considerations The machine-readable option provides an output in the format that can be read only by machines but is suitable for programs.Table 2-4 lists the fields of the OPTIONS 'm' output. Table 2-4. Fields of OPTIONS 'm' Output Column name Data Type Description MODULE NAME CHAR (60) Reserved for future use. STATEMENT NAME CHAR (60) Statement name; truncated on the right if longer than 60 characters.
Examples of EXPLAIN SQL/MX Statements Table 2-5 lists the cost factors of the DETAIL_COST column: Table 2-5. Cost Factors of DETAIL_COST column Cost Factor Description CPU_TIME An estimate of the number of seconds of processor time it might take to execute the instructions for this operator. A value of 1.0 is 1 second. IO_TIME An estimate of the number of seconds of I/O time (seeks plus data transfer) to perform the I/O for this operator.
Examples of EXPLAIN SQL/MX Statements ps_suppkey INT not null not droppable, ps_availqty INT not null not droppable, ps_supplycost NUMERIC(12,2) not null not droppable, ps_comment VARCHAR(199) not null not droppable, PRIMARY KEY (ps_partkey,ps_suppkey) not droppable); Create index psx1 on partsupp ( ps_suppkey , ps_supplycost , ps_availqty ); Create index psx2 on partsupp ( ps_partkey , ps_suppkey , ps_supplycost , ps_availqty ); To use the EXPLAIN statement with a prepared statement, prepare the query,
Examples of EXPLAIN SQL/MX Statements The following output is displayed: ------------------------------------------------------------------ PLAN SUMMARY MODULE_NAME .............. DYNAMICALLY COMPILED STATEMENT_NAME ........... XX PLAN_ID .................. 212122794829778687 ROWS_OUT ................. 1 EST_TOTAL_COST ........... 0.2332 STATEMENT ................
Examples of EXPLAIN SQL/MX Statements NESTED_JOIN =============================== REQUESTS_IN .............. 1 ROWS_OUT ................. 1 EST_OPER_COST ............ 0.0001 EST_TOTAL_COST ........... 0.0372 cpu_cost ............... 0.0016 io_cost ................ 0.0372 msg_cost ............... 0 idle_cost .............. 0 probes ................. 1 DESCRIPTION fragment_id ............ 0 parent_frag ............ (none) fragment_type .......... master join_type .............. inner join_method ...........
Examples of EXPLAIN SQL/MX Statements PARTITION_ACCESS ========================== REQUESTS_IN .............. 1 ROWS_OUT ................. 1 EST_OPER_COST ............ 0.0008 EST_TOTAL_COST ........... 0.0165 cpu_cost ............... 0.0008 io_cost ................ 0.0165 msg_cost ............... 0 idle_cost .............. 0 probes ................. 1 DESCRIPTION fragment_id ............ 2 parent_frag ............ 0 fragment_type .......... dp2 buffer_size ....... 31,000 record_length ..........
Examples of EXPLAIN SQL/MX Statements INDEX_SCAN ================================ SEQ_NO 1 NO CHILDREN TABLE_NAME ............... CAT.SCH.PARTSUPP REQUESTS_IN .............. 1 ROWS_OUT ............... 100 EST_OPER_COST ............ 0.0206 EST_TOTAL_COST ........... 0.0206 cpu_cost ............... 0.0001 io_cost ................ 0.0206 msg_cost ............... 0 idle_cost .............. 0 probes ................. 1 DESCRIPTION fragment_id ............ 2 parent_frag ............ 0 fragment_type ..........
Examples of EXPLAIN SQL/MX Statements The following output is displayed: ------------------------------------------------------------------ PLAN SUMMARY MODULE_NAME .............. DYNAMICALLY COMPILED STATEMENT_NAME ........... XX PLAN_ID .................. 212122794829778687 ROWS_OUT ................. 1 EST_TOTAL_COST ........... 0.23 STATEMENT ................
Examples of EXPLAIN SQL/MX Statements FILE_SCAN_UNIQUE ========================== SEQ_NO 5 NO CHILDREN TABLE_NAME ............... CAT.SCH.PART REQUESTS_IN .............. 1 ROWS_OUT ................. 1 EST_OPER_COST ............ 0.02 EST_TOTAL_COST ........... 0.02 DESCRIPTION fragment_id ............ 3 parent_frag ............ 0 fragment_type .......... dp2 olt_optimization ....... not used olt_opt_lean ........... not used scan_type .............. unique access of table CAT.SCH.PART object_type .........
Examples of EXPLAIN SQL/MX Statements INDEX_SCAN ================================ SEQ_NO 1 NO CHILDREN TABLE_NAME ............... CAT.SCH.PARTSUPP REQUESTS_IN .............. 1 ROWS_OUT ............... 100 EST_OPER_COST ............ 0.02 EST_TOTAL_COST ........... 0.02 DESCRIPTION fragment_id ............ 2 parent_frag ............ 0 fragment_type .......... dp2 olt_optimization ....... not used olt_opt_lean ........... not used scan_type .............. full scan of index CAT.SCH.PSX2(CAT.SCH.
Examples of EXPLAIN SQL/MX Statements The following output is displayed: MODULE_NAME STATEMENT_NAME PLAN_ID SEQ_NUM OPERATOR LEFT_CHILD_SEQ_NUM RIGHT_CHILD_SEQ_NUM TNAME CARDINALITY OPERATOR_COST TOTAL_COST DETAIL_COST DESCRIPTION ------------------------------------------------------------ ----------------------------------------------------------- -------------------- ---------- ------------------------------ ------------------ ------------------ ---------------------------------------------------------
Examples of EXPLAIN SQL/MX Statements ? XX 212122794829778687 4 PARTITION_ACCESS 3 ? 1.0000000E+000 7.5787946E-004 1.6517225E-002 CPU_TIME: 0.000805815 IO_TIME: 0.0165172 MSG_TIME: 0 IDLETIME: 0 PROBES: 1 fragment_id: 2 parent_frag: 0 fragment_type: dp2 buffer_size: 31000 record_length: 8 space_usage: 12:8:8:32 eid_space_computation: on ? XX 212122794829778687 5 FILE_SCAN_UNIQUE ? ? CAT.SCH.PART 1.0000000E+000 2.0646531E-002 2.0646531E-002 CPU_TIME: 3.18424e-005 IO_TIME: 0.
Examples of EXPLAIN SQL/MX Statements • Use the EXPLAIN statement without the output options: >>explain xx; The following output is displayed: ------------------------------------------------------------------ PLAN SUMMARY MODULE_NAME .............. DYNAMICALLY COMPILED STATEMENT_NAME ........... XX PLAN_ID .................. 212122794829778687 ROWS_OUT ................. 1 EST_TOTAL_COST ........... 0.23 STATEMENT ................
Examples of EXPLAIN SQL/MX Statements FILE_SCAN_UNIQUE ========================== SEQ_NO 5 NO CHILDREN TABLE_NAME ............... CAT.SCH.PART REQUESTS_IN .............. 1 ROWS_OUT ................. 1 EST_OPER_COST ............ 0.02 EST_TOTAL_COST ........... 0.02 DESCRIPTION fragment_id ............ 3 parent_frag ............ 0 fragment_type .......... dp2 olt_optimization ....... not used olt_opt_lean ........... not used scan_type .............. unique access of table CAT.SCH.PART object_type .........
Examples of EXPLAIN SQL/MX Statements INDEX_SCAN ================================ SEQ_NO 1 NO CHILDREN TABLE_NAME ............... CAT.SCH.PARTSUPP REQUESTS_IN .............. 1 ROWS_OUT ............... 100 EST_OPER_COST ............ 0.02 EST_TOTAL_COST ........... 0.02 DESCRIPTION fragment_id ............ 2 parent_frag ............ 0 fragment_type .......... dp2 olt_optimization ....... not used olt_opt_lean ........... not used scan_type .............. full scan of index CAT.SCH.PSX2(CAT.SCH.
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-165 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-165. 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 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 ]...} [WITH GRANT OPTION] [BY authid-grantor] procedure-ref is: [[catalog-name.]schema-name.
Considerations for GRANT EXECUTE SQL/MX Statements 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. Only the super ID can use the BY clause. If another user attempts to do so, the system returns an error.
Examples of GRANT EXECUTE SQL/MX 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.BETTY' grants EXECUTE privilege on spj1 to some users in the HR group: GRANT EXECUTE ON PROCEDURE samdbcat.persnl.spj1 TO 'HR.MIKE', 'HR.JOE', '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-41. For the description of query-expr, see SELECT Statement on page 2-198. 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 disable INSERT_VSBB to use statement atomicity, because performance is affected. Perform UPDATE STATISTICS on the tables so that row estimates are correct. To see what rollback mode NonStop SQL/MX is choosing, you can prepare the query, and then use the EXPLAIN statement: explain options 'f' my_query; Token “x” means that the transaction will be rolled back. Token “s” means that NonStop SQL/MX will choose DP2 savepoints.
Considerations for INSERT SQL/MX Statements 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 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. Inserting Numeric Values Any numeric data type is compatible with all other numeric data types. If you insert a value into a numeric column that is not large enough, an overflow error occurs.
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-193 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-116. 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-219. 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 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 • • • • If both columns are of exact numeric data types, RESULT contains an exact numeric value whose precision and scale are equal to the greater of the two contributing columns. If both columns are of approximate numeric data types, RESULT contains an approximate numeric value whose precision is equal to the greater of the two contributing columns.
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.
SELECT ROW COUNT Statement SQL/MX Statements SELECT ROW COUNT Statement Considerations for SELECT ROW COUNT Limitations of SELECT ROW COUNT Example of SELECT ROW COUNT The SELECT ROW COUNT statement is used to retrieve the count of rows from an SQL/MX table. The SELECT ROW COUNT () query is sent to each disk process where a partition of the table resides and the count of rows is computed as a parallel SQL operation.
Example of SELECT ROW COUNT SQL/MX Statements • Records have been added, deleted, or moved from one or more partitions of the target table by a MODIFY operation (in this case, only the affected partitions are marked with an invalid row count). If partitions of a table are marked with an invalid row count, the row count can be reset by deleting all the rows from the affected partition(s) using either a DELETE or PURGEDATA statement. Note.
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 transaction mode is an option that can be set in a SET TRANSACTION statement. You cannot specify any of the options—isolation level, access mode, size of the diagnostics area, or autocommit—more than once within one SET TRANSACTION statement. You cannot use the AUTOCOMMIT option in combination with any other option.
Considerations for SET TRANSACTION SQL/MX Statements If you exit a program without executing COMMIT or without setting AUTOCOMMIT ON, any uncommitted changes are automatically rolled back. Embed AUTOCOMMIT is an SQL/MX extension and cannot be used in combination with any other option. autobegin-option specifies that NonStop SQL/MX can start implicit transactions when the statement runs.
Considerations for SET TRANSACTION SQL/MX Statements Embed • • Cursor declarations (both static and dynamic) DECLARE CATALOG and DECLARE SCHEMA In MXCI, the EXECUTE statement is transaction-initiating only if the statement that it executes is transaction-initiating. Explicit Transactions You can issue an explicit BEGIN WORK even if the autocommit option is on. The autocommit option is temporarily disabled until you explicitly issue COMMIT or ROLLBACK.
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-198.
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-13.
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-106.
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-53. 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 • DEFINE name See Database Object Names on page 6-13. 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 previously generated and stored in the table’s histogram tables. Histograms of column groups not specified in the ON clause remain unchanged in histogram tables. For more information about specifying columns, see Generating and Clearing Statistics for Columns on page 2-271.
UPDATE STATISTICS Statement SQL/MX Statements SAMPLE [sample-option] [SET ROWCOUNT c ][sample-tableclause] is an optional clause that specifies that sampling is to be used to gather a subset of the data from the table. UPDATE STATISTICS uses a temporary table to store the sample results and generates histograms. See Histogram Table Properties on page 10-82 for details.
Considerations for UPDATE STATISTICS SQL/MX Statements SET ROWCOUNT c is an optional clause that specifies the number of rows in the table. The value c must be an integer that is greater than or equal to zero (c > 0). If the ROWCOUNT clause in not specified, NonStop SQL/MX determines the number of rows in the table either by estimation or SELECT COUNT(*). See SAMPLE Clause on page 7-8. sample-table-clause USING SAMPLE TABLE WITH PARTITIONS directs SQL/MX to partition the temporary table.
Considerations for UPDATE STATISTICS SQL/MX Statements tables, or be the super ID, and have the authority to read the user table for which statistics are generated. Because the histogram tables are registered in the schema (for SQL/MX tables) or catalog (for SQL/MP) of the primary partition of table, you must have the authority to read and write to this schema or catalog. Then, when the two histogram tables are created, you become the owner of the tables.
Considerations for UPDATE STATISTICS SQL/MX Statements You can clear statistics in any combination of columns you specify, not necessarily with the column-group-list you used to create statistics. However, those statistics will remain until you clear them.
Considerations for UPDATE STATISTICS SQL/MX Statements You can also specify groups of columns. This command uses the system default for sample size, which is 2 percent of the total number of rows in the table or 2 million rows, whichever is less. • If big_table is highly skewed on certain columns (that is, a column has a large variance in the percentage of individual unique values), specify the sample size to be greater than the system default.
Examples of UPDATE STATISTICS SQL/MX Statements When you specify a sample-table-name, you must have ALL privileges on the temporary table and must own its schema or be the super ID. Note. The USING SAMPLE TABLE clause is not supported with SQL/MP tables. For more information on partitioned temporary tables, see the SQL/MX Query Guide.
Examples of UPDATE STATISTICS SQL/MX Statements • This example generates histogram statistics using the ON EVERY COLUMN option for the table DEPT. This statement performs a full scan, and the NonStop SQL/MX determines the default number of intervals. UPDATE STATISTICS FOR TABLE dept ON EVERY COLUMN; --- SQL operation complete. • This example generates statistics for a sample from table MAILINGS. The sample size is 7.3529 percent, and the number of rows in the table is 272,000.
Examples of UPDATE STATISTICS SQL/MX Statements • This example generates statistics for a sample from table MAILINGS. The sample size is 7.3529 percent and the number of rows in the table is 272,000. The records that are selected by sampling are stored in a temporary table, MY_SAMPLE_TABLE, which is specified by the user. The data in the temporary table is then used to generate the statistics. UPDATE STATISITCS FOR TABLE MAILINGS ON EVERY COLUMN SAMPLE RANDOM 7.
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.
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-33 Sets default schema for unqualified object names in static SQL statements within a compilation unit. DESCRIBE Statement on page 3-34 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-37 Designates the end of a Declare Section. EXEC SQL Directive on page 3-38 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-37.
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-33. 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-198 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-56. 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 static updatable cursor. The FOR UPDATE clause lists the columns to be updated: EXEC SQL DECLARE cursor1 CURSOR FOR SELECT COL1, COL2, COL3, COL4 FROM SALES.PARTS WHERE COL2 >= :hostvar2 READ COMMITTED ACCESS FOR UPDATE OF COL2, COL3, COL4; • This SQL statement defines a dynamic updatable cursor: EXEC SQL BEGIN DECLARE SECTION; CHAR query[50]; ... EXEC SQL END DECLARE SECTION; ...
Embedded-Only SQL/MX Statements COBOL Examples of DECLARE CURSOR ... EXEC SQL DECLARE getparts CURSOR FOR curspec END-EXEC.
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-51. 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-138.
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 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 the descriptor
Embedded-Only SQL/MX Statements Considerations for SET DESCRIPTOR 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 SET DESCRIPTOR 'in_desc3' VALUE :desc_val TYPE
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: ...
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-4 Creates DEFINEs for Guardian file names. ALTER DEFINE Command on page 4-6 Changes DEFINEs for Guardian file names. CD Command on page 4-8 Changes the current working directory.
MXCI Commands GET VERSION OF SYSTEM SCHEMA Command on page 4-39 Displays the system schema version of the specified node. GET VERSION OF Object Command on page 4-40 Displays the object schema version (OSV) and the object feature version (OFV) of the specified database object. GET VERSION OF MODULE Command on page 4-41 Displays the module version of the specified module. GET VERSION OF PROCEDURE Command on page 4-42 Displays the plan version of the specified procedure in the specified module.
MXCI Commands SH Command on page 4-71 Invokes the shell from MXCI. SHOW PARAM Command on page 4-72 Lists each parameter, and its value, defined in the current MXCI session. SHOW PREPARED Command on page 4-73 Displays the prepared statements in the current MXCI session. SHOW SESSION Command on page 4-74 Displays MXCI session attributes. You can also use ENV. SHOWCONTROL Command on page 4-76 Displays the access plan, controls, and system defaults in effect.
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 module-name is the name of the module to search for, enclosed in single quotes. NonStop SQL/MX searches all modules matching the pattern in /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.
Examples of DISPLAY USE OF MXCI Commands If the module could not be loaded because the module name is not valid or the module name is valid but has been corrupted, NonStop SQL/MX displays an error. If the module could not be loaded because the name is valid but the module cannot be found, NonStop SQL/MX displays a warning. 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.
Examples of DISPLAY USE OF MXCI Commands • Display use of a specified Guardian object in all modules: >>display use of object '\NODE1.$DATA08.ORDERS.T1'; Object: \NODE1.$DATA08.ORDERS.T1 Object: \NODE1.$DATA08.ORDERS.T1 Module: TANDEM_SYSTEM_NSK.SCH.INS1M Object: \NODE1.$DATA08.ORDERS.T1 Module: 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.
DISPLAY USE OF SOURCE MXCI Commands DISPLAY USE OF SOURCE Examples of DISPLAY USE OF Source The DISPLAY USE OF SOURCE Command displays the source SQL file (from which the module was created) for the given module.The syntax and utility of the new enhancement is as follows DISPLAY USE OF [NOE] [MODULE_DIR 'module-directory-path'] SOURCE ['module-name'] NOE directs NonStop SQL/MX to scan modules only in the local node and not the nodes on the Expand network.
Examples of DISPLAY USE OF Source MXCI Commands You can search 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.*.*M' Note. If you do not specify the module-name, the command displays the source SQL file name for all the modules.
DISPLAY USE OF ALL | INVALID MODULES MXCI Commands DISPLAY USE OF ALL | INVALID MODULES Considerations for DISPLAY USE OF ALL | INVALID MODULES Examples of ALL | INVALID MODULES If the INVALID keyword is specified in the command, it displays all the dependent modules along with their source SQL files for a given object that has become invalid because of the DDL changes to the object, after the module was created.
Considerations for DISPLAY USE OF ALL | INVALID MODULES MXCI Commands Note. The current design does not support SQL/MP aliases to know about the DDL changes performed on the underlying SQL/MP object. Hence, this command can consider a module to be valid even if the underlying SQL/MP object has been changed after the creation of the module. object-name is case-sensitive. Wild-card characters are not allowed. A valid example is: TPCC.OE.
Examples of ALL | INVALID MODULES MXCI Commands Examples of ALL | INVALID MODULES • Display invalid modules along with their corresponding source SQL files for a given object: >>display use of INVALID MODULES FOR ‘CAT.SCH.TABLE1’; Object: CAT.SCH.TABLE1 Module: CAT.SCH.MODTABLE1 Source Name: /E/NODE11/modulelist/module1.sql Module: CAT.SCH.MODTABLE2 Source Name: /E/NODE11/modulelist/module2.
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-116. 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-120. 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-44. 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.
GTACL Command MXCI Commands GTACL Command Considerations for GTACL Examples of GTACL The GTACL command allows you to run the TACL commands, such as, FUP, PSTATE, STATUS, TACL macros, programs, and utilities from the MXCI interface. Note. The GTACL command is available only on systems running J06.09 and later J-series RVUs and H06.20 and later H-series RVUs. This command is introduced to inherit the same property as provided in the gtacl command of the Open System Services (OSS) environment.
Examples of GTACL MXCI Commands The output is displayed as: gtacl[9]: warning: unable to propagate all environment variables Home terminal: $ZTN0.#PTMMMM5 TACL process: \NSAA12.$Z1QA Primary CPU: 2 (NSE-D) Default Segment File: $DATA02.#0000085 Pages allocated: 56 Pages Maximum: 1036 Bytes Used: 99116 (4%) Bytes Maximum: 2121728 Current volume: $DATA02.LAKDGTST Saved volume: $SYSTEM.SYSTEM Userid: 255,255 Username: SUPER.SUPER Security: "NUNU" Logon name: SUPER.
GET NAMES OF RELATED NODES Command MXCI Commands GET NAMES OF RELATED NODES Command The GET NAMES OF RELATED NODES command displays the names of the transitive closure of nodes that are related to the specified node. A node is related to another node if they have one or more catalogs in common. The specified node is included in the output. GET NAMES OF RELATED NODES [FOR node]; node is the node name for which the list of related nodes is requested. The default is the local node.
GET NAMES OF RELATED SCHEMAS Command MXCI Commands GET NAMES OF RELATED SCHEMAS Command The GET NAMES OF RELATED SCHEMAS command displays the names of the transitive closure of schemas related to the specified schema. Schemas are related if a view, a trigger, or a constraint in one schema references an object in the other schema. The specified schema is included in the output.
GET NAMES OF RELATED CATALOGS MXCI Commands GET NAMES OF RELATED CATALOGS The GET NAMES OF RELATED CATALOGS command displays the names of the transitive closure of catalogs related to the specified catalog. Catalogs are related if a view, a trigger, or a constraint in one catalog references an object in the other catalog. The specified catalog is included in the output.
GET VERSION OF SYSTEM MXCI Commands GET VERSION OF SYSTEM The GET VERSION OF SYSTEM command displays the SQL/MX Software Version (MXV) information of a specified node. If no node is specified, the MXV of the local node is returned. GET VERSION OF SYSTEM [ node ]; node is the node name for which the SQL/MX Software Version information is requested. The default is the local node.
GET VERSION OF SCHEMA Command MXCI Commands GET VERSION OF SCHEMA Command The GET VERSION OF SCHEMA command displays the schema version of the specified schema. GET VERSION OF SCHEMA schema-name; schema-name is the ANSI name of the schema for which the schema version is requested. There is no default for the schema-nam. However, the MXCI default catalog applies.
GET VERSION OF SYSTEM SCHEMA Command MXCI Commands GET VERSION OF SYSTEM SCHEMA Command The GET VERSION OF SYSTEM SCHEMA command displays the system schema version of the specified node. If no node is specified, the system schema version of the local node is displayed. GET VERSION OF SYSTEM SCHEMA [ ON node ]; node is the node name for which the system schema version information is requested. The default is the local node.
GET VERSION OF Object Command MXCI Commands GET VERSION OF Object Command The GET VERSION OF Object command displays the object schema version (OSV) and the object feature version (OFV) of the specified database object. GET VERSION OF object-type object-name; object-type is the type of object for which version information is requested. The following are the object types: • • • • • • • TABLE INDEX VIEW CONSTRAINT TRIGGER STORED PROCEDURE MPALIAS There is no default object type.
GET VERSION OF MODULE Command MXCI Commands GET VERSION OF MODULE Command The GET VERSION OF MODULE command displays the version of the specified module. GET VERSION OF MODULE 'module-name'; module-name is the name of the module for which the module version information is requested. There is no default for module-name, and MXCI default catalog and schema do not apply. If the module exists in an OSS directory other than USERMODULES, the full OSS path must be specified as the module name. Note.
GET VERSION OF PROCEDURE Command MXCI Commands GET VERSION OF PROCEDURE Command The GET VERSION OF PROCEDURE command displays the plan version of the specified procedure in the specified module. GET VERSION OF PROCEDURE ('module-name','procedure-name'); module-name is the name of the module for which version information is desired. There is no default for module-name and MXCI default catalog and schema do not apply.
GET VERSION OF STATEMENT Command MXCI Commands GET VERSION OF STATEMENT Command The GET VERSION OF STATEMENT command displays the plan version of the specified prepared statement. GET VERSION OF STATEMENT statement-name; statement-name is the name of a prepared statement for which plan version information is requested. There is no default for statement-name. The statement must have been previously prepared in the same MXCI session as the one where the GET VERSION command is issued.
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-30. 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]] | [RESULT [ONLY] ]} [CLEAR]] log_file is the name of a file to which MXCI writes the commands you use and the command output.
Considerations for LOG MXCI Commands Considerations for LOG Contents of the Log File The log file includes all lines you enter except FC editing lines, including the final version of any line you edit by using FC. It also includes the prompts for lines that you enter and all text that MXCI displays or prints in response to those lines, including output from commands and diagnostic messages—except for output from the CD, FC, HISTORY, LS, SH, GTACL, and ! commands.
Examples of LOG MXCI Commands *** ERROR[8822] The statement was not prepared.
Examples of LOG MXCI Commands HP NonStop SQL/MX Reference Manual—640322-001 4- 50
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-77. 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-106. 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—640322-001 4- 67
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-23.
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-77. 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-183.
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 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-83.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 Consequently, if a system-created index is implicitly created by the system to support a not droppable primary key constraint, the DDL output for explicitly creating such an index must be commented out, or a duplicate index results. • • • • • • • • • • • • • • SHOWDDL generates ALTER TABLE ADD COLUMN statements for each column that was added to the table.
Considerations for SHOWDDL MXCI Commands • • SHOWDDL always generates a Java signature for the SPJ. SHOWDDL does not display the GRANT and REVOKE statements used to grant or revoke any privileges on the table. 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.
Considerations for SHOWDDL MXCI Commands • • • • • • • • • • • For NUMERIC and SMALLINT data types, SIGNED does not appear because it is the default. Only UNSIGNED is displayed. DATETIME is not a supported data type in NonStop SQL/MX, but SHOWDDL displays this data type for SQL/MP tables that contain it. The largest MAXEXTENTS value for an SQL/MX table is 768, but it is 959 for NonStop SQL/MP. SHOWDDL displays the EXTENT and MAXEXTENTS only for the primary partition of an SQL/MP table or index.
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 ) EXTENT 48 MAXEXTENTS 300 PARTITION ( \FIGARO.$DATA14.DEANCAT.T1 FIRST KEY (5000), \FIGARO.$DATA15.DEANCAT.
Examples of SHOWDDL MXCI Commands , EXTENT (48, 48),MAXEXTENTS 300 PARTITION ( ADD FIRST KEY (10000) LOCATION \FIGARO.$DATA14 , ADD FIRST KEY (5000) LOCATION \FIGARO.$DATA15 ) ; CREATE INDEX IDXA ON T1 ( SID ASC ) LOCATION \FIGARO.$DATA17 PARTITION ( ADD FIRST KEY (100) LOCATION \FIGARO.$DATA14 , ADD FIRST KEY (1000) LOCATION \FIGARO.$DATA15 ) ATTRIBUTES NO AUDITCOMPRESS ; CREATE UNIQUE INDEX UIDX ON T1 ( SSN ASC ) LOCATION \FIGARO.
Examples of SHOWDDL MXCI Commands >>SHOWDDL T1, SQLMP CREATE TABLE \FIGARO.$DATA17.DEANCAT.T1 ( NAME CHAR(10) CHARACTER SET ISO88591 COLLATE DEFAULT DEFAULT 'nobody' HEADING 'NAME' , SID LARGEINT NO DEFAULT -- NOT NULL NOT DROPPABLE , SSN INT UNSIGNED NO DEFAULT -- NOT NULL NOT DROPPABLE , BIRTHDATE DATE NO DEFAULT -- NOT NULL NOT DROPPABLE , PRIMARY KEY (SID DESC) ) CATALOG \FIGARO.$DATA17.DEANCAT PARTITION ( \FIGARO.$DATA14.DEANCAT.T1 FIRST KEY 5000 ) ; CREATE CONSTRAINT C1 on \FIGARO.$DATA17.DEANCAT.
Examples of SHOWDDL MXCI Commands MYOLDROW, NEW AS MYNEWROW WHEN (MYNEWROW.D > MYOLDROW.D) SET MYNEWROW.B = MYNEWROW.B + MYOLDROW.D; ; • This is an example of SHOWDDL on a view. >>CREATE VIEW V1 AS SELECT keycol, valcol, ssn, salary FROM T2 TRANSPOSE SSN, salary AS valcol KEY BY keycol; >>SHOWDDL V1; 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.
Examples of SHOWDDL MXCI Commands • This is an example of SHOWDDL that reports the maximum number of result sets the sales.order_summary procedure returns. >>showddl samdbcat.sales.order_summary; CREATE PROCEDURE SAMDBCAT.SALES.ORDER_SUMMARY ( IN ON_OR_AFTER_DATE VARCHAR(20) CHARACTER SET ISO88591 , OUT NUM_ORDERS LARGEINT ) EXTERNAL NAME 'SPJMethods.orderSummary (java.lang.String,long[],java.sql.ResultSet[],java.sql.Result Set[])' EXTERNAL PATH '/usr/mydir/myclasses' LOCATION \ALPINE.$SYSTEM.ZSDCR2C6.
Examples of SHOWDDL MXCI Commands ) LOCATION \FIGARO.$DATA2.ZSDUXXBK.
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-36 and SET SHOWSHAPE Command on page 4-65. 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.
Examples of SHOWSHAPE MXCI Commands HP NonStop SQL/MX Reference Manual—640322-001 4 -108
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 mxtool Utility on page 5-111 Performs FIXUP, GOAWAY, and comment: INFO or VERIFY operations. POPULATE INDEX Utility on page 5-112 Loads indexes. PURGEDATA Utility on page 5-115 Purges data from tables, indexes, or partitions. RECOVER Utility on page 5-119 Determines the state of a failed utility operation and restores recoverable objects.
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.
DOWNGRADE Utility SQL/MX Utilities DOWNGRADE Utility Considerations for DOWNGRADE Example of DOWNGRADE DOWNGRADE is a syntax-based utility that can be executed through MXCI. The DOWNGRADE transforms all metadata that is visible on the local node from its existing version to the specified, lower schema version. This includes the schemas in the system catalog. The REPORTONLY option allows you to test if the operation can be executed without actually performing the operation.
Considerations for DOWNGRADE SQL/MX Utilities Otherwise, the output is appended to the existing contents of oss-file. The following is the format of the first line of log output: ************** Time:
Example of DOWNGRADE SQL/MX Utilities Error Conditions The following are the error conditions that might occur while executing the RECOVER command: • • • An involved node has an incompatible version (because the version of the node was changed between the time of the original operation and the time of recover) No corresponding UPGRADE or DOWNGRADE operation is recorded The original command is still active Example of DOWNGRADE This example transforms all the metadata to the 1200 SQL/MX version: DOWNGRAD
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 • DUP does not support RI constraints duplication. 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.
FASTCOPY Utility SQL/MX Utilities FASTCOPY Utility Considerations for FASTCOPY Examples of FASTCOPY FASTCOPY is a syntax-based utility that can be executed through MXCI and from a program using dynamic SQL. The RECOVER support is available for the FASTCOPY utility. FASTCOPY is not available as an embedded SQL. For more information about the FASTCOPY utility, see the SQL/MX Installation and Management Guide. Note. The FASTCOPY utility is available only on systems running J06.
FASTCOPY INDEX Command SQL/MX Utilities index-clause specifies how FASTCOPY TABLE will treat indexes. The index-clause has these values: EXPLICIT Indexes on the target table will be explicitly copied. For each matching pair of source and target indexes, the FASTCOPY INDEX Command can be used to explicitly perform the copy concurrently with the copy of the table, if required. Each target index must have a matching source index.
Considerations for FASTCOPY SQL/MX Utilities Equivalence Requirements • The target table and the source table must be equivalent so that the following command can be executed successfully: insert into (*) select * from ; Two tables must have the same number of columns. The columns with the same ordinal position must have compatible data types. Also, either both tables must a SYSKEY column or none of the tables must have a SYSKEY column.
Considerations for FASTCOPY SQL/MX Utilities • utility operations that modify the data or definition of the source table or its indexes Data in the target table are not available while executing the FASTCOPY TABLE or FASTCOPY INDEX command. Data in the target table can be accessed only after the FASTCOPY operation completes successfully. The definition of the target table(DDL) are available for read-only operations.
Considerations for FASTCOPY SQL/MX Utilities • DDL_LOCKS for target objects For target objects, the DDL_LOCKS row displays an operation value Fastcopy Target (FT). The status indicates the actual progress of the FASTCOPY of that particular target object. The status values are listed below: Value Description 1 A fastcopy operation is started. Audit is turned off and all target partitions (table and indexes) are marked "corrupt".
Examples of FASTCOPY SQL/MX Utilities Examples of FASTCOPY • Consider a source table ST with indexes SI1 and SI2 and the target table TT with index TI1. Run the following command: FASTCOPY TABLE ST TO TT INDEXES IMPLICIT; The command copies all the rows from the source table to the target table and automatically maintains index TI1 as part of that copying.
FIXRCB Operation SQL/MX Utilities FIXRCB Operation Error Conditions Example of FIXRCB Operation FIXRCB is an OSS command-line utility run from mxtool. It performs a Record Control Block (RCB) fixup for all the required database objects in catalogs that have an automatic reference on the local system. The command must be executed by the local super ID.
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 Programmatic Interfaces Output File Consideration 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.
import Utility SQL/MX Utilities import must be lowercase. catalog.schema.table specifies the fully qualified name of the destination table for the imported data. You must specify the catalog and schema names. To import data to the table mycat.mysch."%&*()", you must specify the delimited table name in the import command: import 'mycat.mysch."%&*()"' -I myinput.
import Utility SQL/MX Utilities -F first-row is the number of the first row (or record) to import. The first row of the input file is designated as the number 0. If you do not specify this number, import begins with the first row (which is the same as specifying -F 0). -FD field-delimiter specifies the single or multicharacter field delimiter for the file. The default delimiter is a comma (,). This parameter takes precedence over the field delimiter specified in a format file.
import Utility SQL/MX Utilities If the -LES option is specified and any -L, -XL, -E, -XE, -PM, -XM, or -SF options are also specified, the value(s) specified for the individual options overrides the default value, which the -LES option establishes. The default values established by the -LES option is applicable for any of the seven individual options, which are not specified on the command line.
import Utility SQL/MX Utilities Note. If the -PM option is used, you must also consider the space consumed by the error message log file when choosing the -L value. Each error message will take at least 80 bytes and may be much longer if the error message includes specified column data,and so on. -QL field-qualifier specifies a single character field qualifier. The default qualifier is double quote ("). This parameter takes precedence over the field qualifier specified in a format file.
import Utility SQL/MX Utilities with an appropriate error message. If the -SF option is not specified, the summary information will not be generated. If only -SF is specified (without file name), the results summary information is written to Stdout at the completion of the import operation. Any positive value specified for the -SI option is ignored because the process responsible for updating the four lines of progress information cannot access Stdout for the import process.
import Utility SQL/MX Utilities -W file-type specifies the input file type. The possible values for file-type are DELIM and FIXED. If you do not specify this parameter, import assumes the default DELIM file type (a delimited input file). If you do not specify this parameter and there is no format file, import assumes the default delimiters for a delimited input file. If you use the -W option, it must follow the -IP option on the command line.
import Utility SQL/MX Utilities -XL max-exec-errors is an option that directs import to ignore the specified number max-execerrors (from 0 to 2147483646) of ignorable execution errors without terminating. If the number of execution errors detected by import exceeds max-execerrors, import shall terminate, although because of internal bundling of multiple rows for insertion, import may report several more than max-exec-errors detected when it does terminate.
Considerations for import SQL/MX Utilities The error messages written to exec-errormsg-filename will not have any row number in them to indicate the row in the input file or in exec-error-filename associated with the error message. Regardless of whether exec-errormsg-filename and exec-errorfilename are the same file, if you invoke import again with exec-errorfilename as the input file, the same format file can be used. Any interspersed error messages will be automatically ignored by import.
Considerations for import SQL/MX Utilities import operation with the fast-loading technique is being performed, the second operation fails with a concurrent access error. If you turn off auditing for the table, online dumps are invalidated. After the import operation completes, you must perform a new TMF online dump for all partitions of the table.
Considerations for import SQL/MX Utilities 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. Concurrent import operations are not allowed. Concurrent DML, DDL, and utility operations are also not allowed. If import is not using fast-loading techniques, all DML operations (SELECT, UPDATE, DELETE, INSERT) can be performed concurrently.
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-42. 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.
Programmatic Interfaces 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.
Programmatic Interfaces SQL/MX Utilities Note. In Release 2.0, under these conditions, import wrote a message to Stdout displaying how many rows were imported, but did not write a message displaying "Import Completed …" In Release 2.X, import will do the same. import sets the exit status code to 30 if the input file is readable, but is a zero-length file. (No success and no ignorable errors). Note. In Release 2.
Output File Consideration SQL/MX Utilities 30 No success and no ignorable errors 40 No success and ignorable errors encountered 50 No success and a serious problem encountered 70 Serious problems that prevent the import from starting 90 Invalid option or combination of options File permissions When import creates any of the error output files, import ensures that the permissions are set so that read and write permission is granted only for the current user and his/her group because these files m
Output File Consideration SQL/MX Utilities 1. The format of numbers may be changed. For example: 123456.7 in the original input file may appear as 1.234567E+05 in the error log file. 2. The value of some floating point numbers may not be exactly the same (though extremely close). This is due to an internal conversion to binary format and then back to floating point ASCII format for logging to the error log file. 3.
Examples of import SQL/MX Utilities Examples of import • Example 1 shows an import of data from a delimited file. This example shows the schema of the table to be loaded, the data to be loaded (the input data file), the format file describing the data, and the import command used to load it.
Examples of import SQL/MX Utilities This import command imports data into the COMPANY table from the delimited input file named COINPUT using the format file FORMFILE: import cat.sch.company -I coinput -U formfile -W DELIM • Example 2 shows an import into the same COMPANY table from a fixed width file. This example shows the data to be loaded (the input data file), the format file describing the data, and the import command used to load it.
Examples of import SQL/MX Utilities table to be loaded, the data to be loaded (the input data file), the format file describing the data, and the import command used to load it. Table Schema This statement creates the TABLE_2 table: CREATE TABLE table_2 (COL1 CHAR(5) ); Data to Input The input file, COINPUT_FX2, contains records like this: 0123456789012345 ABCDEFGHIJKLMNPQ 0123456789012345 Three hidden spaces are at the end of each line.
Examples of import SQL/MX Utilities Data to Input Suppose you have an input file named X.in , containing the following 10 lines 11,12345678 A8,22345678 11,82345678 14,423456789 17,52345678,9 15,62345678 27,72345678 5,32345678 BZ,XYZ 55,12345678 Execute the following command: import cat.sch.Xample -i X.in -L 50 X.perrmsg \ -XL 5 -XE X.xerrs -XM X.xerrmsg \ -SF X.sum -SI 10 -E X.perrs -PM Output NonStop SQL/MX Import Utility 2.3 (c) Copyright 2007 Hewlett-Packard Development Company, LP.
Examples of import SQL/MX Utilities The X.perrs file would contain: A8,22345678 14,423456789 17,52345678,9 BZ,XYZ The X.perrmsg file would contain: *** ERROR[20081] Row number 2 and column number 1 could not be processed. Column Data: A8 *** ERROR[20291] The data specified in row number 4 column number 2 is longer than the actual column size definition. Column Data:123456789. *** ERROR[20070] Columns in the datafile are not correct.
Examples of import SQL/MX Utilities The results summary file, X.sum, would contain: Import Results Summary Import Process ID: 4060 Input File or Process Name: X.in Start time: Mon Oct 15 13:12:43 2007 Rows to be skipped initially: 0 Rows read so far = 10 Rows skipped = 0 Elapsed time = 0:0:0.088011 Elapsed time since skipping initial rows = 0:0:0.088011 Rows Imported Successfully = 4 Rows ignored due to parsing errors = 4 Rows ignored due to execution errors = 2 Parsing Error Log File Name: X.
Examples of import SQL/MX Utilities • Example 5 illustrate –LES options, which takes default value of 1000 each for –L and –XL and auto generates the output error file and error message file and prints the summary to the stdout at the end. import cat.sch.Xample -I x.in -LES NonStop SQL/MX Import Utility 2.3 (c) Copyright 2007 Hewlett-Packard Development Company, LP. Rows Imported = 4 Import Results Summary Import Process ID: 5380 Input File or Process Name: x.
Examples of import SQL/MX Utilities • • • • • • The number of rows imported successfully. A line saying "Import Completed Successfully" or "Import Completed with non-fatal errors" if import has reached the end of the input data without encountering any non-ignorable errors. The name for the parsing error log file (if any). The name for the parsing error message log file (if any). The name for the execution error log file (if any). The name for the execution error message log file (if any).
Examples of import SQL/MX Utilities import with the original input file (using the -F option). The parsing errors and/or execution errors will still be detected for those rows. The easiest way to handle such rows would be to delete them from the error log before using it as an input file and fix those rows in the original input file before restarting import with the original input file (using the -F option).
Examples of import SQL/MX Utilities A sample results summary file is as follows: Note. The lines that can be repeated are shown in bold in the following sample summary file. Input File or Process Name: myinput_for_MYTABLE Start time: Mon May 2 15:33:13 CDT 2005 Rows to be skipped initially: 201986 Rows read so far = 2579352 Rows skipped = 359827 Elapsed time = 01:46:37.
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-87 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] | NAME partition-name | [KEY=] {FIRST | LAST} PARTITION | [KEY=] key-value is a location for a partition or a name 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-87 for details about limitations on online operations.
SQL/MX Utilities Manage Partitions of Range Partitioned Tables and Indexes The form of MODIFY for range partitioned tables and indexes is: MODIFY { TABLE | INDEX } [[catalog.]schema.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities commit-options is: { COMMIT [ WORK ] { { [ { ROLLBACK [WORK] [ WHEN READY ] [on-error]} [ { 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 partition-identification describes the partition. | | | LOCATION [\node.]$volume[.subvolume.file-name] NAME partition-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 Range Partitioned Tables and Indexes 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 extent size values of the source partition. See EXTENT on page 8-6 and MAXEXTENTS on page 8-7.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities RECLAIM | NO RECLAIM specifies whether SQL/MX should automatically start ORSERV processes to reclaim unused freespace in affected partitions (RECLAIM) or whether the user must manually perform FUP RELOAD operations (NO RECLAIM). Partitions that contain unused freespace have the UNRECLAIMEDSPACE (F) flag set in the file label.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities new-partition is: LOCATION [\node.]$volume[.subvolume.file-name] is: WITH SHARED ACCESS [commit-options] commit-options is: { COMMIT [WORK] [ WHEN READY ] { [ { AFTER time } ] { [ { BEFORE time } ] { ROLLBACK [WORK] } on-error is: [ ONCOMMITERROR commit-options ] [on-error] } } } [[catalog.]schema.]object is the name of the object.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities | [\node.]$volume [\node.]$volume.subvolume.file-name is the physical location of a partition. If you do not specify the file name, only one partition can exist for the given data source. \node can be either the local node or a remote node. If you do not specify \node, the default is the Guardian system named in your =_DEFAULTS define.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities new-partition is a disk volume or a Guardian file for the new partition. If you use disk volume syntax, MODIFY generates the file suffix name part. The specified new partition can be on the local system or a remote system. new-partition-name is a SQL identifier for a partition. partition-size is the size of the new partition. partition-extent-size [ MAXEXTENTS num-extents ] is the size of the new partition.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities new-partition-name is a SQL identifier for a partition. partition-size is the size of the new partition. partition-extent-size [ MAXEXTENTS num-extents ] is the size of the new partition. You can specify the sizes of the primary and secondary extents and the maximum number of extents. If you do not specify MAXEXTENTS, MODIFY uses the largest maxextents size possible using the combination of primary, secondary and max extent values.
Manage System-Clustered Tables SQL/MX Utilities ROLLBACK WORK. time is a Datetime value. Example of time: '2005-0216 14:00:00' ROLLBACK [WORK] specifies that the operation should be terminated. The effect is the same as issuing a separate RECOVER command with the CANCEL option. ROLLBACK WORK may only be specified in the last on-error clause. ONCOMMITERROR commit-options specifies what action SQL/MX should take if a retryable error occurs during Commit Phase.
Manage System-Clustered Tables SQL/MX Utilities You can use MODIFY to move the existing partition of a system-clustered object to a new location. Note that a system-clustered table can have only a single partition. Only offline partition operations are supported. The form of MODIFY for system-clustered objects is: MODIFY TABLE [[catalog.]schema.]table MOVE [PARTITION] [TO] { new-location [new-name] [partition-size] | new-name} new-location is: LOCATION [\node.]$volume[.subvolume.
Considerations for MODIFY SQL/MX Utilities primary extent and that of secondary extents separately. If you do not specify EXTENT, MODIFY uses the extent size values of the largest partition. See EXTENT on page 8-6 and MAXEXTENTS on page 8-7. Considerations for MODIFY • • • You must be the owner of a schema to run MODIFY against it. You can run MODIFY as either an offline or online operation. You can perform online operations while the partition is being used by another application.
Considerations for MODIFY SQL/MX Utilities • • • Splitting an existing partition and then merging the first or last part of the data to an existing adjacent partition. Merging two adjacent partitions into one. Reusing an existing partition by setting the FIRST KEY values of the partition to new values. You can optionally remove existing data in the partition to be reused.
Considerations for MODIFY SQL/MX Utilities If the attribute neither appears in the SYSTEM_DEFAULTS table nor is specified using a CONTROL QUERY DEFAULT statement, MODIFY uses the value 5000 for offline partition operations and 400 for online partition operations. Default Value for Offline Partition Operations For offline partition operations, MODIFY locks entire source and target partitions, so DP2 lock escalation is not an issue. In general, MODIFY runs more efficiently when you specify a larger value.
Examples of MODIFY SQL/MX Utilities the ORSERV process started by the reload operation might still open the physical file a bit longer (about five minutes) even though FUP STATUS already returns the RELOAD COMPLETED message. 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-95.
Examples of MODIFY SQL/MX Utilities TO LOCATION $data02 EXTENT (512, 512) MAXEXTENTS 256; • Move the second partition of a hash partitioned table to a new location: MODIFY TABLE tab1 MOVE PARTITION WHERE KEY = VALUE (2) TO LOCATION $DATA02; • Move a partition of a hash partitioned table from $data02 to $data03: MODIFY TABLE tab1 MOVE PARTITION WHERE LOCATION $data02 TO LOCATION $data03 EXTENT (1024, 1024) MAXEXTENTS 256; • Modify table with an online operation MODIFY TABLE MODT408A05 ADD PARTITION W
mxexportddl Utility SQL/MX Utilities mxexportddl Utility Considerations for mxexportddl Examples of mxexportddl mxexportddl is an OSS command-line utility that captures the metadata and statistics of SQL/MX objects and saves them in the XML format. This utility supports OSS large files (files greater than 2 GB) as output files. It is used to export the: • • SQL/MX object metadata to an XML file for DDL replication SQL/MX table statistics to an XML file for statistics replication Note.
mxexportddl Utility SQL/MX Utilities • • • A constraint cannot be specified explicitly in the mxexportddl utility. To export a constraint, the table including the constraint must be exported. The constraints that are exported vary depending on whether the CONSTRAINTS option is set to ON or OFF. Views can be implicitly exported with the entire schema and not only by the table. System defaults are always exported.
mxexportddl Utility SQL/MX Utilities -TAB | -TABLE is the object type for a table. The sqlmx-object-name-list is: ( sqlmx-object-name [sqlmx-object-name] ... ) sqlmx-object-name is a fully-qualified SQL/MX object name of the specified sqlmx-object-type. The specified object and all subordinate objects are exported. Wild cards are not permitted in the sqlmx-object-name. For delimited names, use ' \" ' to represent a quote. If a schema is "CATALOG"."SCHEMA", you must represent the schema as \"CATALOG\".
Considerations for mxexportddl SQL/MX Utilities -CLEAR ON |OFF specifies if the mxexportddl utility can overwrite the specified XML file if it already exists. The default is OFF. ON overwrites the specified XML file if it already exists. OFF does not overwrite the specified XML file. If the file already exists, the write operation fails. Considerations for mxexportddl You must be the super ID or schema owner to run mxexportddl. You can edit the XML file manually using simple text editors.
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.
mximportddl Utility SQL/MX Utilities mximportddl Utility Considerations for mximportddl Examples of mximportddl mximportddl is an OSS command-line utility that replicates the DDL definition and statistics of SQL/MX objects. It is used to import the: • • SQL/MX object metadata from an XML file for DDL replication SQL/MX table statistics from an XML file for statistics replication Note. The mximportddl utility is available only on systems running J06.07 and later Jseries RVUs and H06.
mximportddl Utility SQL/MX Utilities • • • • Referential integrity constraints, views, triggers, and stored procedures are referred to as dependency objects. The dependency objects are imported at the end of the mximportddl utility to ensure that all parent objects are imported in advance. The SHOWDDL ON and SHOWDDLLOC options are provided, the DDL of dependency objects will be written to OSS files. This can be used to manually create the objects later. Dependency objects will not be imported.
mximportddl Utility SQL/MX Utilities ( sqlmx-object-type sqlmx-object-name-list [ sqlmx-object-type sqlmx-object-name-list] ... ) The sqlmx-object-type is one of these object types: { -CAT | -CATALOG } { -SCH | -SCHEMA } { -TAB | -TABLE } -CAT | -CATALOG is the object type for a catalog. -SCH | -SCHEMA is the object type for a schema. -TAB | -TABLE is the object type for a table. The sqlmx-object-name-list is: ( sqlmx-object-name [sqlmx-object-name] ...
mximportddl Utility SQL/MX Utilities -MAPFILE or -MAP map-file-name specifies the name of the MAP file. map-file-name must be a valid OSS file name. While importing the XML file, MAP file can be used to map the source catalog or schema to a target catalog or schema. Also, the source node name and volume can be mapped to the target node name and volume. The MAP file template can be generated for the specific XML file, by specifying -PREPAREMAP in the mximportddl utility.
mximportddl Utility SQL/MX Utilities OFF does not import the statistics of the tables. Only the metadata of the SQL/MX objects is imported. -CLEAR ON |OFF specifies if the mximportddl utility can overwrite the specified MAP file if it already exists and -PREPAREMAP is provided. The default is OFF. ON overwrites the specified MAP file if it already exists. OFF does not overwrite the specified MAP file. If the file already exists, the write operation fails.
mximportddl Utility SQL/MX Utilities -KEEPSTATS ON | OFF specifies whether the mximportddl utility should retain the statistics of target tables if they already exist. The default is ON. ON imports the statistics only if the target table does not have statistics. OFF imports the statistics even if the target table already has statistics. The existing statistics will be deleted before importing the statistics. -LISTONLY ON | OFF lists the SQL/MX objects in the specified XML file. Object is not imported.
Considerations for mximportddl SQL/MX Utilities SQL/MX objects. The generated files are named as shown in the following table: File Name Purpose Subordinate object of... SHOWDDLn_RI_Constraints Referential integrity Table SHOWDDLn_Stored_Procedur es Java stored procedures Schema SHOWDDLn_Triggers Triggers Table SHOWDDLn_Views Views Schema n starts at 0 and increments by one. A new file is created every time when the current file becomes full.
Examples of mximportddl SQL/MX Utilities • • • Constraints: check, not null, primary key, and unique Table statistics that includes physical statistics (index level, nonempty block count, and EOF), histograms, and histogram intervals Referential integrity constraints, views, triggers, and stored procedures Not Supported by mximportddl • • System defaults SQL/MP tables and aliases Examples of mximportddl • To import the catalog cat1 and schema cat2.sch1 and cat2.
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 Syntax Description of POPULATE INDEX 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 table-name [option] index-name ::= name table-name ::= [[catalog.]schema.
Considerations for POPULATE INDEX SQL/MX Utilities COMMIT [WORK] [ WHEN READY ] [ { AFTER time [ { BEFORE time } ] [on-error] } ] specifies the time at which the Commit Phase should occur. COMMIT WHEN READY specifies that the Commit Phase should occur at the earliest possible time. COMMIT AFTER time specifies that the Commit Phase should occur after the given time. COMMIT BEFORE time specifies that the Commit Phase should occur before the given time.
Examples of POPULATE INDEX SQL/MX Utilities resource unavailability, and missing a BEFORE or AFTER time window. Some errors are retried automatically. Errors detected during the COMMIT phase are retried based on the ONCOMMITERROR clause. Errors detected during the initial and the data movement phases are retried individually and may include retry counts.
PURGEDATA Utility SQL/MX Utilities PURGEDATA Utility Syntax Description of PURGEDATA 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 indexes. If you specify this clause, PURGEDATA purges data from the partitions in 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.
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 • Purgedata does not allow you to purge data from a referred table. 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.
RECOVER Utility SQL/MX Utilities RECOVER Utility Syntax Description of RECOVER 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.
UPGRADE Utility SQL/MX Utilities UPGRADE Utility Considerations for UPGRADE Example of UPGRADE UPGRADE is a syntax-based utility that can be executed through MXCI. The UPGRADE utility transforms all metadata that is visible on the local node from its existing version to the current schema version for the SQL/MX software version (MXV). This includes the schemas in the system catalog. The REPORTONLY option allows you to test if the operation can be executed without actually performing the operation.
Considerations for UPGRADE SQL/MX Utilities Log file messages correspond to the EMS event messages. Regardless of the LOG TO option, the UPGRADE utility will generate EMS events to the $0 primary collector that documents the progress of the command. For information about error messages, see the SQL/MX Messages Manual.
Example of UPGRADE SQL/MX Utilities Example of UPGRADE This example transforms all the metadata to the /usr/dbadmin/upgradeLog file: UPGRADE ALL METADATA LOG TO OUTFILE /usr/dbadmin/upgradeLog CLEAR; The following is an excerpt from the output file. *************** Time:
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-95. 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 • • Triggers on page 6-112 Views on page 6-112 HP NonStop SQL/MX Reference Manual—640322-001 6 -2
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-4. 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-4. • 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-22 Fixed-length and variable-length character data types. Datetime Data Types on page 6-25 DATE, TIME, and TIMESTAMP data types. Interval Data Types on page 6-31 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 Considerations for Extended NUMERIC Precision Data Type • • • • Supported in all DDL and DML statements where an ordinary NUMERIC data type is supported. ° MX tables only Supported from the MXCI, ODBC, JDBC T2 and T4 interfaces. Does not support for host variable declarations in embedded programs. CAST function allows conversion between an ordinary NUMERIC and extended NUMERIC precision data type.
Comparable and Compatible Data Types SQL/MX Language Elements SPACE SQRT STDDEV SUBSTRING SUM TAN TANH THIS VARIANCE Restrictions for Extended NUMERIC Precision Data Type The extended NUMERIC precision data type is not supported: • • On the disk for SQL/MP tables By Module File caching (MFC) Example for Extended NUMERIC Precision Data Type >>create table t( n NUMERIC(128,30)); --- SQL operation complete. >> >>showddl table t; CREATE TABLE CAT.SCH.T ( N ) ..... ..... ..... .....
Comparable and Compatible Data Types SQL/MX Language Elements In this example, you are able to perform an ALTER TABLE statement in SQLCI on an SQL/MP table to add a float column with a default value near the boundary value for Tandem float values, but you are unable to use NonStop SQL/MX to insert this default value into the float column. In SQLCI, create an SQL/MP table: >>create table tfloat (c1 INT, c2 INT); --- SQL operation complete. >>insert into tfloat (c1) values (10); --- 1 row(s) inserted.
SQL/MX Language Elements Character String Data Types 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. You cannot compare character data to numeric, datetime, or interval data.
SQL/MX Language Elements Character String Data Types 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. You can specify the number of characters in a PIC X column by specify either length or multiple Xs, with each X representing one character position. DISPLAY does not change the meaning of the clause.
Character String Data Types SQL/MX Language Elements If you do not want to have blanks added to your character string, you can specify a variable-length character column as VARCHAR(n), where n is the maximum number of characters you want to store. If you store five characters in a column specified as VARCHAR(10), only the five characters are stored logically—without blank padding. When you are creating SQL/MP tables, group all variable-length columns after all fixed-length columns for faster access.
SQL/MX Language Elements Datetime Data Types For SQL/MP tables, a character data type has an associated character set and collation that can be implicitly or explicitly specified. The CHAR data type can be associated with any of the character sets, and the NCHAR data type is typically associated with the KANJI and KSC5601character sets. For more information, see Character Sets on page 6-4 and Database Object Names on page 6-13.
SQL/MX Language Elements Datetime Data Types SQL/MP Considerations for Datetime Data Types Not Equivalent to DATE, TIME, TIMESTAMP SQL/MP Considerations for Datetime Data Types Equivalent to DATE, TIME, TIMESTAMP A value of datetime data type represents a point in time according to the Gregorian calendar and a 24-hour clock in local civil time (LCT). A datetime item can represent a date, a time, or a date and time.
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 this example, the SQL/MP column of type INTERVAL SECOND(2) TO FRACTION(1) is interpreted in NonStop SQL/MX as type INTERVAL SECOND(2,1). 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.
SQL/MX Language Elements Numeric Data Types Exact numeric data types are types that can represent a value exactly: NUMERIC, SMALLINT, INTEGER, LARGEINT, DECIMAL, and PICTURE COMMENT:. Approximate numeric data types are types that do not necessarily represent a value exactly: FLOAT, REAL, and DOUBLE PRECISION. 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/MX Language Elements Numeric Data Types LARGEINT specifies an exact numeric column—an eight-byte signed binary integer. The column stores integers in the range -2**63 to 2**63 -1 (approximately 9.223 times 10 to the eighteenth power). DEC[IMAL] [(precision [,scale])] [SIGNED|UNSIGNED] specifies an exact numeric column—a decimal number, SIGNED or UNSIGNED,stored as ASCII characters. precision specifies the total number of digits and cannot exceed 18.
SQL/MX Language Elements Numeric Data Types REAL specifies a 4-byte approximate numeric column. The column stores 32-bit floating-point numbers with 23 bits of binary precision and 8 bits of exponent. The minimum and maximum range is from +/- 1.17549435e-38 through +/ 3.40282347e+38. DOUBLE PRECISION specifies an 8-byte approximate numeric column. The column stores 64-bit floating-point numbers and designates from 1 through 52 bits of precision.
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-41 Operands can be combined with the concatenation operator (||). Example: 'HOUSTON,' ||' TEXAS' Datetime Value Expressions on page 6-43 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 Not supported (error) Yes NOT DROPPABLE If STORE BY column list is a prefix of or the same as the primary key column list, NonStop SQL/MX uses the primary key column list. Other combinations are not supported and generate errors.
SQL/MX Language Elements Index Keys 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 nonunique index, the clustering key of the index is composed of columns specified in create index and the clustering key of the table. The clustering key of the index cannot exceed 2010 bytes for 4K blocks and 2048 bytes for 32K blocks. Because the entire row of the index is the clustering key of the index, the entire row of the index cannot exceed 2010 bytes for 4K blocks and 2048 bytes for 32K blocks. For more information, see Table 6-2 on page 6-61.
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-64 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-4.
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-25. 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. You cannot use leading or trailing spaces within a datetime string (within the single quotes).
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 128 digits (0 through 9), and an optional period (.) that indicates a decimal point. Leading zeros do not count toward the 128-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-62 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-60. For more information on this feature, see Creating Partitions Automatically on page 2-94. 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 one or more base tables or other views. The specification is a SELECT statement that is executed whenever the view is referenced. 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 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_DATE specifies the default value for the column as the value returned by the CURRENT_DATE 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 DATE. 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.
Examples of DEFAULT SQL/MX Clauses column data-type NOT NULL NOT DROPPABLE No default. column data-type NOT NULL Default null when NOT_NULL_ CONSTRAINT_DROPPABLE_OPTION is set to ON. column data-type NOT NULL No default when NOT_NULL_ CONSTRAINT_DROPPABLE_OPTION is set to OFF (the default). See CREATE TABLE Statement on page 2-77.
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-83 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. The SAMPLE clause always uses READ UNCOMMITTED access mode. It overrides the user specified access mode. See SELECT Statement on page 2-198.
SAMPLE Clause SQL/MX Clauses percent-result PERCENT [ROWS | {CLUSTERS OF number-blocks BLOCKS}] | BALANCE WHEN condition THEN percent-result PERCENT [ROWS] [WHEN condition THEN percent-result PERCENT [ROWS]]... [ELSE percent-result PERCENT [ROWS]] END specifies the value of the size for RANDOM sampling by using a percent of the result table. The value percent-result must be a numeric literal. You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table.
Considerations for SAMPLE SQL/MX Clauses number-rows ROWS | BALANCE WHEN condition THEN number-rows ROWS [WHEN condition THEN number-rows ROWS]... [ELSE number-rows ROWS] END specifies the value of the size for FIRST sampling by using the number of rows intended in the sample. The value number-rows must be an integer literal. You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table.
Examples of SAMPLE SQL/MX Clauses in the file in which a table is stored. The number of blocks in a cluster is specified in the CLUSTERS subclause of the SAMPLE RANDOM clause. For example: SELECT * FROM customers SAMPLE RANDOM 1 PERCENT CLUSTERS OF 2 BLOCKS; This query randomly selects one percent of the clusters in the CUSTOMERS table and then adds each row in all selected clusters to the result table.
Examples of SAMPLE SQL/MX Clauses ,amount NUMERIC (9,2) UNSIGNED ,PRIMARY KEY (empid) ); CREATE TABLE $db.mining.dept ( dnum NUMERIC (4) UNSIGNED NOT NULL ,name VARCHAR (20) ,PRIMARY KEY (dnum) ); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.salesperson $db.mining.salesper; CREATE SQLMP ALIAS db.mining.sales $db.mining.sales; CREATE SQLMP ALIAS db.mining.department $db.mining.
Examples of SAMPLE SQL/MX Clauses • Return the SALARY of the youngest five sales people, skip the next 15 rows, and repeat this process until there are no more rows in the intermediate result table. Note that you cannot specify periodic sampling with the sample size larger than the period. SELECT salary FROM salesperson SAMPLE PERIODIC 5 ROWS EVERY 20 ROWS SORT BY age; SALARY ----------90000.00 90000.00 28000.00 27000.12 136000.00 36000.00 ... --- 17 row(s) selected.
Examples of SAMPLE SQL/MX Clauses For this query execution, the number of rows returned is limited by the total number of rows in the SALESPERSON table. Therefore, it is possible that no rows are returned, and the result is null. • This query illustrates sampling after execution of the WHERE clause has chosen the qualifying rows. The query computes the average salary of a random 10 percent of the sales people over 35 years of age.
Examples of SAMPLE SQL/MX Clauses Note that the results of this query and some of the results of previous queries might return null: SELECT AVG(salary) FROM ( SELECT salary, dnum FROM salesperson SAMPLE RANDOM 10 PERCENT ) AS S, department D WHERE S.DNUM = D.DNUM AND D.NAME = 'CORPORATE'; (EXPR) -------------------? --- 1 row(s) selected. 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.
Examples of SAMPLE SQL/MX Clauses 32 32 ... GRAPHICPRINTER, M2 GRAPHICPRINTER, M2 ... S S ... 15000.00 15000.00 ... --- 88 row(s) selected. • 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 ...
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-198. 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—640322-001 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 or 32768 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—640322-001 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-85 Replaces the leftmost specified number of characters in a character expression with a padding character. LTRIM Function on page 9-88 Removes leading spaces from a character string. OCTET_LENGTH Function on page 9-109 Returns the length of a character string in bytes. POSITION Function on page 9-113 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-33 Converts a Julian timestamp to a TIMESTAMP value. CURRENT Function on page 9-37 Returns the current timestamp. You can also use the CURRENT_TIMESTAMP Function. CURRENT_DATE Function on page 9-38 Returns the current date. CURRENT_TIME Function on page 9-39 Returns the current time.
Mathematical Functions SQL/MX Functions and Expressions MONTH Function on page 9-93 Returns an integer value in the range 1 through 12 that represents the corresponding month of the year. MONTHNAME Function on page 9-94 Returns a character literal that is the name of the month of the year (January, February, and so on). QUARTER Function on page 9-115 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-54 Returns the exponential value (to the base e) of a numeric value expression. FLOOR Function on page 9-66 Returns the largest integer less than or equal to a numeric value expression. LOG Function on page 9-79 Returns the natural logarithm of a numeric value expression. LOG10 Function on page 9-79 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-48 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-145 Returns the sum of nonnull values of a column expression up to and including the current row. RUNNINGVARIANCE Function on page 9-147 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-74 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: COMPILERCONTROL S Function on page 9-28 Retrieves the active control settings, such as, CQDs, CTs, CQS from the compiler.
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-41.
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-52. 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-52. 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 The contents of the character string to be converted must be consistent in meaning with the data type of the result. For example, if you are converting to DATE, the contents of the character string must be 10 characters consisting of the year, a hyphen, the month, another hyphen, and the day. • • • • • A date value to a character string or to a TIMESTAMP (NonStop SQL/MX fills in the time part with 00:00:00.00).
SQL/MX Functions and Expressions • CEILING Function Suppose that your database includes a log file of user information. This example converts the current timestamp to a character string and concatenates the result to a character literal. Note the length must be specified. INSERT INTO stats.
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.
COMPILERCONTROLS Function SQL/MX Functions and Expressions COMPILERCONTROLS Function Considerations for COMPILERCONTROLS Examples of COMPILERCONTROLS The COMPILERCONTROLS function is an SQL/MX extension. The COMPILERCONTROLS 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. The syntax for the COMPILERCONTROLS function has no parameters.
Examples of COMPILERCONTROLS SQL/MX Functions and Expressions Examples of COMPILERCONTROLS • To display control tables, set the following CTs to ON: >>control table t3 mdam 'on'; --- SQL operation complete. >>control table t4 mdam 'on'; --- SQL operation complete.
Examples of COMPILERCONTROLS SQL/MX Functions and Expressions The query displays the following output: SEQNUM TYPE STATE ATTRIBUTE ------ --- ---- -------- ATTRIBUTE_VALUE ------------- 0 CQS BY_USER CONTROL QUERY SHAPE SHAPE SCAN (TABLE1 'T1', PATH 'IT1'); ? TABLE_NAME ---------- CONTROL QUERY --- 1 row(s) selected.
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-52. 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-40. 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-37. 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-43.
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-43.
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-43.
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-43.
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-52. 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-52. 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-56. 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, it takes 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 EXPLAIN statement display for the prepared statement named xx is identical to the EXPLAIN statement display shown under FC Command on page 4-30.
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 runtime_option_delimiters: ' ' max_results: 2 --- 1 row(s) selected.
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-43 and Interval Value Expressions on page 6-47.
FEATURE_VERSION_INFO Function SQL/MX Functions and Expressions FEATURE_VERSION_INFO Function FEATURE_VERSION_INFO is a built-in table-valued function that returns feature version information for all user objects with an object feature version (OFV) higher than a given value, in a specified set of catalogs. Information is not returned for definition schema tables or user metadata tables.
SQL/MX Functions and Expressions Example of FEATURE_VERSION_INFO Note. Possible values for the E_TYPE input parameter are: • • CATALOG – The E_VALUE parameter specifies the external format ANSI name of a catalog. Output rows are for objects in that catalog only. CATALOG_CASCADE – The E_VALUE parameter specifies the external format ANSI name of a catalog. Output rows are for objects in that catalog and catalogs that are related to it.
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-52. 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-43.
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-41.
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-52. 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-2.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-2.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-2.
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 or string. With the ANSI_STRING_FUNCTIONALITY CQD set to ON, the function pads the left side of a character expression with the specified string. LPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr.
SQL/MX Functions and Expressions • Examples of LPAD The following LPAD function returns the original string 'go fly a kite' because the count is equal to the length of the string: LPAD('go fly a kite', 13, 'z') • The following LPAD function returns a string of 10 characters ' padding the string 'Robert' with four spaces: Robert' by left LPAD('Robert',10) • The following LPAD function returns a string of eight characters '0000kite' by left padding the string 'kite' with four pad-characters '0': LPAD
SQL/MX Functions and Expressions • Examples of LPAD The following LPAD functions return an error because the count is greater than the string length: LPAD('Robert',10) LPAD('kite', 8, '0') LPAD('go fly a kite', 23, 'John,') HP NonStop SQL/MX Reference Manual—640322-001 9- 87
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-41.
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-43.
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-43.
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-43.
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-41.
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-43.
SQL/MX Functions and Expressions QUERYCACHE Function 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 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 CURRENT_SIZE INT Current size of the text and template cache. MAX_CACHE_SIZE INT Maximum cache size in KB. MAX_NUM_VICTIMS INT Maximum number of template cache entries that can be displaced from the cache to make room for a new entry.
Examples of QUERYCACHE SQL/MX Functions and Expressions Column Name Data Type Description OPTIMIZATION_LEVEL CHAR(10) The current desired level of query optimization. Can be 0, 2, 3, or 5. AVG_TEMPLATE_SIZE INT UNSIGNED Average template cache entry size in bytes. The size of a shared plan object is counted once. TEXT_CACHE_HITS INT UNSIGNED Reserved for future use. AVG_TEXT_SIZE INT UNSIGNED Reserved for future use. TEXT_ENTRIES INT UNSIGNED Reserved for future use.
Examples of QUERYCACHE SQL/MX Functions and Expressions NUM_PIN_HITS_PARSING NUM_PIN_HITS_BINDING 0 0 NUM_CACHEABLE_TOO_LARGE NUM_DISPLACED 0 OPTIMIZATION_LEVEL 3 PINNING_STATEOFF 0 --- 1 row(s) selected. • 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 PLAN_LENGTH INT Size in bytes of the compiled plan associated with this entry. COMPILATION_TIME INT Time in milliseconds it took to compile the query associated with this entry. AVERAGE_HIT_TIME INT Time in milliseconds it took on the average to process a query as a cache hit against this entry. SHAPE CHAR(1024) Required CONTROL QUERY SHAPE of the query associated with this entry.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions Dept/Num Dept/Name Mgr -------- ------------ ----1000 FINANCE 23 1500 PERSONNEL 213 2000 INVENTORY 32 . . . --- 12 row(s) selected. Rpt/Dept -------9000 1000 9000 Location -----------------CHICAGO CHICAGO LOS ANGELES >SELECT * FROM JOB; Job/Code -------100 200 250 Job Description -----------------MANAGER PRODUCTION SUPV ASSEMBLER . . . --- 10 row(s) selected.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions ------------------211894097543468116 211894097552547493 211894097548497817 ---------1 0 0 --------OFF OFF OFF --- 3 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-52. Examples of RADIANS • Return the value 7.85398150000000160E-001, or approximately 0.
RELATEDNESS Function SQL/MX Functions and Expressions RELATEDNESS Function RELATEDNESS is a built-in table-valued function that returns relatedness information for a single entity. relatedness ('E_TYPE', 'E_VALUE') Table 9-3 shows the input and output parameters for RELATEDNESS. Table 9-3. Input and Output Parameters for RELATEDNESS Input/Output Type Parameter Specification Description Input parameter E_TYPE CHAR (32) NOT NULL The type of version information that is requested.
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-41.
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 or string. With the ANSI_STRING_FUNCTIONALITY CQD set to ON, the function pads the right side of a character expression with the specified string. RPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr.
SQL/MX Functions and Expressions • Examples of RPAD The following RPAD function returns a string of seven characters 'kite string 'kite' is right-padded with three spaces. '. The RPAD('kite', 7) • The following RPAD function returns a string of eight characters 'kite0000'. The string 'kite' is right-padded with four pad-characters '0'. RPAD('kite', 8, '0') • The following RPAD function returns a string of 14 characters 'go fly a kitez'.
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-41.
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-43.
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-40 and the USER Function on page 9-176 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-52. 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 each of which is 0x20 (for the ISO88591 character set), 0x0020 (for the UCS2 character set), or 0x2020 (for the KANJI and KSC5601 character sets). SPACE is an SQL/MX extension. SPACE (length [,char-set-name]) length specifies the number of characters to be returned.
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-52. 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-130. 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-4.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-4.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-4.
SQL/MX Functions and Expressions Table 9-5.
SQL/MX Functions and Expressions Table 9-5.
SQL/MX Functions and Expressions Table 9-5.
Examples of UCASE SQL/MX Functions and Expressions Table 9-6. 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.
VERSION_INFO Function SQL/MX Functions and Expressions VERSION_INFO Function VERSION_INFO is a built-in table-valued function that returns version information for a single entity. version_info ('E_TYPE', 'E_VALUE') Table 9-7 shows the input and output parameters for VERSION_INFO. Table 9-7. Input and Output Parameters for VERSION_INFO Input/Output Type Parameter Specification Description Input parameter E_TYPE CHAR (32) NOT NULL The type of version information that is requested.
VERSION_INFO Function SQL/MX Functions and Expressions Table 9-8. Values for the E_TYPE and E_VALUE Parameters Value for the E_TYPE and E_VALUE Parameters Description SYSTEM_SCHEMA The specified node. SCHEMA All nodes where the catalog of the schema is visible. By default, this includes the local node. TABLE All nodes where partitions of that table reside, and the local node. TABLE_ALL All nodes where partitions of that table reside. All nodes where partitions of indexes on that table reside.
Example of VERSION_INFO SQL/MX Functions and Expressions Table 9-9. VERSION Output Column Values E_TYPE and E_VALUE Parameters (page 2 of 2) E_TYPE E_VALUE VERSION CONSTRAINT ANSI name of constraint OFV of constraint TRIGGER ANSI name of trigger OFV of trigger PROCEDURE ANSI name of procedure OFV of procedure MPALIAS ANSI name of mpalias OFV of mpalias MODULE ANSI name of module Module version ANSI names in the input value parameter must be fully qualified, in external format.
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-43.
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-43.
10 Metadata Tables This section describes: • • • • • • • SQL/MX Metadata Catalogs on page 10-2 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-34 User Metadata Tables (UMD): Histogram Tables on page 10-81 MXCS Metadata Tables on page 10-91 NonStop SQL/MX stores system metadata for all objects in SQL/MX tables, automatically creating and maintaining metadata as users create, alter, drop, or update s
SQL/MX Metadata Catalogs 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 3.
SQL/MX Metadata Schemas and Tables Metadata Tables SQL/MX Metadata Schemas and Tables Note. See the diagrammatic representation of the SQL/MX metadata tables in the SQL/MX Installation and Management Guide that is applicable for SQL/MX R 3.0. System Schema Tables: Schema SYSTEM_SCHEMA System metadata to resolve object names is stored in schema SYSTEM_SCHEMA of catalog NONSTOP_SQLMX_nodename on the Data Access Manager volume specified as the system metadata volume during installation.
Definition Schema Tables: Schema DEFINITION_SCHEMA_VERSION_vernum Metadata Tables This table lists definition schema tables in schema DEFINITION_SCHEMA_VERSION_vernum of each catalog: 1ACCESS_PATHS Table on page 10-11 Physical instances (a table, index, or a partition) of data in the catalog ACCESS_PATH_COLS Table on page 10-13 Columns in physical instances of data CK_COL_USAGE Table on page 10-13 Columns referenced in search conditions of check constraints CK_TBL_USAGE Table on page 10-13 Tables
System Defaults Tables (User Metadata Tables): Schema SYSTEM_DEFAULTS_SCHEMA Metadata Tables 12TRIGGER_USED Table on Describes how triggers use objects page 10-30 VWS Table on page 10-31 Views in the catalog 13VW_COL_TBLS Table on Base tables referenced by columns of a view page 10-32 VW_COL_TBL_COLS Table on page 10-32 Base table columns used in views VW_COL_USAGE Table on page 10-32 Columns used in views VW_TBL_USAGE Table on page 10-33 Tables referenced by views 1.
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-91 Associates MXCS service to a data source DATASOURCES Table on page 10-92 Data source information ENVIRONMENTVALUES Table on page 10-93 Sets, controls and defines environment values NAME2ID Table on page 10-93 Associates service or data source name to ID RESOURCEPOLICIES Table on page 10-94 Governing information *In addition,
VALIDATEROUTINE: Schema SYSTEM_SQLJ_SCHEMA Metadata Tables This table lists SQL/MP histogram tables: HISTOGRM Table on page 10-86 HISTINTS Table on page 10-87 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 For each interval of the table for which the histogram is created, the number of rows and unique rows and the value of the interval upper boundary For detailed descriptions of histogram
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. Column Name Data Type Description *1 CAT_UID LARGEINT UID of catalog for schema; link to CATSYS *2 SCHEMA_NAME CHAR(128) Schema name 3 SCHEMA_UID LARGEINT UID of schema; link to OBJECTS 4 SCHEMA_OWNER INT Owner's user ID 5 SCHEMA_VERSION INT Version of schema: 1200 for R2.x 3000 for R3.
SCHEMA_REPLICAS Table Metadata Tables SCHEMA_REPLICAS Table SCHEMA_REPLICAS is a metadata table in NONSTOP_SQLMX_nodename.SYSTEM_SCHEMA that lists locations of all replicas for all schemas that have definitions on the node.
ACCESS_PATHS Table Metadata Tables Column Name Data Type Description 11 PARTITIONING_SCHEME CHAR(2) Partitioning method for this access path: N Not partitioned RP Range partitioned by first key HP Hash-1 partitioned 12 BLOCK_SIZE INT Number of bytes for disk blocks on this access path 13 KEY_LENGTH INT Number of bytes in key 14 PARTITIONING_KEY_LENGTH INT Number of bytes in partitioning key 15 LOCK_LENGTH INT Reserved for future use 16 AUDITED CHAR(2) Y if this path is audited N if not
ACCESS_PATH_COLS Table Metadata Tables ACCESS_PATH_COLS Table ACCESS_PATH_COLS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes columns within each access paths for the catalog: Column Name Data Type Description *1 ACCESS_PATH_UID LARGEINT UID of access path *2 POSITION_IN_ROW INT Ordinal of column within access path (first position is 0) 3 COLUMN_NUMBER INT Position within row of base table (first column is 0) 4 ORDERING CHAR(2) A if ascending order D if descending ord
COLS Table Metadata Tables In SQL/MX Release 2.0, you can reference only one table in a search condition. COLS Table COLS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes columns in tables and views in the catalog. The COLS table also contains attributes of the individual parameters of an SPJ, one row per parameter.
COLS Table Metadata Tables Column Name Data Type Description 9 ENCODING CHAR (40) Internal representation of columns with character data types. 10 COLLATION_SEQUENCE CHAR(40) Collation 11 FS_DATA_TYPE INT File system data type.
COLS Table Metadata Tables Column Name Data Type Description 14 UPSHIFTED CHAR(2) Y if type is CHAR, VARCHAR or PIC with UPSHIFT clause N if not 15 NULL_HEADER_SIZE INT Length of NULL indicator header 16 VARLEN_HEADER_SIZE INT Length of VARCHAR header 17 DEFAULT_CLASS CHAR(2) Default defined by: Blank No default CD Current default ND Null default UD User default If CD, the value of the column depends on its data type: DATE Current date TIME Current time TIMESTAMP Current timestamp 18 LOGGAB
COLS Table Metadata Tables Column Name Data Type Description 28 DATE_DISPLAY_FORMAT VARCHAR(64) Reserved for future use 29 CASE_SENSITIVE_COMPARI SON CHAR(2) Case-sensitive comparison, if character type column.
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 O if granted as schema owne
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
KEY_COL_USAGE Table Metadata Tables Column Name Data Type Description *3 DATA_SOURCE CHAR(8) Name of a volume. The volume name includes the leading '$' sign. *4 FILE_SUFFIX CHAR(18) Subvol and simple name. * Indicates primary key Note. The DDL_PARTITION_LOCKS table is not present in schema version 3000 and newer system schemas. KEY_COL_USAGE Table KEY_COL_USAGE is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that lists columns on key constraints in the catalog.
OBJECTS Table Metadata Tables OBJECTS Table OBJECTS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes tables, views, indexes, constraints, triggers, MP aliases, stored procedures, locks, and trigger temporary tables.
PARTITIONS Table Metadata Tables Column Name Data Type Description 12 OBJECT_OWNER INT The integer representation of the owner's authorization ID 13 RESERVED_FILLER_INT INT Reserved for future use 14 RESERVED_FILLER_CHAR CHAR(20) Reserved for future use 15 DROPPABLE CHAR(2) Reserved for future use 16 RCB_VERSION INT The version of the object's Record Control Block (RCB) * Indicates primary key Note.
REF_CONSTRAINTS Table Metadata Tables Column Name Data Type Description 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(28670) 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) CA RE NA SD SN CASCADE 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
TBL_PRIVILEGES Table Metadata Tables TBL_PRIVILEGES Table TBL_PRIVILEGES is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores grant information for tables in the catalog: Column Name Data Type Description *1 GRANTOR INT Security ID of grantor (or of owner if grantor is the super ID acting for owner) *2 GRANTOR_TYPE CHAR(2) S if system grant U if user grant O if granted as schema owner *3 GRANTEE INT If GRANTEE_TYPE is U, security ID of grantee and link to COL_PRIVILEGES; no meani
TEXT Table Metadata Tables 1. TABLE_UID 2. GRANTOR 3. GRANTOR_TYPE 4. GRANTEE 5. GRANTEE_TYPE 6. PRIVILEGE_TYPE TEXT Table TEXT is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores text for objects in the catalog: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID for object.
TRIGGERS Table Metadata Tables Column Name Data Type Description 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 TRIGGER_CREATED LARGEINT Timestamp of creation of the trigger * Indicates primary key H
TRIGGERS_CAT_USAGE Table Metadata Tables TRIGGERS_CAT_USAGE Table TRIGGERS_CAT_USAGE is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes a trigger's use of objects in other catalogs (primarily needed for the DROP TRIGGER statement). Triggers can access objects in different (“foreign”) catalogs than the catalog of the trigger itself.
VWS Table Metadata Tables Column Name Data Type Description *6 OPERATION CHAR(2) Operation that fires the trigger U UPDATE I INSERT D DELETE For the used-object only, the operation performed on the used object S SELECT R ROUTINE *7 IS_SUBJECT_TABLE CHAR(2) Y if the USED_OBJECT_UID is the subject table of this trigger N if the USED_OBJECT_UID is used only by this trigger * Indicates primary key The primary key consists of the columns in the following order: 1. USED_OBJECT_UID 2. USED_COL_NUM 3.
VW_COL_TBLS Table Metadata Tables VW_COL_TBLS Table VW_COL_TBLS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that records the base table (but not the 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 t
VW_TBL_USAGE Table Metadata Tables Column Name Data Type Description *4 USED_OBJ_UID LARGEINT UID of object with referenced column *5 COLUMN_NUMBER INT Column number within object (first is 0) * Indicates primary key VW_TBL_USAGE Table VW_TBL_USAGE is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that records references by views in the catalog to tables or other views: Column Name Data Type Description *1 USING_VIEW_UID LARGEINT UID of referencing view *2 USED_OBJ_UID LARGEINT UID
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: Character Set Constraint Droppable Options Data Types Function Control Histograms Isolation Level Locking Local Autonomy Metadata Management Module Management 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 Ja
Default Attributes Metadata Tables This table provides a quick reference to the attributes you can set or override with the SYSTEM_DEFAULTS table: Attribute (page 1 of 9) Description Category ALLOW_DP2_ROW_SAMPLING Determines whether the sampling is done by the DP2 or the SQL/MX Executor. Query Optimization and Performance on page 10-63 ANSI_STRING_FUNCTIONALITY Determines the behavior of the LPAD and RPAD functions. A value set to ON will pad the string with the specified characters.
Default Attributes Metadata Tables Attribute (page 2 of 9) Description Category DATA_FLOW_OPTIMIZATION Controls whether query plans are considered that have high data flow rates. Query Optimization and Performance on page 10-63 DDL_DEFAULT_ LOCATIONS Specifies the physical location of the primary range partition to be created by CREATE statements that do not specify a LOCATION clause.
Default Attributes Metadata Tables Attribute (page 3 of 9) Description Category GEN_EIDR_BUFFER_SIZE Buffer size for partition access. Query Optimization and Performance on page 10-63 GEN_MAX_NUM_PART_ DISK_ENTRIES Controls the size of a partition list prepared by the compiler and used by the executor. Partition Management on page 10-60 GEN_MAX_NUM_PART_ NODE_ENTRIES Controls the size of a partition list prepared by the compiler and used by the executor.
Default Attributes Metadata Tables Attribute (page 4 of 9) Description Category HIST_SAME_TABLE_PRED_ REDUCTION Controls overlap amount in predicate selectivity when multicolumn predicates are used. Histograms on page 10-49 HIST_SCRATCH_VOL Sets the physical volume for UPDATE STATISTICS temporary tables. Histograms on page 10-49 HIST_SECURITY_WARNINGS Controls whether warnings on histogram tables are displayed.
Default Attributes Metadata Tables Attribute (page 5 of 9) Description Category MDAM_SCAN_METHOD Enables or disables the MultiDimensional Access Method. Query Optimization and Performance on page 10-63 MEMORY_USAGE_SAFETY_NET Specifies the MXCMP memory threshold in megabyte. Query Optimization and Performance on page 10-63 MIN_MAX_OPTIMIZATION Enables or disables MINMAX optimization.
Default Attributes Metadata Tables Attribute (page 6 of 9) Description Category OPTIMIZATION_LEVEL Controls increasing effort in optimizing queries. Query Optimization and Performance on page 10-63 OPTS_PUSH_DOWN_DAM Controls whether NonStop SQL/MX considers pushdown plans. Query Optimization and Performance on page 10-63 PARALLEL_NUM_ESPS Maximum number of parallel ESPs that work on a particular type of operator, like a join.
Default Attributes Metadata Tables Attribute (page 7 of 9) Description Category QUERY_CACHE_MAX_VICTIMS Limits the number of entries that an unusually large query plan is allowed to displace from the cache. Query Plan Caching on page 10-70 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.
Default Attributes Metadata Tables Attribute (page 8 of 9) Description Category SCRATCH_DISKS Restricts scratch disks for sort operations to the volumes specified. Scratch Disk Management on page 10-72 SCRATCH_DISKS_ EXCLUDED Excludes certain volumes from being used as scratch disks for sort operations. Scratch Disk Management on page 10-72 SCRATCH_DISKS_ PREFERRED Volumes preferred as scratch disks for sort operations.
Default Attributes Metadata Tables Attribute (page 9 of 9) Description Category UDR_JAVA_OPTIONS Specifies JVM startup options for the Java environment of an SPJ. Stored Procedures in Java on page 10-76 UPD_ORDERED Controls whether rows must be inserted, updated, or deleted in clustering key order. Query Optimization and Performance on page 10-63 UPD_ABORT_ON_ERROR Controls whether an update, insert, or delete function is aborted if an error occurs.
Character Set Metadata Tables Character Set This attribute determines the default for the character set: Attribute Setting INFER_CHARSET When set to ON, the parser does not consider the character set of literals. However, the binder decides the character set depending on the context. The default value for this attribute is OFF for MXCI and ON for ODBC/MX and JDBC/MX. For example: >>create table infchar(i CHAR(10) character set ucs2); --- SQL operation complete.
Constraint Droppable Options Metadata Tables *** ERROR[8822] The statement was not prepared. >>control query default infer_charset 'on'; --- SQL operation complete. >>insert into infchar values('abc'); --- 1 row(s) inserted. NATIONAL_CHARSET Displays the national character set ISO88591, UCS2, KANJI, or KSC5601 used in NCHAR and NCHAR VARYING columns. The national character set also governs the interpretation of the character string literal N'string'.
Data Types Metadata Tables These settings affect the way NonStop SQL/MX processes NOT NULL and PRIMARY KEY constraints, as follows: • • If a column is defined with the NOT NULL NOT DROPPABLE constraint, the executor does not check for null—thereby improving performance of updates and inserts. The NOT NULL NOT DROPPABLE constraint also eliminates the need for a null indicator, which reduces space requirements.
Function Control Metadata Tables 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. If the result value exceeds the allowed numeric limit, the precision is truncated to 18. PRESERVE_MIN_SCALE allows you to preserve minimum scale in a result when the precision exceeds 18. Allowable values: 0 to 18 The default is 0.
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 4294967295. 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.
Local Autonomy Metadata Tables Local Autonomy This attribute controls how SQL/MX handles local autonomy: Attribute Setting SKIP_UNAVAILABLE_PARTITIO N This attribute provides local autonomy for certain situations by directing SQL/MX to continue processing a query even if partitions required for the access plan of the query are not available. This attribute applies to partitioned tables, but affects only the main query in a SELECT statement without INTO clause.
Metadata Management Metadata Tables Metadata Management This attribute enables NonStop SQL/MX to manage metadata: Attribute Setting CREATE_DEFINITION_SCHEM A_VERSION Assigns a schema version to new schemas during schema creation time. For SQL/MX 3.0, the valid schema versions are SYSTEM, 1200, and 3000. The default value is SYSTEM.
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 ALLOW_DP2_ROW_SAMPLING Set to SYSTEM, ON, or OFF. When a SQL/MX query contains a SAMPLE clause, this attribute determines whether the sampling operation should be done by DP2 or by the SQL/MX Executor. When set to SYSTEM, the sampling is done by DP2 for sample percentages of up to 5%.
Query Optimization and Performance Metadata Tables Attribute Setting CHECK_CONSTRAINT_PRUNING Set to ON, OFF, RESET, or SYSTEM. The default is ON. If OFF, the constraint based query pruning optimization will not be tried on the subsequent queries. The CQD value RESET or SYSTEM sets the value of CQD back to the default value. The constraint based pruning uses the Constant Range Predicate Folding (CRPF) feature.
Query Optimization and Performance Metadata Tables Attribute Setting GENERATE_EXPLAIN Enables generation of EXPLAIN information at compile time. For MXCI, the default is automatically turned on by a CONTROL QUERY DEFAULT GENERATE_EXPLAIN 'ON' command issued by MXCI at startup time. For performance testing in MXCI, you might want to turn off GENERATE_EXPLAIN.
Query Optimization and Performance Metadata Tables Attribute Setting JOIN_ORDER_BY_USER Enables (ON) or disables (OFF) the join order specified you specify in the FROM clause of a query. When set to ON, the optimizer considers only execution plans that have the join order you specify. For additional information about this setting, see the SQL/MX Query Guide. The default is OFF.
Query Optimization and Performance Metadata Tables Attribute Setting MIN_MAX_OPTIMIZATION Set to ON or OFF. This performance optimization enables the compiler to read only the result row or a select number of rows to answer minimum (MIN) or maximum (MAX) aggregate expressions. The compiler can perform this type of optimization only when the rows are naturally ordered on the MINMAX column. If OFF, this type of optimization is disabled. The default is ON.
Query Optimization and Performance Metadata Tables Attribute Setting OPTIMIZATION_LEVEL Set to 0, 2, 3, or 5 to indicate increasing effort in optimizing SQL queries. Values 1 and 4 are reserved for future use. For additional information about this setting, see the SQL/MX Query Guide. The default is 3. OPTS_PUSH_DOWN_DAM Set to ON (1) or OFF (0). When set to ON, the system considers pushing down a plan to DAM for compound statements or nested joins.
Query Optimization and Performance Metadata Tables Attribute Setting REMOTE_ESP_ALLOCATION Set to ON, OFF, or SYSTEM. If ON, NonStop SQL/MX is forced to bring up ESPs on all the systems that are in the scope of the specific query and all target systems become active systems. If OFF, NonStop SQL/MX is forced to bring up all ESPs on the local system only. If SYSTEM, NonStop SQL/MX decides which target systems should be used for ESP placement.
Query Plan Caching Metadata Tables Query Plan Caching These attributes enable NonStop SQL/MX to cache query plans: Attribute Setting QUERY_CACHE Set to a value between 0 to 4194303. Indicates the size in kilobytes to which the cache is allowed to grow. The default setting is 1024, which activates a query cache that can grow to 1024 KB in the current session. To deactivate the query cache in the current session, set QUERY_CACHE to 0. If a query cache was allocated, this setting frees it.
Referential Action Metadata Tables Attribute Setting QUERY_CACHE_STATEMENT_ PINNING Set to ON, OFF, or CLEAR. Controls whether queries are entered into the cache as pinned or unpinned. You might have important, compile-time critical queries that you want to ensure are in the cache when needed. When a query is pinned in the cache, it usually cannot be displaced from the cache unless the cache becomes full of pinned queries. In this case, the least recently used pinned entries also become displaceable.
Scratch Disk Management Metadata Tables READONLY_CURSOR Set to TRUE or FALSE. If set to TRUE, you must declare cursors with the FOR UPDATE clause for the named columns or all columns to be updatable. This setting improves cursor performance. If set to FALSE and the declarations omit FOR UPDATE or FOR READ ONLY, all columns are updatable. In SQL/MX, DELETE WHERE CURRENT OF does not work without the FOR UPDATE clause if READONLY_CURSOR is set to true.
Sequence Functions Metadata Tables specified by the SCRATCH_DISKS_EXCLUDED control are removed. If the SCRATCH_DISKS control is specified, the disks that are not specified in the SCRATCH_DISKS control are removed from the pool. From this disk pool, a disk is selected based on this criteria: • • • • • • The amount of used space on the disk. (rank * 30) The number of scratch files on the disk. (rank * 70) The number of fragments on the disk. (rank * 20) The biggest available fragment on the disk.
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. RECOMPILE_ON_ PLANVERSION_ERROR Set to ON or OFF. If set to ON, a SQL statement is automatically recompiled at run time in case of versioning errors.
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-240.
Table Management Metadata Tables Attribute Setting SAVE_DROPPED_TABLE _DDL Controls whether definitions of dropped tables are saved to enable them to be recovered. If set to ON, DDL information for a dropped table is saved to a file called catalog.schema.tablename-yyyymmddtimestamp.ddl in the OSS directory /usr/tandem/sqlmx/ddl. For example, if a table called CAT.SCH.T123 is dropped at 12:53:31 PM on July 29, 2003, the full OSS path name of the saved DDL file would be: /usr/tandem/sqlmx/ddl/CAT.SCH.
Trigger Management Metadata Tables Attribute Setting VARCHAR_PARAM_ DEFAULT_SIZE Depending on context, untyped parameters might be converted to the VARCHAR type during compilation of a query. The default length for this type is 255 characters. This CQD allows you to change the default length. Allowable values: 1 to 32768. The default is 255 characters.
Metadata Tables • Examples of SYSTEM_DEFAULTS Table Query the SYSTEM_DEFAULTS table to obtain the current default setting for the transaction isolation level: SELECT ATTRIBUTE, ATTR_VALUE FROM SYSTEM_DEFAULTS WHERE ATTRIBUTE = 'ISOLATION_LEVEL'; • Set a new value for the transaction isolation level: UPDATE SYSTEM_DEFAULTS SET ATTR_VALUE = 'READ COMMITTED' WHERE ATTRIBUTE = 'ISOLATION_LEVEL'; • Set the level of optimization for the next query to be executed.
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.
HISTOGRAMS Table Metadata Tables Column Name Data Type Description 13 READ_COUNT SMALLINT The number of times READ_TIME is updated since this histogram was last generated. 14 SAMPLE_SECS LARGEINT Number of seconds required to create and populate sample table in seconds with the minimum value being 1 sec. If sampling is not used, this column is set to 0. 15 COL_SECS LARGEINT Number of seconds required to create statistics from column data for histogram. This column does not include sample time.
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-111 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-29 DECLARE NAMETYPE Declaration on page 3-32 DECLARE SCHEMA Declaration on page 3-33 DELETE DEFINE Command on page 4-9 DELETE Statement on page 2-116 DESCRIBE Statement on page 3-34 DISPLAY STATISTICS Command on page 4-23 DISPLAY USE OF Command on p
F Quick Reference EXEC SQL Directive on page 3-38 EXECUTE IMMEDIATE Statement on page 3-39 EXECUTE Statement on page 2-138 EXIT Command on page 4-29 EXPLAIN Statement on page 2-145 mxexportddl Utility on page 5-92 F FC Command on page 4-30 FETCH Statement on page 3-40 FIXUP Operation on page 5-21 G GET DESCRIPTOR Statement on page 3-46 GET DIAGNOSTICS Statement on page 3-55 GET NAMES OF RELATED NODES Command on page 4-34 GET NAMES OF RELATED SCHEMAS Command on page 4-35 GET NAMES OF RELATED CATALOGS on
L Quick Reference IF Statement on page 3-61 import Utility on page 5-31 INFO DEFINE Command on page 4-45 INFO Operation on page 5-65 INITIALIZE SQL Statement on page 2-168 INSERT Statement on page 2-169 INVOKE Command on page 4-46 INVOKE Directive on page 3-64 L LOCK TABLE Statement on page 2-180 LOG Command on page 4-47 LS Command on page 4-51 M migrate Utility on page 5-67 MODIFY Utility on page 5-72 MODULE Directive on page 3-70 MXCI Command on page 4-55 MXGNAMES Utility on page 5-96 mximportddl Util
S Quick Reference REPEAT Command on page 4-58 RESET PARAM Command on page 4-59 REVOKE Statement on page 2-190 REVOKE EXECUTE Statement on page 2-193 ROLLBACK WORK Statement on page 2-196 S SELECT Statement on page 2-198 SET Statement on page 2-233 SET CATALOG Statement on page 2-234 SET (Assignment) Statement on page 3-76 SET DESCRIPTOR Statement on page 3-78 SET LIST_COUNT Command on page 4-61 SET MPLOC Statement on page 2-236 SET NAMETYPE Statement on page 2-237 SET PARAM Command on page 4-62 SET SCHEM
U Quick Reference TABLE Statement on page 2-250 U UNLOCK TABLE Statement on page 2-251 UNREGISTER CATALOG Statement on page 2-252 UPDATE Statement on page 2-253 UPDATE STATISTICS Statement on page 2-266 UPGRADE Utility on page 5-121 V VALUES Statement on page 2-277 VERIFY Operation on page 5-124 W WHENEVER Declaration on page 3-86 HP NonStop SQL/MX Reference Manual—640322-001 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-57. 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—640322-001 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 depends on the block size. For 4K blocks, the maximum length is 2010 bytes. For 32K blocks, the maximum length is 2048 bytes.
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.
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—640322-001 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—640322-001 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-118 DML statements use of 1-7 INSERT statement use of 2-169 READ COMMITTED 1-8 READ UNCOMMITTED 1-8 REPEATABLE READ 1-8 SELECT statement use of 2-212 SERIALIZABLE 1-8, 1-10, 1-22 SKIP CONFLICT 1-8 SQL/MP considerations 1-30 STABLE 1-9 UPDATE statement use of 2-257 Access privileges ALL PRIVILEGES 2-162 DELETE 2-162 INSERT 2-162 REFERENCES 2-162 SELECT 2-162 tables 2-162 UPDATE 2-162 views 2-1
A Index ALLOCATE DESCRIPTOR statement (continued) syntax diagram of 3-6 ALLOCATE file attribute 8-2 ALLOW_DP2_ROW_SAMPLING default 10-63 ALL_UIDS metadata table 10-8 ALTER DEFINE command examples of 4-7 syntax diagram of 4-6 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 ALT
B Index ATTEMPT_ESP_PARALLELISM default 10-63 AUDITCOMPRESS file attribute ALTER TABLE use of 8-3 CREATE TABLE use of 8-3 syntax diagram of 8-3 Audited tables CREATE TABLE considerations 2-93 DELETE considerations 2-121 INSERT considerations 2-176 transaction management 1-15 UPDATE considerations 2-261 Authorization ID 1-5 AUTOMATIC_RECOMPILATION default 10-74 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
C Index CEILING function (continued) syntax diagram of 9-22 CHAR data type 6-23 CHAR function examples of 9-23 syntax diagram of 9-23 CHAR VARYING data type 6-23 Character set default attribute 10-46 Character sets description of 6-4 ISO88591 6-4 KANJI 6-4 KSC5601 6-4 setting default 6-64, 6-65, 6-66, 10-74 support standards E-7 UCS2 6-4 Character string data types CHAR and VARCHAR, differences 6-23 examples of literals 6-67 maximum storage lengths 6-24 Character string functions summary of 9-2 ASCII 9-11
C Index CLOSE statement (continued) static and dynamic forms 3-11 syntax diagram of 3-11 Cluster sampling 7-10 Clustering key description of 6-60 limits C-2 NONDROPPABLE PRIMARY KEY specification 2-82 STORE BY clause 7-22 STORE BY clause, CREATE TABLE 2-86 system-defined SYSKEY 6-63 CODE_VALUE function, syntax diagram of 9-27 Collations description of 6-6 SQL/MP considerations 1-31 COLS metadata table 10-14 Columns column reference 6-7 default values 6-8 qualified name 6-7 COL_PRIVILEGES metadata table 10
C Index Constraints (continued) UNIQUE 6-9 CONTROL QUERY DEFAULT statement attributes 10-36 examples of 2-35 syntax diagram of 2-34 CONTROL QUERY SHAPE statement examples of 2-43 syntax diagram of 2-36 CONTROL TABLE statement examples of 2-51 syntax diagram of 2-48 CONVERTTIMESTAMP function examples of 9-33 JULIANTIMESTAMP inverse relationship to 9-33 syntax diagram of 9-33 Correlation names examples of 6-11 purpose of 6-11 table reference use of 6-11 COS function examples of 9-34 syntax diagram of 9-34 C
D Index CREATE VIEW statement (continued) examples of 2-115 LOCATION file option within 2-113 syntax diagram of 2-111 updatability requirements 2-115 WITH CHECK OPTION within 2-114 CROSS join, description of 2-207 CROSS_PRODUCT_CONTROL default 10-64 Ctrl-c, effect on queries 1-5 Ctrl-Y, effect on MXCI session 4-29 CURRENT_DATE function examples of 9-38 syntax diagram of 9-38 CURRENT_TIME function examples of 9-39 precision specification within 9-39 syntax diagram of 9-39 CURRENT_TIMESTAMP function example
D Index Data types (continued) REAL 6-37 character 6-22 comparable and compatible 6-17 datetime DATE 6-26 TIME 6-26 TIMESTAMP 6-26 exact numeric DECIMAL 6-36 descriptions of 6-35 INTEGER 6-35 LARGEINT 6-36 NUMERIC 6-35 PICTURE 6-36 SMALLINT 6-35 extended numeric precision 6-18 fixed length character CHAR 6-23 NATIONAL CHAR 6-23 NCHAR 6-23 PIC 6-23 interval 6-31 Java 2-63 literals, examples of character string literals 6-67 datetime literals 6-70 interval literals 6-75 numeric literals 6-76 varying-length
D Index Datetime value expression (continued) syntax diagram of 6-43 DAY function examples of 9-42 syntax diagram of 9-42 DAYNAME function examples of 9-43 syntax diagram of 9-43 DAYOFMONTH function examples of 9-44 syntax diagram of 9-44 DAYOFWEEK function examples of 9-45 syntax diagram of 9-45 DAYOFYEAR function examples of 9-46 syntax diagram of 9-46 DDL statements See Data Definition Language (DDL) statements DDL_DEFAULT_LOCATIONS default 10-60 DDL_LOCKS metadata table 10-19 DDL_PARTITION_LOCKS metad
D Index Default settings (continued) ATTEMPT_ASYNCHRONOUS_ACCES S 10-63 ATTEMPT_ESP_PARALLELISM 10-63 AUTOMATIC_RECOMPILATION 10-74 CACHE_HISTOGRAMS 10-49 CACHE_HISTOGRAMS_REFRESH_IN TERVALS 10-50 CATALOG 10-57 CROSS_PRODUCT_CONTROL 10-64 DATA_FLOW_OPTIMIZATION 10-64 DDL_DEFAULT_LOCATIONS 10-60 DEFAULT_BLOCKSIZE 10-77 DEF_MAX_HISTORY_ROWS 10-73 DOOM_USERTRANSACTION 10-74 DP2_CACHE_4096_BLOCKS 10-64 DYNAMIC_HISTOGRAM_COMPRESS ION 10-50 FFDC_DIALOUTS_FOR_MXCMP 10-6 4 FLOATTYPE 10-48 GENERATE_EXPLAIN 10-65 G
D Index Default settings (continued) POS_LOCATIONS 10-62 POS_NUM_OF_PARTNS 10-62 POS_RAISE_ERROR 10-62 PREFERRED_PROBING_ORDER_FO R_NESTED_JOIN 10-68 PRESERVE_MIN_SCALE 10-49 PRIMARY_KEY_CONSTRAINT_DROP PABLE_OPTION 10-47 QUERY_CACHE 10-70 QUERY_CACHE_MAX_VICTIMS 10-7 0 QUERY_CACHE_REQUIRED_PREFIX _KEYS 10-70 QUERY_CACHE_STATEMENT_PINNI NG 10-71 READONLY_CURSOR 10-72 RECOMPILATION_WARNINGS 10-75 RECOMPILE_ON_PLANVERSION_ER ROR 10-75 REF_CONSTRAINT_NO_ACTION_LIK E_RESTRICT 10-71 REMOTE_ESP_ALLOCATION 10-69
D Index DELETE statement (embedded) C examples of 2-122 COBOL examples of 2-123 positioned form 2-116 searched form 2-116 Delimited identifiers 6-56 Derived column names examples of 6-8 syntax of 6-7 DESCRIBE statement C examples of 3-35 COBOL examples of 3-36 INPUT form 3-34 OUTPUT form 3-34 scope of 3-35 syntax diagram of 3-34 DETAIL_COST in EXPLAIN output CPU_TIME 2-148 IDELTIME 2-148 IP_TIME 2-148 MSG_TIME 2-148 PROBES 2-148 DIFF1 function equivalent definitions 9-48 examples of 9-49 syntax diagram of
E Index DROP PROCEDURE statement (continued) syntax diagram of 2-127 DROP SCHEMA statement authorization and availability requirements 2-128 examples of 2-130 limits C-1 syntax diagram of 2-128 DROP SQL statement authorization and availability requirements 2-131 examples of 2-131 syntax diagram of 2-131 DROP SQLMP ALIAS statement examples of 2-133 syntax diagram of 2-132 usage restrictions 2-132 DROP TABLE statement authorization and availability requirements 2-134 examples of 2-135 syntax diagram of 2-13
F Index Exclamation point (!) command examples of 4-28 syntax diagram of 4-28 EXCLUSIVE lock mode 1-11 EXEC SQL directive examples of 3-38 syntax diagram of 3-38 terminating with END-EXEC in COBOL 3-38 terminating with semicolon in C 3-38 EXECUTE IMMEDIATE statement C examples of 3-39 COBOL examples of 3-39 syntax diagram of 3-39 EXECUTE statement C examples of 2-142 COBOL examples of 2-143 MXCI examples of 2-141 scope of 2-139, 2-141 syntax diagram of 2-138 EXISTS predicate correlated subquery within 6-9
G Index FETCH statement (continued) using host variables 3-41 FFDC_DIALOUTS_FOR_MXCMP default 10-64 File attributes summary of 8-1 ALTER INDEX use of 8-1 ALTER TABLE use of 8-1 AUDITCOMPRESS 8-3 BLOCKSIZE 8-4 CLEARONPURGE 8-5 CREATE INDEX use of 8-1 CREATE TABLE use of 8-1 description of 8-1 EXTENT 8-6 MAXEXTENTS 8-7 File options CREATE INDEX use of 2-54 CREATE TABLE use of 2-77 STORE BY 2-86, 7-22 File organizations entry-sequenced 1-31 key-sequenced 1-31 relative 1-31 restrictions on 1-31 First (partiti
H Index GET VERSION OF SCHEMA command examples of 4-38 syntax diagram of 4-38 GET VERSION OF STATEMENT command example of 4-43 syntax diagram of 4-43 GET VERSION OF SYSTEM command example of 4-37 syntax diagram of 4-37 GET VERSION OF SYSTEM SCHEMA command example of 4-39 syntax diagram of 4-39 GOAWAY operation 5-26 GRANT EXECUTE statement authorization and availability requirements 2-166 examples of 2-166 security 2-166 syntax diagram of 2-165 GRANT statement authorization and availability requirements 2-
I Index HIST_SECURITY_WARNINGS default 10-53 Host variable arrays, INSERT statement 2-172 Host variables, INSERT statement 2-175 HOUR function examples of 9-71 syntax diagram of 9-71 I Identifiers 6-56 ID, authorization 1-5 IF statement examples of 3-62, 3-63 syntax diagram of 3-61 import utility 5-31 IN predicate examples of 6-96 limits C-1 logical equivalent using ANY 6-95 operand requirements 6-95 syntax diagram of 6-94 Index keys 6-62 Indexes ALTER INDEX statement 2-7 CREATE INDEX statement 2-54 desc
J Index INVOKE command examples of 4-46 syntax diagram of 4-46 INVOKE directive examples of 3-67 syntax diagram of 3-64 whether preprocessor preserves or overrides 3-30, 3-66 ISO standards E-2 ISO88591 character set 6-4 Isolation levels READ COMMITTED 1-22 READ UNCOMMITTED 1-21 REPEATABLE READ 1-22 SERIALIZABLE 1-8, 1-10, 1-22 ISOLATION_LEVEL default 10-53 IUD_NONAUDITED_INDEX_MAINT default 10-57 J Java data types 2-63 Join CONTROL QUERY SHAPE statement 2-40 CROSS 2-207 INDEXJOIN 2-40 JOIN ON 2-207 join
L Index Limits (continued) indexes 2-60, C-1 joins 2-216, C-1 MAXEXTENTS C-1 partitions C-1 referential constraints 2-20, C-2 SELECT statement, FROM clause C-1 tables 2-94, C-2 Literals character string, examples of 6-67 datetime, examples of 6-70 description of 6-64 examples of 6-64 interval, examples of 6-75 numeric, examples of 6-76 LOCATE function examples of 9-78 result of 9-77 syntax diagram of 9-77 LOCATION file option CREATE CATALOG use of 2-52 CREATE INDEX use of 2-56 CREATE VIEW use of 2-113 Loc
M Index Logical operators NOT, AND, OR 6-106 search condition use of 6-106 LOWER function examples of 9-84 syntax diagram of 9-80 LPAD function examples of 9-85 syntax diagram of 9-85 LS command examples of 4-52 options 4-51 LTRIM function examples of 9-88 syntax diagram of 9-88 M Magnitude 6-53 Management statements, summary of 9-89 MATERIALIZE default 10-76 Math functions summary of 9-5 ABS 9-10 ACOS 9-10 ASIN 9-12 ATAN 9-13 ATAN2 9-13 CEILING 9-22 COS 9-34 COSH 9-34 DEGREES 9-47 EXP 9-54 FLOOR 9-66 LO
M Index Metadata tables (continued) DATASOURCES 10-92 DDL_LOCKS 10-19 DDL_PARTITION_LOCKS 10-19 ENVIRONMENTVALUES 10-93 HISTINTS 10-87 HISTOGRAMS_nodename 10-83 HISTOGRAM_INTERVALS 10-85 HISTOGRM 10-86 KEY_COL_USAGE 10-20 MP_PARTITIONS 10-20 NAME2ID 10-93 OBJECTS 10-21 PARTITIONS 10-22 REF_CONSTRAINTS 10-23 REPLICAS 10-24 RESOURCEPOLICIES 10-94 RI_UNIQUE_USAGE 10-24 ROUTINES 10-25 SCHEMATA 10-10 SCHEMA_REPLICAS 10-11 SYSTEM_DEFAULTS 10-34 TBL_CONSTRAINTS 10-26 TBL_PRIVILEGES 10-27 TEXT 10-28 TRIGGERS 10-2
N Index MOVINGSTDDEV function examples of 9-104 syntax diagram of 9-103 MOVINGSUM function examples of 9-106 syntax diagram of 9-105 MOVINGVARIANCE function examples of 9-108 syntax diagram of 9-107 MP_PARTITIONS metadata table 10-20 MP_SUBVOLUME default 10-58 MP_SYSTEM default 10-58 MP_VOLUME default 10-58 MSCF_ET_REMOTE_MSG_TRANSFER default 10-67 MXCI break key 1-5, 4-57 description of 1-2 parameters 6-77 statement length 1-3 MXCI command examples of 4-55 syntax diagram of 4-55 MXCMP_PLACES_LOCAL_MODULE
O Index NOT NULL constraint 6-9 NOT_NULL_CONSTRAINT_DROPPABLE_ OPTION default 10-47 NULL predicate examples of 6-100 syntax diagram of 6-99 Null symbol 6-80 NULL, using 2-256 NUMBER_OF_USERS default 10-67 NUMERIC data type 6-35 Numeric data types approximate numeric 6-35 exact numeric 6-35 extended numeric 6-18 literals, examples of 6-76 Numeric literals approximate 6-76 exact 6-76 examples of 6-76 Numeric value expression evaluation order 6-53 examples of 6-55 syntax diagram of 6-52 OBJECTS metadata tab
P Index Partitioning key (continued) CREATE TABLE, FIRST KEY specification 2-88 Partitions automatic creation 2-94 description of 6-83 hash 6-83 hash, MODIFY utility 5-80 limits C-1 managing 5-72 range 6-83 range, MODIFY utility 5-72, 5-74 PARTITIONS metadata table 10-22 Path name, CD command use of 4-8 Performance buffer size 10-65 character string data types 6-24 CLEARONPURGE file attribute 8-5 compound statements 3-14 constraint droppable options 10-48 constraints 2-22 CONTROL TABLE statement 2-48 CREA
Q Index PREPARE statement (continued) MXCI examples of 2-185 naming statements 2-185 scope of 2-184 syntax diagram of 2-183 Prepared SQL, statements for 2-3 PRESERVE_MIN_SCALE default 10-49 Primary key ALTER TABLE statement 2-14 description of 6-63 Primary key constraint 6-9 PRIMARY_KEY_CONSTRAINT_DROPPA BLE_OPTION default 10-47 Privileges ALL PRIVILEGES 2-162 DELETE 2-162 GRANT EXECUTE statement 2-165 GRANT statement use of 2-162 INSERT 2-162 REFERENCES 2-162 required to execute utilities 5-2 REVOKE EXEC
R Index RECOMPILATION_WARNINGS default 10-75 RECOMPILE_ON_PLANVERSION_ERRO R default 10-75 RECOVER utility 5-119 REFERENCES access privilege 2-162, 2-191 References column constraint, ALTER TABLE statement 2-15, 2-19 References column constraint, description of 6-9 Referential constraints, limits C-2 Referential integrity constraint 6-9 Referential integrity, ALTER TABLE statement 2-15 REF_CONSTRAINTS metadata table 10-23 REF_CONSTRAINT_NO_ACTION_LIKE_R ESTRICT default 10-71 REGISTER CATALOG command examp
S Index ROWS SINCE function (continued) syntax diagram of 9-130 Rowsets DELETE statement 2-117, 2-118 expressions 6-55 GET DESCRIPTOR items 3-50 INSERT statement 2-170, 2-172 predicates 6-104 search condition 6-108 SELECT statement FROM clause 2-208 HAVING clause 2-212 host variables 2-203 ROWSET FOR clause 2-201 search condition 2-209 size 2-208 SET DESCRIPTOR items 3-80 default 3-80 triggers 2-108, 2-109 UPDATE statement 2-254/2-255, 2-257 RPAD function examples of 9-132 syntax diagram of 9-132 RTRIM fu
S Index Scope (continued) 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-35 EXECUTE use of 2-139 FETCH use of 3-41 OPEN use of 3-72 PREPARE use of 2-184 SCRATCH_DISKS default 10-72 SCRATCH_DISKS_EXCLUDED default 10-72 SCRATCH_DISKS_PREFERRED default 10-72 SCRATCH_FREESPACE_THRESHOLD_P ERCENT default 10-72 Search condition Boolean operators within 6-106 CASE expression use of 9-17 DELETE statement use of 2-118 description of 6
S Index Sequence functions (continued) DIFF2 9-51 LASTNOTNULL 9-74 MOVINGAVG 9-95 MOVINGCOUNT 9-97 MOVINGMAX 9-99 MOVINGMIN 9-101 MOVINGSTDDEV 9-103 MOVINGSUM 9-105 MOVINGVARIANCE 9-107 OFFSET 9-110 ROWS SINCE 9-130 RUNNINGAVG 9-135 RUNNINGCOUNT 9-137 RUNNINGMAX 9-139 RUNNINGMIN 9-141 RUNNINGSTDDEV 9-143 RUNNINGSUM 9-145 RUNNINGVARIANCE 9-147 THIS 9-161 SERIALIZABLE 1-8, 1-10, 1-22 SESSION_USER function examples of 9-150 syntax diagram of 9-150 SET CATALOG statement C examples of 2-235 COBOL examples of 2
S Index SET TRANSACTION statement (continued) syntax diagram of 2-244 transaction modes set by 2-245 SET WARNINGS command examples of 4-70 syntax diagram of 4-70 SH command examples of 4-71 syntax diagram of 4-71 SHARE lock mode 1-11 Shorthand view 6-113 SHOW PARAM command examples of 4-72 syntax diagram of 4-72 SHOW PREPARED command examples of 4-73 syntax diagram of 4-73 SHOW SESSION command attributes displayed by 4-74 examples of 4-75 syntax diagram of 4-74 SHOWCONTROL command examples of 4-77 syntax
S Index SQL value expression 6-41 SQLCODE, using ERROR command 1-35 SQLMP objects, logical names 6-14 SQLMX objects, logical names 6-13 SQLSTATE, in SQL/MX messages 1-35 SQL/MP aliases ALTER SQLMP ALIAS statement 2-8 catalogs 10-58 CREATE SQLMP ALIAS statement 2-73 description of 6-109 DROP SQLMP ALIAS statement 2-132 OBJECTS table 6-15 schemas 6-105 SQL/MP catalogs 6-3 SQL/MP considerations access options 1-30 catalogs 6-3 collations 1-31 datetime literals data inserting 6-69 selecting 6-28 embedded stat
S Index Statistics (continued) SET STATISTICS command 4-68 SQL/MP histogram tables 10-80 stored in PARTITIONS table 10-22 UPDATE STATISTICS statement considerations 2-270 examples of 2-274 syntax diagram 2-266 STDDEV function DISTINCT clause within 9-153 examples of 9-154 statistical definition of 9-153 syntax diagram of 9-153 STORE BY clause, syntax description 7-22 Stored procedure statements CALL 2-27 CREATE PROCEDURE 2-61 DROP PROCEDURE 2-127 Stored text reserved words B-1 SQL/MP restrictions 1-30 Str
T Index SYSTEM_DEFAULTS table (continued) data types 10-48, 10-49 examples of 10-79 histograms 10-49 isolation level 10-53 locking 10-54 nonaudited tables 10-57 object naming 10-57 partition management 10-60 query optimization and performance 10-63 query plan caching 10-70 referential action 10-71 row maintenance 10-71 scratch disk management 10-72 sequence functions 10-73 statement atomicity 10-74 statement recompilation 10-74 stored procedures in Java 10-76 stream access 10-76 table management 10-77 SYS
U Index Transaction management statements (continued) COMMIT WORK 2-31 ROLLBACK WORK 2-196 SET TRANSACTION statement 2-244 Transactions 1-14 TRANSLATE function, syntax diagram of 9-163 TRANSPOSE clause cardinality of result 7-28 degree of result 7-27 examples of 7-29 SELECT statement use of 7-25 syntax diagram of 7-25 Triggers ALTER TRIGGER statement 2-25 considerations 2-104 CREATE TABLE LIKE statement 2-92 CREATE TRIGGER statement 2-101 description 6-112 DROP TRIGGER statement 2-136 DUP utility 5-11 imp
V Index UPDATE STATISTICS statement (continued) column lists 2-267 examples of 2-274 histogram tables 2-267 row distribution 2-268 sample size 2-269 syntax diagram of 2-266 table row count 2-270 UPD_ABORT_ON_ERROR default 10-74 UPD_ORDERED default 10-69 UPD_SAVEPOINT_ON_ERROR default 10-74 UPGRADE utility 5-121 considerations for 5-121 example of 5-123 output options for 5-121 UPPER function examples of 9-174 syntax diagram of 9-174 UPSHIFT function examples of 9-175 syntax diagram of 9-175 User aliases,
W Index Views (continued) insertable 2-115 relationship to tables 6-112 SQL/MP considerations 1-30 updatability requirements 2-115 VWS metadata table 10-31 VW_COL_TBLS metadata table 10-32 VW_COL_TBL_COLS metadata table 10-32 VW_COL_USAGE metadata table 10-32 VW_TBL_USAGE metadata table 10-33 W WEEK function examples of 9-185 syntax diagram of 9-185 WHENEVER declaration actions within 3-87 C examples of 3-88 COBOL examples of 3-88 conditions within 3-86 syntax diagram of 3-86 Y YEAR function examples of