HP NonStop SQL/MX Reference Manual Abstract This manual describes the syntax of SQL language elements—data types, expressions, functions, identifiers, literals, and predicates—and SQL statements of HP NonStop™ SQL/MX, the NonStop relational database management system based on ANSI SQL:1999. The manual also includes embedded SQL statements and MXCI commands. Product Version NonStop SQL/MX Releases 2.0 and 2.1 Supported Release Version Updates (RVUs) This publication supports G06.
Document History Part Number Product Version Published 522680-002 NonStop SQL/MX Release 1.8 February 2003 523725-001 NonStop SQL/MX Release 2.0 April 2004 523725-002 NonStop SQL/MX Release 2.0 August 2004 523725-003 NonStop SQL/MX Releases 2.0 and 2.1 June 2005 523725-004 NonStop SQL/MX Releases 2.0 and 2.
HP NonStop SQL/MX Reference Manual Index Figures What’s New in This Manual xxxi Manual Information xxxi New and Changed Information Tables xxxii About This Manual xxxv Audience xxxv Organization xxxv Related Documentation xxxvi Notation Conventions xl 1.
1. Introduction (continued) Contents 1.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
2. SQL/MX Statements (continued) Contents 2.
Contents 3. Embedded-Only SQL/MX Statements (continued) 3. Embedded-Only SQL/MX Statements (continued) C Examples of BEGIN DECLARE SECTION 3-9 C++ Examples of BEGIN DECLARE SECTION 3-9 COBOL Examples of BEGIN DECLARE SECTION 3-10 CLOSE Statement 3-11 Considerations for CLOSE 3-11 C Examples of CLOSE 3-12 COBOL Examples of CLOSE 3-13 Compound (BEGIN...
Contents 3. Embedded-Only SQL/MX Statements (continued) 3.
3. Embedded-Only SQL/MX Statements (continued) Contents 3.
4. MXCI Commands (continued) Contents 4.
4. MXCI Commands (continued) Contents 4.
4. MXCI Commands (continued) Contents 4. MXCI Commands (continued) Examples of SHOWSHAPE 4-89 5.
5. SQL/MX Utilities (continued) Contents 5.
Contents 6. SQL/MX Language Elements (continued) 6.
6. SQL/MX Language Elements (continued) Contents 6.
7. SQL/MX Clauses Contents 7.
9. SQL/MX Functions and Expressions Contents 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
Contents 9. SQL/MX Functions and Expressions (continued) 9.
9. SQL/MX Functions and Expressions (continued) Contents 9.
10. Metadata Tables (continued) Contents 10.
10. Metadata Tables (continued) Contents 10.
A. Quick Reference Contents A. Quick Reference A B C D E F G H I L M O P R S T U V W A-1 A-1 A-1 A-2 A-2 A-3 A-3 A-3 A-3 A-3 A-4 A-4 A-4 A-4 A-4 A-5 A-5 A-5 A-5 B. Reserved Words Reserved SQL/MX and SQL/MP Identifiers SQL/MP Identifiers to Avoid B-5 B-1 C. Limits D.
D. Sample Database (continued) Contents D. Sample Database (continued) SUPPLIER Table D-10 PARTSUPP Table D-11 PARTLOC Table D-13 E. Standard SQL and SQL/MX ANSI SQL Standards E-1 ISO Standards E-2 SQL/MX Compliance E-2 SQL/MX Extensions to Standard SQL Character Set Support E-7 E-6 Index Figures Figure 5-1. Figure D-1. SQL/MX import Utility 5-31 Sample Database Tables D-2 Tables Table 1-1. Table 1-2. Table 1-3. Table 1-4. Table 1-5. Table 3-1. Table 3-2. Table 3-3. Table 3-4. Table 3-5. Table 6-1.
Contents HP NonStop SQL/MX Reference Manual—523725-004 xxx
What’s New in This Manual Manual Information HP NonStop SQL/MX Reference Manual Abstract This manual describes the syntax of SQL language elements—data types, expressions, functions, identifiers, literals, and predicates—and SQL statements of HP NonStop™ SQL/MX, the NonStop relational database management system based on ANSI SQL:1999. The manual also includes embedded SQL statements and MXCI commands. Product Version NonStop SQL/MX Releases 2.0 and 2.
New and Changed Information What’s New in This Manual New and Changed Information Changes to the G06.30 manual: Section New or Changed Information 1 SQL/MX Statements Deleted the description for NOT NULL [[NOT] DROPPABLE] on page 2-14 under ALTER TABLE Statement. 2 MXCI Commands • • • Updated the MXCI Command on page 4-40. Added an example for MXCI under Examples of MXCI Command on page 4-40. Updated the current Defaults for the SHOWCONTROL command on page 4-65.
New and Changed Information What’s New in This Manual Section New or Changed Information 1 Introduction Updated information in SKIP CONFLICT on page 1-8. 6 SQL/MX Language Elements Updated Restrictions on Using Character Set Data on page 6-3. Updated Numeric Data Types on page 6-17 to discuss floating-point data. Updated Partitions on page 6-82 with more information on hash partitioned tables. Updated SQL/MP Views on page 6-112. 8 SQL/MX File Attributes Updated MAXEXTENTS on page 8-8.
What’s New in This Manual New and Changed Information HP NonStop SQL/MX Reference Manual—523725-004 xxxiv
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.
Related Documentation About This Manual Section Description 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. Appendix B, Reserved Words Lists the words that are reserved in NonStop SQL/MX.
Related Documentation About This Manual Programming Manuals SQL/MX Programming Manual for C and COBOL Describes how to embed SQL/MX statements in ANSI C and COBOL programs. SQL/MX Programming Manual for Java Describes how to embed SQL/MX statements in Java programs according to the SQLJ standard. Specialized Guides SQL/MX Installation and Management Guide Describes how to plan for, install, create, and manage an SQL/MX database. Explains how to use installation and management commands and utilities.
Related Documentation About This Manual Glossary Help Terms and definitions from the SQL/MX Glossary. NSM/web Help Context-sensitive help topics that describe how to use the NSM/web management tool. Visual Query Planner Help Context-sensitive help topics that describe how to use the Visual Query Planner graphical user interface. The NSM/web and Visual Query Planner help systems are accessible from their respective applications.
Related Documentation About This Manual This figure shows the manuals in the SQL/MX library: Programming Manuals Introductory Guides SQL/MX Comparison Guide for SQL/MP Users SQL/MX Quick Start SQL/MX Programming Manual for C and COBOL SQL/MX Programming Manual for Java Reference Manuals SQL/MX Reference Manual SQL/MX Messages Manual SQL/MX Glossary SQL/MX Connectivity Service Administrative Command Reference DataLoader/MX Reference Manual Specialized Guides SQL/MX Installation and Management
Notation Conventions About This Manual Notation Conventions Icons These icons appear in the left margins of this manual. Each icon represents a specific context of the SQL/MX syntax and semantics. Embed Designates information that is specific to embedding SQL/MX statements in programs. This information applies to any of the supported programming languages. C/COBOL Designates information that is specific to embedding SQL/MX statements in C or COBOL programs.
General Syntax Notation About This Manual computer type. Computer type letters within text indicate C and Open System Services (OSS) keywords and reserved words. Enter these items exactly as shown. Items not enclosed in brackets are required. For example: myfile.c italic computer type. Italic computer type letters within text indicate C and Open System Services (OSS) variable items that you supply. Items not enclosed in brackets are required. For example: pathname [ ] Brackets.
Change Bar Notation About This Manual Punctuation. Parentheses, commas, semicolons, and other symbols not previously described must be entered as shown. For example: error := NEXTFILENAME ( file-name ) ; LISTOPENS SU $process-name.#su-name Quotation marks around a symbol such as a bracket or brace indicate the symbol is a required character that you must enter as shown. For example: "[" repetition-constant-list "]" Item Spacing.
1 Introduction NonStop SQL/MX allows you to use SQL/MX DML statements, which comply closely to ANSI SQL:1999, to access SQL/MP and SQL/MX databases.
MXCI SQL/MX Conversational Interface Introduction User metadata tables, such as the SYSTEM_DEFAULTS table, histogram tables, and other tables, contain SQL/MX metadata that the user rather than the system maintains. For more information, see Section 10, Metadata Tables. MXCI SQL/MX Conversational Interface MXCI, the SQL/MX conversational interface, is useful for running ad hoc queries and for comparing the relative efficiency of various queries.
Entering a Command Introduction Transactions Transaction modes set by the SET TRANSACTION statement for the next transaction in the session NAMETYPE value Attribute value ANSI or NSK that determines whether partiallyqualified object names in SQL statements executed in the session are logical names (ANSI) or Guardian physical names (NSK).
Transactions in MXCI Introduction All text between two hyphens and the end of the physical line is a comment. You can include a comment within a statement or command (but not within a literal) if you use more than one physical line to enter the statement or command. If you include comments in an MXCI command file, MXCI prints the comments along with the commands as it executes the file.
Security Introduction After you press the MXCI break key, the statement or command terminates, and MXCI returns this message and prompts you to enter another statement or command: ***WARNING[15033] Break was received. >> When you use the MXCI break key to terminate a transaction, the transaction might or might not be rolled back. Execute the SHOW SESSION command to determine the status of the transaction.
Guardian User ID Introduction Guardian User ID Each user authorized to log on to a node is identified by a Guardian user ID that consists of a group and user identification. The user ID has one of these forms: group_number,user_number or group_name.user_name Guardian Super ID Each node has one special user ID called the super ID that has Guardian group 255 and user number 255. The super ID has one of these forms: 255,255 or SUPER.SUPER The super ID can act as the owner of any object or file on the node.
SQL/MP Considerations Introduction The implementation for REPEATABLE READ and SERIALIZABLE access options is equivalent. This entry uses SERIALIZABLE for purposes of illustration. For information about transactions, see Transaction Isolation Levels on page 1-20. SQL/MP Considerations Note.
SKIP CONFLICT Introduction SERIALIZABLE (or REPEATABLE READ) provides the highest level of data consistency. A statement executing with this access option does not allow dirty reads, nonrepeatable reads, or phantoms. SKIP CONFLICT This option allows transactions to skip rows locked in a conflicting mode by another transaction. Do not use SKIP CONFLICT in a SET TRANSACTION statement. For more information on the skip conflict access method, see the SQL/MX Queuing and Publish/Subscribe Services.
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 Holder Introduction SHARE lock mode allows multiple users to lock and read the same data. EXCLUSIVE lock mode limits access to locked data to the lock holder and to other users who specify READ UNCOMMITTED (but not READ COMMITTED or SERIALIZABLE) access. Lock modes are the same when you choose READ COMMITTED or SERIALIZABLE access. Lock mode is sometimes determined by NonStop SQL/MX.
Transaction Management Introduction Transaction Management A transaction (a set of database changes that must be completed as a group) is the basic recoverable unit in case of a failure or transaction interruption. Transactions can be defined during an MXCI session or in a host program. The typical order of events is: 1. Transaction is started. 2. Database changes are made. 3. Transaction is committed.
Statement Atomicity Introduction Statement atomicity occurs if these conditions are met: • • • • The UPD_ABORT_ON_ERROR default must be set to OFF (the default.) The underlying table must not have referential integrity constraints, COMMENT materialized view logs, END COMMENT or triggers.
User-Defined and System-Defined Transactions Introduction For more information about the differences in auto-abort behavior between NonStop SQL/MP and NonStop SQL/MX, see the SQL/MX Comparison Guide for SQL/MP Users. User-Defined and System-Defined Transactions User-Defined Transactions Transactions you define are called user-defined transactions.
Concurrency Introduction If this option is set to ON, NonStop SQL/MX automatically commits any changes, or rolls back any changes, made to the database at the end of statement execution. AUTOCOMMIT is set ON by default at the start of an MXCI session. If this option is set to OFF, the current transaction remains active until the end of the MXCI session unless you explicitly commit or roll back the transaction. The default is OFF for embedded SQL in a C or COBOL program.
Concurrency Introduction Table 1-2 compares DDL and utility operations with DML operations and shows DDL operations you can start while DML operations are in progress: Table 1-2.
Concurrency Introduction Table 1-3.
Concurrency Introduction Table 1-4. Operations Effect on Table Timestamps (page 2 of 2) Alter Operation Timestamp Updated CREATE TRIGGER Yes, of the table on which the trigger is defined CREATE VIEW No DUP No FIXUP Yes GRANT No IMPORT Yes, if using fast load technique INFO No MODIFY, all forms Yes mxexportddl No MXGNAMES No POPULATE INDEX Yes PURGEDATA Yes RESTORE Yes** REVOKE No UPDATE STATISTICS No VERIFY No * Manual recompilation might be required.
Concurrency Introduction Table 1-5 lists concurrency limits on utilities. Table 1-5. Concurrency Limits on Utility Operations (page 1 of 2) DDL operations Utility DML operations Other utilities Utilities that only read metadata information: EXPORTDDL INFO MXGNAMES SHOWDDL SHOWLABEL VERIFY All DML operations (SELECT, UPDATE, DELETE, INSERT) can be performed concurrently. Any utility in this category can be performed concurrently. Not recommended.
Transaction Access Modes Introduction Table 1-5. Concurrency Limits on Utility Operations (page 2 of 2) Utility DML operations Other utilities Utilities that update data and potentially change metadata: FIXUP DUP (target table only) IMPORT using fast load MODIFY when dropping a hash partition PURGEDATA RESTORE Not allowed. Concurrent operations are not allowed. DDL operations Not allowed. * There are some exceptions.
Transaction Isolation Levels Introduction Transaction Isolation Levels A transaction has an isolation level that is either READ UNCOMMITTED, READ COMMITTED, or SERIALIZABLE or REPEATABLE READ. The SQL/MX implementation for REPEATABLE READ and SERIALIZABLE is equivalent. SERIALIZABLE is used for purposes of illustration. You can set the isolation level of a transaction explicitly by using a SET TRANSACTION statement. See SET TRANSACTION Statement on page 2-223.
Partition Management Introduction SERIALIZABLE or REPEATABLE READ This option locks all data accessed through the transaction and holds the locks on data in audited tables until the end of the transaction. SERIALIZABLE provides the highest level of data consistency. A transaction executing with this isolation level does not allow dirty reads, nonrepeatable reads, or phantoms.
Using NonStop SQL/MX to Access SQL/MP Databases Introduction NonStop SQL/MX provides support for nonstandard SQL/MP features so that you can develop applications that use these databases. However, when you use NonStop SQL/MX to access an SQL/MP database, you should be aware of some restrictions involving SQL/MP features that do not directly map to NonStop SQL/MX.
Naming Objects Introduction Naming Objects Refer to SQL/MP database objects through MXCI or through applications by using either physical names, logical names, or DEFINE names, as described next. For more information, see Database Object Names on page 6-12, Object Naming on page 10-47, or DEFINEs on page 6-36. Physical Names NonStop SQL/MP uses Guardian names as names for SQL tables, views, indexes, partitions, collations, and program modules.
Delimiting Reserved Words in Guardian Names Introduction For the complete syntax and semantics, see CREATE SQLMP ALIAS Statement on page 2-71. To use ANSI names with the DDL Statements for the Sample Database on page D-3, you must create an alias for each table that has been created. For example, suppose that you have created the EMPLOYEE table with the physical Guardian name $samdb.persnl.employee. To specify the logical name samdbcat.persnl.
Selecting or Changing Data Introduction Selecting or Changing Data To select or change SQL/MP data that does not directly map to SQL/MX data types and literals, you can use special extensions of NonStop SQL/MX with some restrictions. DATETIME Data The SQL/MP DATETIME data type is specified: DATETIME [start-field TO] end-field The start-field and end-field specify a range of logically contiguous fields: YEAR MONTH DAY HOUR MINUTE SECOND FRACTION [(precision)] The start-field must precede the end-field.
Selecting or Changing Data Introduction When you are storing values in a DATETIME column, you must explicitly cast the DATETIME value in question to the desired DATETIME data type to ensure compatibility. If extension occurs on the more significant end of a value, the values for the missing fields are drawn from the fields of CURRENT_TIMESTAMP. If extension occurs on the less significant end, the values are the minimum field values.
Selecting or Changing Data Introduction The start-ym and end-ym specify a range of logically contiguous fields: YEAR MONTH Day-Time Interval Specify a day-time duration: INTERVAL start-dt [(digits)] [TO end-dt] The start-dt and end-dt specify a range of logically contiguous fields: DAY HOUR MINUTE SECOND FRACTION [(precision)] The start-dt must precede the end-dt. The FRACTION field can include the precision option only if the FRACTION field is the end-dt.
Accessing Views Introduction NCHAR Data You can select NCHAR columns from SQL/MP tables. See NCHAR Columns in SQL/MP Tables on page 6-23. You can insert into or update NCHAR columns in SQL/MP tables only when the NCHAR data being written to the table contains an even number of bytes. A string literal you use this way can be specified: N'string' N associates the default character set with the string literal. The default is set by the value of the NATIONAL_CHARSET attribute.
SQL/MP Stored Text Introduction SQL/MP Stored Text You cannot access or manipulate SQL/MP tables or views that have been defined in specific ways. There are restrictions on specific types of SQL/MP stored text, which is SQL text that NonStop SQL/MX retrieves from the SQL/MP catalog while processing SQL/MX text. SQL/MP stored text includes views, constraints, column defaults, first keys, clustering keys, and partitioning keys.
SQL/MP File Organizations Introduction SQL/MP File Organizations An SQL/MP table can have one of three physical file organizations: key-sequenced, entry-sequenced, or relative.
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.
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 information on which SQL/MX statements you can embed in a particular language, see the SQL/MX Programming Manual for C and COBOL or the SQL/MX Programming Manual for Java.
Data Definition Language (DDL) Statements SQL/MX Statements CREATE SQLMP ALIAS Statement on page 2-71 Creates mappings from logical names to physical names for SQL/MP database objects. CREATE TABLE Statement on page 2-75 Creates a table. CREATE TRIGGER Statement on page 2-96 Creates a trigger. CREATE VIEW Statement on page 2-105 Creates a view. DROP CATALOG Statement on page 2-119 Drops an empty catalog. DROP INDEX Statement on page 2-120 Drops an index.
Data Manipulation Language (DML) Statements SQL/MX Statements REVOKE EXECUTE Statement on page 2-173 Revokes access privileges for a procedure to specified users. SET Statement on page 2-211 Controls the action of a BEFORE trigger. SIGNAL SQLSTATE Statement on page 2-227 Enables a trigger execution to raise an exception that causes both the triggered and triggering statements to fail.
Embedded-Only SQL/MX Statements SQL/MX Statements Embedded-Only SQL/MX Statements For information on SQL/MX statements that you can use only in embedded SQL programs, see Section 3, Embedded-Only SQL/MX Statements.
Alias Statements SQL/MX Statements default ANSI names for the catalog and schema or Guardian physical names for the volume and subvolume: SET CATALOG Statement on page 2-212 Sets the default ANSI catalog for unqualified schema names for the current session. SET MPLOC Statement on page 2-214 Sets the default operating system volume and subvolume for SQL/MP physical object 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-26 Alters a trigger. CREATE TRIGGER Statement on page 2-96 Creates a trigger. DROP TRIGGER Statement on page 2-132 Drops a trigger. SET Statement on page 2-211 Controls the action of a BEFORE trigger.
ALTER INDEX Statement SQL/MX Statements ALTER INDEX Statement Considerations for ALTER INDEX Examples of ALTER INDEX The ALTER INDEX statement modifies an SQL/MX index by changing one or more file attributes of the index. See Database Object Names on page 6-12. ALTER INDEX is an SQL/MX extension. ALTER INDEX [[catalog-name.]schema-name.]index ATTRIBUTE[S] attribute [,attribute ]...
Considerations for ALTER INDEX SQL/MX Statements Considerations for ALTER INDEX You cannot use ALTER INDEX to change a partition’s name. Authorization and Availability Requirements To alter an index, you must own its schema or be the super ID. All partitions of the index must be available when ALTER INDEX executes. The appropriate metadata tables must also be available.
ALTER SQLMP ALIAS Statement SQL/MX Statements ALTER SQLMP ALIAS Statement Considerations for ALTER SQLMP ALIAS Examples of ALTER SQLMP ALIAS The ALTER SQLMP ALIAS statement changes the physical name of an SQL/MP table to which an existing alias is mapped. ALTER SQLMP ALIAS is an SQL/MX extension. ALTER SQLMP ALIAS catalog.schema.object [\node.]$volume.subvol.filename Syntax Description of ALTER SQLMP ALIAS catalog.schema.object is the alias name of an SQL/MP table or view.
Examples of ALTER SQLMP ALIAS SQL/MX Statements Comparison With Previous Versions In SQL/MX releases earlier than SQL/MX Release 2.x, the maximum length of the alias name was 200 characters. Starting with these releases, the alias name is an ANSI name. The ALTER SQLMP ALIAS statement was not supported in product versions prior to SQL/MX Release 2.x.
ALTER TABLE Statement SQL/MX Statements ALTER TABLE Statement Considerations for ALTER TABLE Examples of ALTER TABLE The ALTER TABLE statement modifies an SQL/MX table by adding a column to the table, by adding or dropping a constraint on the table, or by changing one or more file attributes for the table. See Database Object Names on page 6-12.
ALTER TABLE Statement SQL/MX Statements default is: literal | NULL | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | {CURRENT_USER | USER} column-constraint is: UNIQUE | PRIMARY KEY [ASC[ENDING] | DESC[ENDING]] | CHECK (condition) | REFERENCES ref-spec table-constraint is: UNIQUE (column-list) | PRIMARY KEY (key-column-list) | CHECK (condition) | FOREIGN KEY (column-list) REFERENCES ref-spec column-list is: column-name [,column-name]...
Syntax Description of ALTER TABLE SQL/MX Statements Syntax Description of ALTER TABLE table specifies the name of the table to alter. See Database Object Names on page 6-12. ADD [COLUMN] column-definition adds a column to table. The clauses for the column-definition are specified as: column-name specifies the name for the new column in the table. Column-name is an SQL identifier. column-name must be unique among column names in the table.
Syntax Description of ALTER TABLE SQL/MX Statements HEADING 'heading-string'| NO HEADING specifies a string heading-string of 0 to 128 characters to use as a heading for the column if it is displayed with a SELECT statement in MXCI. The heading-string can contain characters only from the ISO88591 character set. The default heading is column, the column name. If you specify a heading that is identical to the column name, INVOKE and SHOWDDL do not display that heading.
Syntax Description of ALTER TABLE SQL/MX Statements the PRIMARY KEY constraint for the table. Columns you define as unique must be specified as NOT NULL. A UNIQUE constraint is enforced with a unique index. If there is already a user-defined unique index on column-list, NonStop SQL/MX uses this index; if not, the system creates a unique index. The maximum combined length of the columns for a UNIQUE constraint is 255 bytes.
Syntax Description of ALTER TABLE SQL/MX Statements NonStop SQL/MX checks the condition whenever an operation occurs that might affect its value. The operation is allowed if the predicate in the search condition evaluates to TRUE or null, but is prohibited if the predicate evaluates to FALSE. When a check constraint is added, existing data is checked for violations.
Syntax Description of ALTER TABLE SQL/MX Statements update rule specifies what referential action is taken when column-list in referenced-table is updated. If no ON UPDATE clause is specified, a default of ON UPDATE NO ACTION is assumed. delete rule specifies what referential action is taken when a row in referenced-table is deleted. If no ON DELETE clause is specified, a default of ON DELETE NO ACTION is assumed.
Syntax Description of ALTER TABLE SQL/MX Statements If you specify CASCADE and referential constraints are dependent on the constraint, those dependent constraints are dropped in addition to the specified constraint being dropped. If you drop a constraint, NonStop SQL/MX drops its dependent index if SQL/MX originally created the same index. If the constraint uses an existing index, the index is not dropped. The default is RESTRICT. CONSTRAINT constraint specifies a name for the column or table constraint.
Syntax Description of ALTER TABLE SQL/MX Statements specify on a PRIMARY KEY constraint cannot match the set of columns on any UNIQUE constraint for the table. ASCENDING and DESCENDING specify the direction for entries in each column within the key. The default is ASCENDING. The PRIMARY KEY value in each row of the table must be unique within the table. Columns within a PRIMARY KEY cannot contain nulls. A PRIMARY KEY defined for a set of columns implies that the column values are unique and not null.
Syntax Description of ALTER TABLE SQL/MX Statements table can contain only values that match those in a column or set of columns specified in the REFERENCES clause. The two columns or sets of columns must have the same characteristics (data type, length, scale, precision), and there must be a UNIQUE or PRIMARY KEY constraint on the column or set of columns specified in the REFERENCES clause.
Considerations for ALTER TABLE SQL/MX Statements Unlike NonStop SQL/MP’s form of this statement, SQL/MX’s ALTER TABLE statement has no PARTONLY clause. When you supply a new value for attributes, ALTER TABLE modifies the value of the attribute on all partitions of the table. For more detail, see the entry for a specific attribute. Considerations for ALTER TABLE You cannot use ALTER TABLE to change a partition’s name.
Considerations for ALTER TABLE SQL/MX Statements secondary extent size and MAXEXTENTS values as the base table's primary partition.The index is created on the same volume as the base table's primary partition. NonStop SQL/MX then populates the new index. After NonStop SQL/MX populates the index, you should perform a FUP RELOAD on the index and all its partitions, to organize the index structure more efficiently and to reduce index levels.
Examples of ALTER TABLE SQL/MX Statements SQL/MX Extensions to ALTER TABLE These clauses are SQL/MX extensions: • • ATTRIBUTES clause ASCENDING and DESCENDING options on the PRIMARY KEY constraint Examples of ALTER TABLE • This example adds a UNIQUE table constraint: ALTER TABLE persnl.project ADD CONSTRAINT projtimestamp_uc UNIQUE (projcode, ship_timestamp); • This example drops a constraint: ALTER TABLE persnl.
Examples of ALTER TABLE SQL/MX Statements CITY CHAR(15), MGR CHAR(3), UNIQUE (PNUM), FOREIGN KEY (MGR) REFERENCES STAFF_M(EMPNUM)); ALTER TABLE STAFF_M ADD FOREIGN KEY (PRI_WK) REFERENCES PROJ_M (PNUM); Suppose further that you now need to drop the foreign key. Use SHOWDDL to obtain the key’s system identification: >>showddl staff_m; CREATE TABLE NIST_EMB_CAT.SUN.
Examples of ALTER TABLE SQL/MX Statements ALTER TABLE NIST_EMB_CAT.SUN.STAFF_M ADD CONSTRAINT NIST_EMB_CAT.SUN.STAFF_M_187893997_9541 UNIQUE (EMPNUM) DROPPABLE ; ALTER TABLE NIST_EMB_CAT.SUN.STAFF_M ADD CONSTRAINT NIST_EMB_CAT.SUN.STAFF_M_859182618_9541 FOREIGN KEY (PRI_WK) REFERENCES NIST_EMB_CAT.SUN.PROJ_M(PNUM) DROPPABLE ; --- SQL operation complete.
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.
BEGIN WORK Statement SQL/MX Statements BEGIN WORK Statement The BEGIN WORK statement enables you to start a transaction explicitly—where the transaction consists of the set of operations defined by the sequence of SQL statements that begins immediately after BEGIN WORK and ends with the next COMMIT or ROLLBACK statement. See Transaction Management on page 1-11. BEGIN WORK is an SQL/MX extension.
C Examples of BEGIN WORK SQL/MX Statements C Examples of BEGIN WORK • Begin a transaction, execute an UPDATE statement, and test SQLSTATE. If the UPDATE is successful, the database changes are committed. Otherwise, the database changes are rolled back: ... char SQLSTATE_OK[6] = "00000"; EXEC SQL BEGIN DECLARE SECTION; char SQLSTATE[6]; ... EXEC SQL END DECLARE SECTION; ... EXEC SQL BEGIN WORK; /* Start a transaction. ... EXEC SQL UPDATE ... ; /* Change the database. ...
CALL Statement SQL/MX Statements CALL Statement Considerations for CALL Examples of CALL The CALL statement invokes a stored procedure in Java (SPJ) in NonStop SQL/MX. To develop, deploy, and manage SPJs in NonStop 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.
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 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-145.
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-11. COMMIT [WORK] WORK is an optional keyword that has no effect.
C Examples of COMMIT WORK SQL/MX Statements The transaction must add the order for terminals to PARTSUPP, add the supplier to the SUPPLIER table, and update QTY_ON_HAND in PARTLOC. After the INSERT and UPDATE statements execute successfully, you commit the transaction, as shown, within MXCI: -- This statement initiates a transaction. BEGIN WORK; --- SQL operation complete. -- This statement inserts a new entry into PARTSUPP. INSERT INTO invent.partsupp VALUES (5100, 17, 800.00, 24); --- 1 row(s) inserted.
COBOL Examples of COMMIT WORK SQL/MX Statements COBOL Examples of COMMIT WORK • Begin a transaction, execute an UPDATE statement, and test SQLSTATE. If the UPDATE is successful, the database changes are committed. Otherwise, the database changes are rolled back. ... 01 SQLSTATE-OK PIC X(5) VALUE "00000". EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 SQLSTATE PIC X(5). ... EXEC SQL END DECLARE SECTION END-EXEC. ... * Start a transaction. EXEC SQL BEGIN WORK END-EXEC. ... * Change the database.
CONTROL QUERY DEFAULT Statement SQL/MX Statements CONTROL QUERY DEFAULT Statement The CONTROL QUERY DEFAULT statement changes the system-level default settings for the current process. Execution of this statement does not change the contents of the SYSTEM_DEFAULTS table. See System Defaults Table on page 10-29. CONTROL QUERY DEFAULT is an SQL/MX extension.
Examples of CONTROL QUERY DEFAULT SQL/MX Statements Relationship to CONTROL TABLE Use the CONTROL QUERY DEFAULT statement to override system-level default settings for various attributes for all tables in the current process. Use the CONTROL TABLE statement to override system-level default settings for the TABLELOCK, TIMEOUT, and SIMILARITY_CHECK attributes per table or for all tables in the current process.
CONTROL QUERY SHAPE Statement SQL/MX Statements CONTROL QUERY SHAPE Statement Considerations for CONTROL QUERY SHAPE Examples of CONTROL QUERY SHAPE The CONTROL QUERY SHAPE statement forces access plans. You can generate the result of the EXPLAIN function for a prepared DML statement, and then modify the operator tree for the statement’s access plan, by using CONTROL QUERY SHAPE. Both the EXPLAIN function and the CONTROL QUERY SHAPE statement use similar identifiers for the nodes of an operator tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements scan-option is: TABLE table | PATH {access-path | ANY} | BLOCKS_PER_ACCESS value | MDAM mdam-option,... | MDAM_COLUMNS mdam-columns-option,... mdam-option is: OFF | SYSTEM | FORCED mdam-columns-option is: n | SYSTEM | ALL | (density,...) | SYSTEM (density,...) | ALL (density,...) density is: SPARSE | DENSE | SYSTEM query-shape-options IMPLICIT { SORT | EXCHANGE | EXCHANGE_AND_SORT } makes SORT, EXCHANGE, or ENFORCER nodes in CONTROL QUERY SHAPE optional.
CONTROL QUERY SHAPE Statement SQL/MX Statements statement can still contain additional enforcer nodes, and the compiler will enforce such nodes. Note that WITHOUT ENFORCERS does not mean that the statement or the generated plans are free of enforcer nodes. shape specifies the operator tree for an access plan for the next query to be executed within the current session. shape defines this operator tree recursively by using a LISP-like expression to represent the nodes of the tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements INDEX_SCAN Replaces a SCAN node in operator tree. JOIN Replaces a JOIN node in operator tree. NESTED_JOIN Replaces a NESTED_JOIN in operator tree. MERGE_JOIN Replaces a MERGE_JOIN in operator tree. HASH_JOIN (cut,cut) or HJ (cut,cut) Replaces a HYBRID_HASH_JOIN or ORDERED_HASH_JOIN in operator tree. HYBRID_HASH_JOIN (cut,cut) or HHJ (cut,cut) Replaces a HYBRID_HASH_JOIN in operator tree.
CONTROL QUERY SHAPE Statement SQL/MX Statements {SCAN | FILE_SCAN | INDEX_SCAN} [(scan-option,...)] specifies these options that you can use with SCAN, FILE_SCAN, or INDEX_SCAN: TABLE table specifies a table or correlation name. table is a character string literal—for example, 't1'. PATH {access-path | ANY} access-path specifies an index name or the table name table. It is a character string literal—for example, 'ix1' or 't1'. Use this option to force the scan to be on that particular index or base table.
CONTROL QUERY SHAPE Statement SQL/MX Statements MDAM_COLUMNS mdam-columns-option,... specifies these MDAM_COLUMNS options: n specifies n key columns to be used by MDAM. For example, if MDAM is using key columns specified by an index defined on a table, n specifies that the first n columns listed in the index are used. The enumeration algorithm for each column is determined by the system. This option is the same as ALL if n exceeds the total number of columns that MDAM can use.
Considerations for CONTROL QUERY SHAPE SQL/MX Statements ALL (density,...) forces an enumeration algorithm to be used by MDAM for each key column as determined by the density list. All the remaining columns are used by MDAM, and their enumeration algorithms are determined by the system. For more information, see the SQL/MX Query Guide.
Examples of CONTROL QUERY SHAPE SQL/MX Statements By using the SET SHOWSHAPE command, you can inspect the default plan generated by the optimizer: SET SHOWSHAPE ON; SELECT * FROM EMPLOYEE, DEPT WHERE EMPLOYEE.DEPTNUM = DEPT.DEPTNUM AND EMPLOYEE.
Examples of CONTROL QUERY SHAPE SQL/MX Statements or SCAN (TABLE 'T1', PATH ANY) ° Scan table T1 using the base table. You want the system to choose whether to use MDAM. SCAN (TABLE 'T1', PATH 'T1') ° Scan table T1 using the index IT1. You want the system to choose whether to use MDAM. SCAN (TABLE 'T1', PATH 'IT1') ° Scan table T1 using the index IT1. You want to disable MDAM. SCAN (TABLE 'T1', PATH 'IT1', MDAM OFF) ° Scan table T1 using MDAM on index IT1.
Examples of CONTROL QUERY SHAPE SQL/MX Statements parser/SqlParser.y regress/compGeneral/EXPECTED018 regress/compGeneral/TEST018 • This example shows how a scan can be forced to use an index: >>prepare xx from +>select * from part where p_partkey = (select max(ps_partkey) from partsupp); --- SQL command prepared. >>display_explain options 'f' xx; LC RC OP OPERATOR OPT DESCRIPTION CARD --- --- --- -------------------- -------- ------------------- ------9 . 10 1.00E+0 5 8 9 1.00E+0 7 . 8 1.00E+0 6 . 7 1.
Examples of CONTROL QUERY SHAPE SQL/MX Statements max(ps_partkey) from partsupp); --- SQL command prepared. >>display_explain options 'f' xx; LC RC OP OPERATOR OPT DESCRIPTION CARD --- --- --- -------------------- -------- ------------------- ------13 . 14 root 1.00E+0 5 12 13 nested_join 1.00E+0 8 11 12 nested_join 1.00E+0 10 . 11 split_top 1.00E+0 9 . 10 partition_access 1.00E+0 . . 9 file_scan_unique fr 1.00E+0 7 . 8 split_top 6.66E+6 6 . 7 partition_access 6.66E+6 . . 6 index_scan fr 6.66E+6 4 .
CONTROL TABLE Statement SQL/MX Statements CONTROL TABLE Statement Considerations for CONTROL TABLE Examples of CONTROL TABLE The CONTROL TABLE statement specifies a performance-related option for DML accesses to a table or view. This statement can also be used as an embedded SQL compiler directive. CONTROL TABLE is an SQL/MX extension.
CONTROL TABLE Statement SQL/MX Statements OFF directs NonStop SQL/MX not to use MDAM. PRIORITY 'priority-value' specifies the priority for subsequent file system requests to the Data Access Manager (DAM). DAM uses the priority to ensure efficient performance within a mixed workload environment. Short-duration OLTP-type requests should specify a higher priority than any concurrent long-duration query requests. 'priority-value' specifies the priority, an integer value from 1 to 9. The default priority is 3.
Considerations for CONTROL TABLE SQL/MX Statements error. This option is for static operations only. For dynamic operations, see SET TABLE TIMEOUT Statement on page 2-218. '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.
Examples of CONTROL TABLE SQL/MX Statements A CONTROL TABLE table statement overrides the effect of a CONTROL TABLE * statement for the specified table or view. Relationship to CONTROL QUERY DEFAULT 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.
CREATE CATALOG Statement SQL/MX Statements CREATE CATALOG Statement Considerations for CREATE CATALOG Examples of CREATE CATALOG The CREATE CATALOG statement creates a new SQL/MX catalog. See Catalogs on page 6-2. CREATE CATALOG is an SQL/MX extension. CREATE CATALOG catalog [LOCATION [\node.]$volume] Syntax Description of CREATE CATALOG catalog is an SQL identifier that specifies the name of the new catalog. catalog must be unique among catalog names on the node. LOCATION [\node].
Examples of CREATE CATALOG SQL/MX Statements Examples of CREATE CATALOG • This example creates a catalog: CREATE CATALOG samdbcat; HP NonStop SQL/MX Reference Manual—523725-004 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-12. CREATE INDEX is an SQL/MX extension. CREATE [UNIQUE] INDEX index ON table (column-name [ASC[ENDING] | DESC[ENDING]] [,column-name [ASC[ENDING] | DESC[ENDING]]]...) [populate-option] [file-option]...
Syntax Description of CREATE INDEX SQL/MX Statements Syntax Description of CREATE INDEX UNIQUE specifies that the values (including NULL values) in the column or set of columns that make up the index field cannot contain more than one occurrence of the same value or set of values. For indexes with multiple columns, the values of the columns as a group determines uniqueness, not the values of the individual columns. If you omit UNIQUE, duplicate values are allowed.
Syntax Description of CREATE INDEX SQL/MX Statements constraint. You can populate an offline index and remove its offline designation by using the POPULATE INDEX utility. POPULATE Specifies that the index is to be created and populated. If you omit the populate-option, the default is POPULATE LOCATION [\node.]$volume[.subvolume.file-name] [NAME partition-name] specifies a node and volume for the primary partition of the index. node is the name of a node on the Expand network.
Syntax Description of CREATE INDEX SQL/MX Statements {[RANGE] PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD range-partn-defn [,ADD range-partn-defn]...)] defines secondary partitions for a range partitioned table. For information about partitions, see Partitions on page 6-82. 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 ADD partn-defn defines a single secondary hash partition and includes the LOCATION of the partition. LOCATION [\node.]$volume[.subvolume.file-name] [NAME partition-name] specifies a volume and optionally the node, subvolume, and filename for the partition. node is the name of a node on the Expand network.
Considerations for CREATE INDEX SQL/MX Statements ATTRIBUTE[S] attribute [,attribute]... specifies file attributes for the key-sequenced file that holds the index. In an ATTRIBUTES clause that is within a PARTITION clause, you must separate attributes with a space. In ATTRIBUTES clauses in other places, you can separate attributes with either a space or a comma. File attributes you can specify are: ALLOCATE/DEALLOCATE on page 8-2 Controls amount of disk space allocated.
Examples of CREATE INDEX SQL/MX Statements Authorization and Availability Requirements To create an SQL/MX index, you must own the schema for the underlying table or be the super ID, and have access to all partitions of the underlying table. CREATE INDEX locks out INSERT, DELETE, and UPDATE operations on the table being indexed. If other processes have rows in the table locked when the operation begins, CREATE INDEX waits until its lock request is granted or timeout occurs.
CREATE PROCEDURE Statement SQL/MX Statements CREATE PROCEDURE Statement Considerations for CREATE PROCEDURE Examples of CREATE PROCEDURE The CREATE PROCEDURE statement registers an existing Java method as a stored procedure in Java (SPJ) within NonStop SQL/MX. To develop, deploy, and manage SPJs in SQL/MX, see the SQL/MX Guide to Stored Procedures in Java.
CREATE PROCEDURE Statement SQL/MX Statements procedure-ref specifies an ANSI logical name of the form: [[catalog-name.]schema-name.]procedure-name where each part of the name is a valid SQL identifier with a maximum of 128 characters. For information, see Identifiers on page 6-54. The procedure-name must be unique among the names of tables, views, SQL/MP aliases, and procedures within its schema. NonStop SQL/MX does not support the overloading of procedure names.
CREATE PROCEDURE Statement SQL/MX Statements sql-identifier specifies an SQL identifier that describes the parameter. For more information, see Identifiers on page 6-54. 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... CHAR[ACTER]* CHAR[ACTER] VARYING * VARCHAR* PIC[TURE] X * NCHAR NCHAR VARYING NATIONAL CHAR[ACTER] NATIONAL CHAR[ACTER] VARYING java.lang.String DATE java.sql.
CREATE PROCEDURE Statement SQL/MX Statements EXTERNAL NAME 'java-method-name [java-signature]' java-method-name specifies the case-sensitive name of the SPJ method of the form: [package-name.]class-name.method-name The Java method must exist in a Java class file, class-name.class, in the OSS directory, or the JAR file path specified by the EXTERNAL PATH clause. The Java method must be defined as public and static and have a return type of void.
CREATE PROCEDURE Statement SQL/MX Statements PARAMETER STYLE JAVA specifies that the run-time conventions for arguments passed to the external user-defined routine are those of the Java language. LOCATION procedure-label specifies a Guardian physical name and location for the stored procedure label. For more information on the procedure label, see the SQL/MX Guide to Stored Procedures in Java. [\node.]$volume[.subvolume.filename] node is the name of a node on the Expand network.
Considerations for CREATE PROCEDURE SQL/MX Statements DYNAMIC RESULT SETS integer specifies the maximum number of result sets that the SPJ can return. NonStop SQL/MX does not support result sets. If you specify this clause, you must set the value to 0 (zero). NOT DETERMINISTIC | DETERMINISTIC specifies whether the SPJ always returns the same values for OUT and INOUT parameters for a given set of argument values (DETERMINISTIC) or does not return the same values (NOT DETERMINISTIC, the default option).
Examples of CREATE PROCEDURE SQL/MX Statements which are SAMDBCAT and SALES in this case. To call this SPJ, use this statement: CALL lowerprice(); • This CREATE PROCEDURE statement registers the SPJ named TOTALPRICE, which accepts three input parameters and returns a numeric value, the total price, to an INOUT parameter: CREATE PROCEDURE samdbcat.sales.totalprice(IN NUMERIC (18), IN VARCHAR (10), INOUT price NUMERIC (18,2)) EXTERNAL NAME 'pkg.subpkg.Sales.totalPrice' EXTERNAL PATH '/usr/mydir/myJar.
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-104. CREATE SCHEMA with the optional subvolume name is an SQL/MX extension. CREATE SCHEMA schema-clause [schema-element [, schema-element] ...
Syntax Description of CREATE SCHEMA SQL/MX Statements RDF backup database. In this case, the subvolume name for each backup schema should match the subvolume name for the corresponding schema in the primary database. In either case, the schema subvolume is written to the SCHEMATA.SCHEMA_SUBVOLUME column in the SQL/MX system schema. The schema subvolume is used as the subvolume for the locations of all objects created within that schema.
Considerations for CREATE SCHEMA SQL/MX Statements 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. However, NonStop SQL/MX does not prevent you from specifying a subvolume name that is already in use by another schema. If you do, a Guardian wild card of the form \system.$*.subvolume.
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 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. You can map the same SQL/MP table or view to multiple different ANSI names in the same catalog and schema and in different catalogs and schemas. For example, you can create these four mappings for a single SQL/MP table or view: cat1.sch1.obj1 cat1.sch1.obj2 cat2.sch1.obj2 cat2.sch2.
Considerations for CREATE SQLMP ALIAS SQL/MX Statements Embedding the Statement in an SQL Program Embed If you embed a CREATE SQLMP ALIAS statement in a static SQL program, subsequent references in the same program to the SQL/MP alias cause compilation errors because the alias does not reside in the OBJECTS table. To avoid these errors, create logical name mappings separately before compiling static SQL programs that refer to the SQL/MP alias.
Examples of CREATE SQLMP ALIAS SQL/MX Statements Examples of CREATE 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 metadata table: CREATE SQLMP ALIAS mycatalog.myschema.mytable $myvol.mysubvol.
CREATE TABLE Statement SQL/MX Statements CREATE TABLE Statement Considerations for CREATE TABLE Examples of CREATE TABLE The CREATE TABLE statement creates an SQL/MX table. See Database Object Names on page 6-12. CREATE TABLE table { (table-element [,table-element]...) | like-spec } [file-option ]...
CREATE TABLE Statement SQL/MX Statements default is: literal | NULL | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | {CURRENT_USER | USER} column-constraint is: NOT NULL [[NOT] DROPPABLE] | UNIQUE | PRIMARY KEY [ASC[ENDING] | DESC[ENDING]] [[NOT] DROPPABLE] | CHECK (condition) | REFERENCES ref-spec ref-spec is: referenced-table [(column-list)] [referential triggered action] referential triggered action is: update rule [delete rule] | delete rule [update rule] update rule is: ON UPDATE referential actio
Syntax Description of CREATE TABLE SQL/MX Statements store-option is: PRIMARY KEY | (key-column-list) partn-file-option is { [RANGE] PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD range-partn-defn [,ADD range-partn-defn]...)] | HASH PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD partn-defn [,ADD partn-defn]...)]} FIRST KEY {col-value | (col-value [,col-value ]...)} LOCATION [\node.]$volume[.subvolume.
Syntax Description of CREATE TABLE SQL/MX Statements data-type is the data type of the values that can be stored in column. A default value must be of the same type as the column, including the character set for a character column. See Data Types on page 6-16. DEFAULT default | NO DEFAULT specifies a default value for the column or specifies that the column does not have a default value. See DEFAULT Clause on page 7-2.
Syntax Description of CREATE TABLE SQL/MX Statements NOT DROPPABLE specifies that the NOT NULL constraint is permanent. Less space is required to store a column if the column has a permanent NOT NULL constraint, and updates and inserts are faster. If the NOT NULL constraint does not include the [NOT] DROPPABLE clause, the value of the NOT_NULL_CONSTRAINT_DROPPABLE_OPTION attribute in the SYSTEM_DEFAULTS table is the default value for [NOT] DROPPABLE.
Syntax Description of CREATE TABLE SQL/MX Statements For both a DROPPABLE and NOT DROPPABLE PRIMARY KEY, the maximum combined length of the columns is 255 bytes. When a UNIQUE or PRIMARY KEY constraint is created on a table, all the constraint columns must have a NOT NULL clause in the CREATE TABLE statement.
Syntax Description of CREATE TABLE SQL/MX Statements subqueries in a CHECK constraint. CHECK constraints cannot contain non-ISO88591 string literals. REFERENCES ref-spec specifies a references column constraint. The maximum combined length of the columns for a REFERENCES constraint is 255 bytes.
Syntax Description of CREATE TABLE SQL/MX Statements ANSI SQL-99 standard: NO ACTION referential action means that the referential check is made at the end of the SQL statement. An error is raised when the referential constraint is violated. NonStop SQL/MX does not support NO ACTION referential action in the way it is specified by ANSI SQL-99.
Syntax Description of CREATE TABLE SQL/MX Statements key-column-list bases the clustering key on the columns in the key-column-list. The key columns in key-column-list must be specified as NOT NULL NOT DROPPABLE and cannot have a combined length of more than 247 bytes. The default is PRIMARY KEY if you specified a PRIMARY KEY clause that has the NOT DROPPABLE constraint in the CREATE TABLE statement.
Syntax Description of CREATE TABLE SQL/MX Statements partn-file-option is defined as: {[RANGE] PARTITION [BY (partitioning-column [,partitioning-column]...)] [(ADD range-partn-defn [,ADD range-partn-defn]...)] defines secondary partitions for a range partitioned table. BY (partitioning-column [,partitioning-column]...) specifies the partitioning columns. The default is the default partitioning key created by the STORE BY clause. Partitioning character columns must derive from the ISO88591 character set.
Syntax Description of CREATE TABLE SQL/MX Statements 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 partition and includes the LOCATION of the partition. LOCATION [\node.]$volume[.subvolume.file-name] [NAME partition-name] specifies a volume and optionally the node, subvolume, and filename for the partition. node is the name of a node on the Expand network.
Syntax Description of CREATE TABLE SQL/MX Statements ATTRIBUTE[S] attribute [,attribute]... specifies attributes of the physical file that holds the table. In an ATTRIBUTES clause that is within a PARTITION clause, you must separate attributes with a 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.
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 Reduced Space Requirements for NOT DROPPABLE Constraints Using the NOT DROPPABLE option on a NOT NULL constraint reduces the space required for the table. A column that allows nulls—or that might allow nulls at some later time—uses two extra bytes in each row to store the null indicator. If you specify that the NOT NULL constraint is NOT DROPPABLE, NonStop SQL/MX creates the table without these extra bytes.
Considerations for CREATE TABLE SQL/MX Statements Creating Partitions Automatically NonStop SQL/MX uses Partition Overlay Specification (POS) so that MXCS and JDBC/MX users can automatically create hash-partitioned tables with the CREATE TABLE statement. NonStop SQL/MX does not support automatic creation of rangepartitioned tables. Applications can control whether POS is enabled, the number of partitions, and the physical location of the partitions.
Examples of CREATE TABLE SQL/MX Statements NonStop SQL/MX will place the primary partition on $VOL1, the second partition on $VOL2, and the third partition on $VOL3. 2. Suppose that you have specified POS_NUM_OF_PARTNS as 5, and you have listed three locations in POS_LOCATIONS, $VOL1, $VOL2, and $VOL3. NonStop SQL/MX will place the primary partition on $VOL1, the second partition on $VOL2, the third partition on $VOL3, the fourth on $VOL1, and the fifth on $VOL2. 3.
Examples of CREATE TABLE SQL/MX Statements unit_price NUMERIC (8,2) NO DEFAULT NOT NULL, qty_ordered NUMERIC (5) UNSIGNED NO DEFAULT NOT NULL, PRIMARY KEY (ordernum, partnum) NOT DROPPABLE ) STORE BY PRIMARY KEY; • This example creates a table stored by the key column list. The clustering key is ordernum, partnum, SYSKEY. CREATE TABLE SALES.
Examples of CREATE TABLE SQL/MX Statements ( A INT NO DEFAULT -- NOT NULL NOT DROPPABLE , B INT DEFAULT NULL , CONSTRAINT J1.SCH1.TAB1_264669593_1268 PRIMARY KEY (A ASC) NOT DROPPABLE , CONSTRAINT J1.SCH1.TAB1_535649593_1268 CHECK (J1.SCH1.TAB1.A IS NOT NULL) NOT DROPPABLE ) LOCATION \CARNAG.$SARA.ZSDCL87P.DMP33T00 NAME CARNAG_SARA_ZSDCL87P_DMP33T00 ATTRIBUTES EXTENT (1024, 1024), MAXEXTENTS 16 PARTITION ( ADD FIRST KEY (2) LOCATION \CARNAG.$HIJO.ZSDCL87P.
Examples of CREATE TABLE SQL/MX Statements NAME CARNAG_CHINA_ZSDCL87P_S1645W00 EXTENT (1024, 1024) MAXEXTENTS 16 ) STORE BY (A ASC) ; --- SQL operation complete. >> • This example creates table mytable with hash partitions.
SQL/MX Statements • Examples of CREATE TABLE 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 5. CREATE TABLE SALES.
CREATE TRIGGER Statement SQL/MX Statements CREATE TRIGGER Statement Considerations for CREATE TRIGGER Examples of CREATE TRIGGER The CREATE TRIGGER statement is used to create triggers on SQL/MX tables. A trigger is a mechanism that sets up the database system to perform certain actions automatically in response to the occurrence of specified events.
Syntax Description of CREATE TRIGGER SQL/MX Statements column-name specifies the ANSI logical name of the column to be inserted, deleted, or updated when the trigger is activated, of the form: [[catalog-name.]schema-name.]column-name where each part of the name is a valid SQL identifier with a maximum of 128 characters. table-name specifies the ANSI logical name of the table this trigger is defined on, of the form: [[catalog-name.]schema-name.
Considerations for CREATE TRIGGER SQL/MX Statements insert-statement is an insert statement to be performed when this trigger is activated. signal-statement is a statement to be sent to the SIGNAL statement. set-new-statement is an assignment statement that can be used as a BEFORE-trigger action to assign values to transition variables representing columns in the subject table modified by the triggering action. quoted-sqlstate is the five-digit SQLSTATE to be passed to SIGNAL.
Considerations for CREATE TRIGGER SQL/MX Statements Authorization and Availability Requirements To create a trigger, you must own the schema where the trigger is defined and the schema where the subject table of the schema resides and you must have REFERENCES privileges on the columns used on the referenced table. Otherwise, you must be the super ID. Trigger Types You can configure triggers as BEFORE or AFTER types. When a triggering statement occurs, this is the order of execution: 1. 2. 3. 4.
Considerations for CREATE TRIGGER SQL/MX Statements • To massage data prior to the insert or update operation that caused the trigger to be activated (using the SET statement as an action.) BEFORE-type trigger operations are exercised as tentative executions. The triggering statement is executed but assigns values to the NEW ROW transition variables rather than to the subject table. That table appears not to be affected by the tentative execution.
Considerations for CREATE TRIGGER SQL/MX Statements • You cannot define triggers on SQL/MP objects. SQL/MP objects cannot be referenced in a trigger. Recompilation and Triggers User applications that change (INSERT, UPDATE, or DELETE) information in a table are automatically recompiled when a trigger with a matching event is added or dropped. User applications that use a SELECT on the subject table do not require recompilation.
Examples of CREATE TRIGGER SQL/MX Statements Keep this limit in mind when you create tables. If you plan to create triggers on a table, its primary key length cannot exceed 239 bytes. A table which will not have triggers can have a primary key of 255 bytes. Rowsets SQL/MX rowsets are allowed in UPDATE and DELETE statements that are trigger events. UPDATE and DELETE statements that use rowset arrays perform multiple executions of UPDATE or DELETE statements.
Examples of CREATE TRIGGER SQL/MX Statements ATTRIBUTES EXTENT (1024,1024) MAXEXTENTS 700 LOCATION $D00001.ZSDDEMO1.PRSCR000; You can create a BEFORE trigger on prescription so that when a prescription is entered, if the prescribed drug is found in generic_drugs, a generic drug is substituted for the brand name drug, and the instructions for the drugs are updated: CREATE TRIGGER alternate_drug BEFORE INSERT ON prescription REFERENCING NEW AS newdrug FOR EACH ROW WHEN (upshift(newdrug.
SQL/MX Statements Examples of CREATE TRIGGER This embedded DML statement inserts 10 rows into table tab1. EXEC SQL insert into cat.sch.tab1 values (:ArrayA); If trigger trg1 is defined as an insert statement trigger on tab1,and trg2 is defined as an insert row trigger on tab1, when the DML statement is executed, the two triggers are fired. The action of trg1 executes once for the entire statement, while trg2 executes ten times, once for each element in the rowset.
CREATE VIEW Statement SQL/MX Statements CREATE VIEW Statement Considerations for CREATE VIEW Examples of CREATE VIEW The CREATE VIEW statement creates an SQL/MX view. See Views on page 6-111. 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 information, see Identifiers on page 6-54. (column-name [heading] [,column-name [heading]]...
Syntax Description of CREATE VIEW SQL/MX Statements 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 WHERE clause of the query expression must evaluate to TRUE for any row that is inserted or updated. If you omit this option, a newly inserted row or an updated row need not satisfy the view definition, which means that such a row can be inserted or updated in the table but does not appear in the view. This check is performed each time a row is inserted or updated.
Examples of CREATE VIEW SQL/MX Statements An updatable view is insertable if the column list does not include a SYSKEY from the underlying base table. Examples of CREATE VIEW • This example creates a view on a single table without a view column list: CREATE VIEW SALES.MYVIEW1 AS SELECT ordernum, qty_ordered FROM SALES.ODETAIL; • This example creates a view with a column list: CREATE VIEW SALES.MYVIEW2 (v_ordernum, t_partnum) AS SELECT v.ordernum, t.partnum FROM SALES.MYVIEW1 v, SALES.
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 WHERE CURRENT OF {cursor-name | ext-cursor-name} Java | WHERE CURRENT OF iterator-name 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.
DELETE Statement SQL/MX Statements Pub/Sub SET ON ROLLBACK set-roll-clause [,set-roll-clause]... causes one or more columns to be updated when the execution of the DELETE 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.
Considerations for DELETE SQL/MX Statements READ COMMITTED specifies that any data used in the evaluation of the search condition must come from committed rows. 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.
Considerations for DELETE SQL/MX Statements To see what rollback mode NonStop SQL/MX is choosing, you can prepare the query, and then perform DISPLAY_OPTIONS: display_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. For information, see DISPLAY_EXPLAIN Command on page 4-13. For information about these defaults, see INSERT_VSBB on page 10-59 and UPD_SAVEPOINT_ON_ERROR on page 10-62.
MXCI Examples of DELETE SQL/MX Statements 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. Nonaudited tables follow a different locking and error handling model than audited tables.
C Examples of DELETE SQL/MX Statements --- 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.00 for items that have part numbers in the range 6400 to 6700: DELETE FROM invent.partsupp WHERE partnum BETWEEN 6400 AND 6700 AND partcost > 300.
COBOL Examples of DELETE SQL/MX Statements 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.EMPLOYEE WHERE CURRENT OF emp_cursor; COBOL Examples of DELETE • Remove the row for JOHN WALKER from the EMPLOYEE table: EXEC SQL DELETE FROM PERSNL.EMPLOYEE WHERE FIRST_NAME = 'JOHN' AND LAST_NAME = 'WALKER' SERIALIZABLE ACCESS END-EXEC.
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-2. DROP CATALOG is an SQL/MX extension. DROP CATALOG catalog Syntax Description of DROP CATALOG catalog is the name of the empty catalog. You must drop all schemas from the catalog before you can use the DROP CATALOG statement.
DROP INDEX Statement SQL/MX Statements DROP INDEX Statement Considerations for DROP INDEX Examples of DROP INDEX The DROP INDEX statement deletes an SQL/MX index. See Database Object Names on page 6-12. DROP INDEX is an SQL/MX extension. DROP INDEX index [RESTRICT | CASCADE] Syntax Description of DROP INDEX index is the ANSI logical name of the index to drop, of the form: [[catalog-name.]schema-name.]index where each part of the name is a valid SQL identifier with a maximum of 128 characters.
Examples of DROP INDEX SQL/MX Statements Examples of DROP INDEX • This example drops an index: DROP INDEX myindex; HP NonStop SQL/MX Reference Manual—523725-004 2 -121
DROP PROCEDURE Statement SQL/MX Statements 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.]procedure-name procedure-ref specifies an ANSI logical name of the form: [[catalog-name.]schema-name.
Example of DROP PROCEDURE SQL/MX Statements Example of DROP PROCEDURE • Drop an SPJ named ADJUSTSALARY from NonStop SQL/MX: DROP PROCEDURE samdbcat.persnl.
DROP SCHEMA Statement SQL/MX Statements 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-104. DROP SCHEMA schema [CASCADE | [RESTRICT] Syntax Description of DROP SCHEMA schema is the name of the schema to drop. If you specify RESTRICT, an error is reported if the specified schema is not empty. If you specify CASCADE, objects in the specified schema in addition to the schema itself are dropped.
Considerations for DROP SCHEMA SQL/MX Statements In the Guardian environment, update through the SCF facility: SCF 1-> info $,detail STORAGE - Detailed Information Magnetic DISK \.$ Common Disk Configuration Information: *BackupCpu............................. 3 *HighPin............................... ON *PrimaryCpu............................ 2 *Program...............................$SYSTEM.SYSTEM.TSYSDP2 *StartState............................
Examples of DROP SCHEMA SQL/MX Statements Examples of DROP SCHEMA • This example drops an empty schema: DROP SCHEMA sales RESTRICT; HP NonStop SQL/MX Reference Manual—523725-004 2 -126
DROP SQL Statement SQL/MX Statements DROP SQL Statement Considerations for DROP SQL Examples of DROP SQL The DROP SQL statement puts NonStop SQL/MX in an uninitialized state. It drops a system catalog that has no user-created catalogs. DROP SQL is an SQL/MX extension. DROP SQL Considerations for DROP SQL After you run the DROP SQL statement, you must run the InstallSqlmx script again to re-enable the use of SQL on the system.
DROP SQLMP ALIAS Statement SQL/MX Statements DROP SQLMP ALIAS Statement Considerations for DROP SQLMP ALIAS Examples of DROP SQLMP ALIAS The DROP SQLMP ALIAS statement is used to drop mappings from ANSI names to physical names of SQL/MP tables or views. DROP SQLMP ALIAS is an SQL/MX extension. DROP SQLMP ALIAS catalog.schema.object catalog.schema.object is the alias name of an SQL/MP table or view.
Examples of DROP SQLMP ALIAS SQL/MX Statements Examples of DROP SQLMP ALIAS • Suppose that you have created an SQL/MP table by using this SQL/MP CREATE TABLE statement: CREATE TABLE $myvol.mysubvol.mytable ( num NUMERIC (4) UNSIGNED NOT NULL ,name VARCHAR (20) ,PRIMARY KEY (num) ); This statement creates a mapping in the system metadata table: CREATE SQLMP ALIAS mycatalog.myschema.mytable $myvol.mysubvol.mytable; This statement drops the mapping in the system metadata table: DROP SQLMP ALIAS mycatalog.
DROP TABLE Statement SQL/MX Statements DROP TABLE Statement Considerations for DROP TABLE Examples of DROP TABLE The DROP TABLE statement deletes an SQL/MX table and any indexes, constraints, and inactive locks on the table. See Database Object Names on page 6-12. DROP TABLE table [RESTRICT | CASCADE] Syntax Description of DROP TABLE table is the name of the table to delete. If the table has an active DDL lock, neither the table nor any of its dependent objects are dropped.
Examples of DROP TABLE SQL/MX Statements in an RDF backup database, full Guardian file names are preserved and can be used to create identical file names. Grant and revoke privileges are not saved as part of DDL text. However, the DDL text includes DELETE statements to remove the default security information from the metadata tables TBL_PRIVILEGES and COL_PRIVILEGES and INSERT statements to record the correct security information.
DROP TRIGGER Statement SQL/MX Statements DROP TRIGGER Statement Considerations for DROP TRIGGER Examples of DROP TRIGGER The DROP TRIGGER statement is used to drop a trigger on an SQL/MX table. DROP TRIGGER trigger-name; Syntax Description of DROP TRIGGER trigger-name specifies the ANSI logical name of the trigger to be dropped, of the form: [[catalog-name.]schema-name.]trigger-name where each part of the name is a valid SQL identifier with a maximum of 128 characters.
DROP VIEW Statement SQL/MX Statements DROP VIEW Statement Considerations for DROP VIEW Examples of DROP VIEW The DROP VIEW statement deletes an SQL/MX view. See Views on page 6-111. DROP VIEW view [CASCADE | RESTRICT] Syntax Description of DROP VIEW view is the name of the view to drop. If you specify RESTRICT, you cannot drop the specified view if it is referenced in the query expression of any other view or in the search condition of another object's constraint.
EXECUTE Statement SQL/MX Statements EXECUTE Statement Considerations for EXECUTE MXCI Examples of EXECUTE C Examples of EXECUTE COBOL Examples of EXECUTE The EXECUTE statement executes an SQL statement previously compiled by a PREPARE statement. You can use EXECUTE in an MXCI session or in an embedded SQL program. C/COBOL MXCI C/COBOL Input data can be supplied either by using host variables or through an SQL descriptor area in an embedded SQL program.
EXECUTE Statement SQL/MX Statements The module that contains EXECUTE must also contain a PREPARE statement for statement-name. MXCI USING param-value [,param-value]... specifies values for the unnamed parameters in the prepared statement. The data type of a parameter value must be compatible with the data type of the associated parameter.
EXECUTE Statement SQL/MX Statements When EXECUTE with INTO executes, NonStop SQL/MX stores information into the host variables (and optionally their indicator variables) that correspond to columns specified in the select list for the prepared statement. :variable-name [[INDICATOR] :indicator-name] is a variable specification—a host variable with optionally an indicator variable. A variable name begins with a colon (:). The data type of an indicator variable is exact numeric with a scale of 0.
Considerations for EXECUTE SQL/MX Statements Considerations for EXECUTE Scope of EXECUTE A statement must be compiled by PREPARE before you EXECUTE it, but after it is compiled, you can execute the statement multiple times without recompiling it. MXCI C/COBOL The statement must have been compiled during the same MXCI session as its execution. The statement must have been prepared during the same compilation unit as its execution.
C Examples of EXECUTE SQL/MX Statements • Use EXECUTE USING for one parameter value, which is unnamed in the prepared statement: PREPARE FINDEMP FROM SELECT * FROM persnl.employee WHERE salary > ?SALARY AND jobcode = ?; SET PARAM ?SALARY 40000.00; EXECUTE FINDEMP USING 450; SET PARAM ?SALARY 20000.00; EXECUTE FINDEMP USING 300; C Examples of EXECUTE • Prepare and execute an UPDATE statement with dynamic input parameters: ... strcpy(stmt_buffer,"UPDATE SALES.
COBOL Examples of EXECUTE SQL/MX Statements • This example uses extended statement names: ... strcpy(stmt,"ins_cust1"); EXEC SQL PREPARE :stmt FROM :stmt_buffer; EXEC SQL EXECUTE :stmt; ... strcpy(stmt,"ins_cust2"); EXEC SQL PREPARE :stmt FROM :stmt_buffer; EXEC SQL EXECUTE :stmt; COBOL Examples of EXECUTE • Prepare and execute an UPDATE statement with dynamic input parameters: ... MOVE "UPDATE SALES.CUSTOMER SET CREDIT = ? & " WHERE CUSTNUM = CAST(? AS NUMERIC(4) UNSIGNED)" TO stmt-buffer. ...
COBOL Examples of EXECUTE SQL/MX Statements END-EXEC. ... EXEC SQL EXECUTE USING SQL DESCRIPTOR 'in_args' INTO SQL DESCRIPTOR 'out_cols' END-EXEC. ... • This example uses extended statement names: ... MOVE EXEC EXEC ... MOVE EXEC EXEC "ins_cust1" TO stmt. SQL PREPARE :stmt FROM :stmt-buffer END-EXEC. SQL EXECUTE :stmt END-EXEC. "ins_cust2" TO stmt. SQL PREPARE :stmt FROM :stmt-buffer END-EXEC. SQL EXECUTE :stmt END-EXEC.
GRANT Statement SQL/MX Statements GRANT Statement Considerations for GRANT Examples of GRANT The GRANT statement grants access privileges for an SQL/MX table, view, or stored procedure to specified users. See also GRANT EXECUTE Statement on page 2-145 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-145. 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).
Examples of GRANT SQL/MX Statements • In this example, the super ID grants SELECT and DELETE privileges on a table on behalf of sql.user1: GRANT SELECT, DELETE ON TABLE sales.odetail TO "sql.user3" BY "sql.
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-39. For the description of query-expr, see SELECT Statement on page 2-178. Embed rowset-value-const There must be at least one rowset expression in the rowset value constructor. See the SQL/MX Programming Manual for C and COBOL for a discussion of semantics when rowsets of different length or rowsets and scalars are used in a rowset value constructor.
Considerations for INSERT SQL/MX Statements ASC | DESC specifies the sort order. The default is ASC. For ordering the source table on a column that can contain null, nulls are considered equal to one another but greater than nonnulls. DEFAULT VALUES specifies a query expression of the form VALUES (DEFAULT, ... ). The value of each DEFAULT is the default value defined in the column descriptor of colname, which is contained in the table descriptor of table.
Considerations for INSERT SQL/MX Statements If the default INSERT_VSBB is set to USER, NonStop SQL/MX does not use statement atomicity. Unless you are inserting only a few records, you should not disable INSERT_VSBB to use statement atomicity, because performance is affected. Perform UPDATE STATISTICS on the tables so that row estimates are correct.
Considerations for INSERT SQL/MX Statements Embed It is important to note that the SET TRANSACTION statement might cause a dynamic recompilation of the DML statements within the next transaction. Dynamic recompilation occurs if NonStop SQL/MX detects a change in the transaction mode at run time compared with the transaction mode at the time of static SQL compilation.
Considerations for INSERT SQL/MX Statements Using Compatible Data Types To insert a row, you must provide a value for each column in the table that has no default value. The data types of the values in each row to be inserted must be compatible with the data types of the corresponding target columns. Inserting Character Values Any character string data type is compatible with all other character string data types that have the same character set.
MXCI Examples of INSERT SQL/MX Statements To avoid problems, do not run DDL or utility operations concurrently with DML operations on nonaudited tables. When you try to delete data in a nonaudited table with an index, NonStop SQL/MX returns an error. 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.
MXCI Examples of INSERT SQL/MX Statements • Insert multiple rows into the JOB table by using only one INSERT statement: INSERT INTO persnl.job VALUES (100,'MANAGER'), (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.
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-9. 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 Command SQL/MX Statements REGISTER CATALOG Command The REGISTER CATALOG command 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-173 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-11. ROLLBACK [WORK] WORK is an optional keyword that has no effect.
C Examples of ROLLBACK WORK SQL/MX Statements WHERE partnum = 4130 AND loc_code = 'K43'; 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. ...
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 all the columns 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 intermediate result table is the cross-product of result tables derived from the individual table references.
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-110. 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-200. 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. For information, see the run-time limits on streams in the SQL/MX Queuing and Publish/Subscribe Services. • • Pub/Sub You cannot use streams with nonaudited tables. Stream access within compound statements is not supported. Joining the Results of an Embedded Delete or Update SQL/MX Release 2.x enables you to join another table with the results of an embedded delete or embedded update.
Considerations for Select List SQL/MX Statements permitted on different columns.
Considerations for GROUP BY SQL/MX Statements The RANDOM function cannot be part of the SEQUENCE BY clause of a sampling method. Considerations for GROUP BY • • • • If you include a GROUP BY clause, the columns you refer to in the select-list must be either grouping columns or arguments of an aggregate (or set) function. For example, if AGE is not a grouping column, you can refer to AGE only as the argument of a function, such as AVG (AGE).
Considerations for UNION SQL/MX Statements Considerations for UNION Suppose that the contributing SELECT statements are named SELECT1 and SELECT2, the contributing tables resulting from the SELECT statements are named TABLE1 and TABLE2, and the table resulting from the UNION operation is named RESULT.
Considerations for UNION SQL/MX Statements You can specify an ORDER BY clause only as the last clause following the final SELECT statement (SELECT2 in this example). The ORDER BY clause in RESULT specifies the ordinal position of the sort column either by using an integer or by using the column name from the select list of SELECT1.
Considerations for UNION SQL/MX Statements you specified for the second operand, NonStop SQL/MX issues a warning. For example: 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' FOR READ UNCOMMITTED ACCESS ORDER BY 1 ASCENDING; This statement will receive a warning: *** WARNING[3192] Union operands sdcommon common and sdmain main have different transaction access/lock modes.
MXCI Examples of SELECT SQL/MX Statements where main.iss_eligible='Y' ORDER BY 1 ascending for browse access; For more information 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 JOBDESC -----------SALESREP SALESREP ... ENGINEER ENGINEER ... SECRETARY SECRETARY ... FIRST_NAME -----------TIM HERBERT LAST_NAME --------------WALKER KARAJAN SALARY ----------32000.00 29000.00 MARK MARIA FOLEY JOSEF 33000.00 18000.10 BILL DINAH WINN CLARK 32000.00 37000.00 --- 27 row(s) selected. This type of condition is sometimes referred to as a join predicate.
MXCI Examples of SELECT SQL/MX Statements 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. Process the select list, leaving only four columns. JOBDESC FIRST_NAME LAST_NAME SALARY SALESREP TIM WALKER 32000 ...
MXCI Examples of SELECT SQL/MX Statements 900 ... 300 420 ... 2000 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. • Select from two tables that have been joined by using an INNER JOIN on matching part numbers: SELECT OD.*, P.* FROM sales.odetail OD INNER JOIN sales.parts P ON OD.
MXCI Examples of SELECT SQL/MX Statements 100 200 250 300 400 420 450 500 600 900 100 300 400 500 600 900 MANAGER PRODUCTION SUPV ASSEMBLER SALESREP SYSTEM ANALYST ENGINEER PROGRAMMER ACCOUNTANT ADMINISTRATOR SECRETARY CORP MANAGER CORP SALESREP CORP SYSTEM ANALYS CORP ACCOUNTANT CORP ADMINISTRATOR CORP SECRETARY --- 16 row(s) selected. • Present two ways to select the same data submitted by customers from California. The first way: SELECT OD.ordernum, SUM (qty_ordered * price) FROM sales.
C Examples of SELECT SQL/MX Statements 300380 --- 3 row(s) selected. 28560.00 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. Note the subquery as part of the expression in the select list: SELECT empnum, first_name, last_name, salary, CAST(salary * 100 / (SELECT SUM(salary) FROM persnl.employee) AS NUMERIC(4,2)) FROM persnl.
COBOL Examples of SELECT SQL/MX Statements 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. EXEC SQL END DECLARE SECTION END-EXEC. ...
Publish/Subscribe Examples of SELECT SQL/MX Statements • These examples show join operations with a base table and a stream: SELECT * FROM tab1, (SELECT * FROM STREAM(tab2)) AS tab2 WHERE tab1.a = tab2.a; SELECT * FROM STREAM(tab1), tab2 WHERE tab1.a = tab2.a; The two preceding queries yield identical results.
SET Statement SQL/MX Statements SET Statement Considerations for SET statement The SET statement is used with BEFORE triggers to assign values to variables representing columns in the SQL/MX table to be modified by the triggering action. SET correlation-name.column-name = value-expression; correlation-name is the name of the new row that correlates to the row to be modified. column-name is the name of the new column that correlates to the column to be modified.
SET CATALOG Statement SQL/MX Statements SET CATALOG Statement Considerations for SET CATALOG MXCI Examples of SET CATALOG C Example of SET CATALOG COBOL Example of SET CATALOG The SET CATALOG statement sets the default logical catalog for unqualified schema names for the current SQL session. Embed The SET CATALOG statement sets the default catalog for unqualified schema names in all dynamic statements within the control flow scope of an embedded SQL program for the current SQL session.
MXCI Examples of SET CATALOG SQL/MX Statements MXCI Examples of SET CATALOG • Set the default catalog name: SET CATALOG mycatalog; 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 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.
SQL/MX Statements Considerations for SET TABLE TIMEOUT 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.
MXCI Examples of SET TABLE TIMEOUT SQL/MX Statements MXCI Examples of SET TABLE TIMEOUT • Set the lock timeout value for all the tables to 30 seconds for the current session: SET TABLE * TIMEOUT 3000; • Set the lock timeout value for the CUSTOMER table to one minute: SET TABLE customer TIMEOUT '6000'; SELECT custnum, custname FROM customer; • Reset the timeout value for the CUSTOMER table to 30 seconds (set earlier for all tables): SET TABLE customer TIMEOUT RESET; • This statement has no effect;
C Examples of SET TABLE TIMEOUT SQL/MX Statements • This SET TABLE statement has no effect; the PARTS table still uses the lock timeout value of 30 seconds (set earlier for all tables): EXEC SQL SET TABLE PARTS TIMEOUT RESET; • Reset all the lock timeout settings.
SET TRANSACTION Statement SQL/MX Statements 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). The attributes are the isolation level, access mode, size of the diagnostics area, and whether to automatically commit changes made to the database.
SET TRANSACTION Statement SQL/MX Statements same data. The default isolation level of a transaction is determined according to the rules specified in Isolation Level on page 10-44. access-mode specifies the type of data access that the transaction requires, depending on whether changes are made to the database by the transaction. If the isolation-level is READ UNCOMMITTED, you cannot specify READ WRITE. The default access-mode is READ ONLY, and you can specify only READ ONLY explicitly.
Considerations for SET TRANSACTION SQL/MX Statements Considerations for SET TRANSACTION Implicit Transactions Most DML statements are transaction-initiating—the system automatically initiates a transaction when the statement begins executing.
MXCI Examples of SET TRANSACTION SQL/MX Statements MXCI Examples of SET TRANSACTION • Set the isolation level of a transaction that performs deletes, inserts, and updates: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; --- SQL operation complete. BEGIN WORK; --- SQL operation complete. DELETE FROM persnl.employee WHERE empnum = 23; --- 1 row(s) deleted. INSERT INTO persnl.employee (empnum, first_name, last_name, deptnum, salary) VALUES (50, 'JERRY','HOWARD', 1000, 137000.00); --- 1 row(s) inserted.
SIGNAL SQLSTATE Statement SQL/MX Statements SIGNAL SQLSTATE Statement The SIGNAL statement is used with triggers. It allows a trigger execution to raise an exception that causes both the triggered and triggering statements to fail. The SIGNAL statement sends an SQLSTATE and error text. SIGNAL SQLSTATE quoted_sqlstate (quoted_string_expr); quoted_sqlstate is the five-digit SQLSTATE to be passed to SIGNAL. quoted_string_expr is a string expression.
TABLE Statement SQL/MX Statements TABLE Statement Considerations for TABLE Examples of TABLE The TABLE statement is equivalent to the query specification SELECT * FROM table. TABLE table table names the user table or view. Considerations for TABLE Relationship to SELECT Statement The result of the TABLE statement is one form of a simple-table, which is part of the definition of a table reference within a SELECT statement. See SELECT Statement on page 2-178.
UNLOCK TABLE Statement SQL/MX Statements UNLOCK TABLE Statement Considerations for UNLOCK TABLE Examples of UNLOCK TABLE The UNLOCK TABLE statement releases locks owned by MXCI on a nonaudited SQL/MP table or on underlying nonaudited SQL/MP tables of a view. UNLOCK TABLE does not affect audited tables. Ending a transaction unlocks an audited table. UNLOCK TABLE is an SQL/MX extension. UNLOCK TABLE table table is the name of the table or view to unlock. See Database Object Names on page 6-12.
UNREGISTER CATALOG Command SQL/MX Statements UNREGISTER CATALOG Command The UNREGISTER CATALOG command 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 Java WHERE CURRENT OF {cursor-name | ext-cursor-name} | WHERE CURRENT OF iterator-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 set-clause associates a value with a specific column in the table being updated. For each set-clause, the value of the specified target column-name is replaced by the 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.
UPDATE Statement SQL/MX Statements search-condition array are updated using the second element in the set-clause array, and so on. For information on using host variables and rowsets, see the SQL/MX Programming Manual for C and COBOL. 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.
UPDATE Statement SQL/MX Statements rowset-expression is an array of SQL value expressions that specifies values for the column. A rowset-expression can appear in the SET ON ROLLBACK clause only when a rowset-search-condition is present in the WHERE clause. The rows returned by the nth element in the rowset-search-condition are updated by using the nth element in the rowset-expression. The rules described above for expression apply to each array element in the rowsetexpression.
Considerations for UPDATE SQL/MX Statements SERIALIZABLE | REPEATABLE READ specifies that the UPDATE 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 UPDATE statement.
Considerations for UPDATE SQL/MX Statements Command on page 4-13. For information about these defaults, see INSERT_VSBB on page 10-59 and UPD_SAVEPOINT_ON_ERROR on page 10-62. Authorization Requirements UPDATE requires authority to read and write to the table or view being updated and authority to read any table or view specified in subqueries used in the search condition. A column of a view can be updated if its underlying column in the base table can be updated.
Considerations for UPDATE SQL/MX Statements specifying access options for individual DML statements instead of using SET TRANSACTION. Conflicting Updates in Concurrent Applications If you are using the READ COMMITTED isolation level within a transaction, your application can read different committed values for the same data at different times. Further, two concurrent applications can update (possibly in error) the same column in the same row.
Considerations for UPDATE SQL/MX Statements For example, suppose that the index of MYTABLE consists of columns A and B, and the UPDATE statement is specified: UPDATE MYTABLE SET B = 20 WHERE A > 10; If the contents of columns A and B are 11 and 12 respectively before the UPDATE, after the UPDATE NonStop SQL/MX will encounter the same row indexed by the values 11 and 20.
Considerations for UPDATE SQL/MX Statements • Pub/Sub If an UPDATE operation is applied to a set of rows and an error is generated while executing the UPDATE operation, and the transaction is rolled back, the actions of the SET ON ROLLBACK clause apply only to the rows that were processed by the UPDATE operation before the error was generated. SET ON ROLLBACK Restrictions The table must be audited. The columns used in the SET ON ROLLBACK clause: • • • • Must be declared as NOT NULL.
MXCI Examples of UPDATE SQL/MX Statements Although NonStop SQL/MX cannot successfully update all rows and return the requested results, it does not return an error. Instead, only one row is updated, and the results for this single updated row are returned in the set of host variables.
C Examples of UPDATE SQL/MX Statements The subquery is evaluated for each row of the DEPT table and returns department numbers for departments located in Chicago. • Suppose that you want to change the employee number of a manager of a department. Because EMPNUM is a primary key of the EMPLOYEE table, you must delete the employee's record and insert a record with the new number. You must also update the DEPT table to change the MANAGER column to the employee's new number.
COBOL Examples of UPDATE SQL/MX Statements while (strcmp(SQLSTATE, SQLSTATE_OK) == 0) { ... /* retrieve and test values in descriptor area */ EXEC SQL UPDATE CUSTOMER SET CREDIT = :new_default WHERE CURRENT OF cursor1; EXEC SQL FETCH cursor1 INTO SQL DESCRIPTOR 'out_sqlda'; } ... COBOL Examples of UPDATE • Reset the credit rating to the default value for all the customers in the CUSTOMER table: EXEC SQL UPDATE CUSTOMER SET CREDIT = DEFAULT END-EXEC.
Publish/Subscribe Examples of UPDATE SQL/MX Statements SET b = b + 1 SET ON ROLLBACK a = a + 1 WHERE b < 10; • This example shows the SKIP CONFLICT access: UPDATE tab1 SET a = a + 1 FOR SKIP CONFLICT ACCESS; HP NonStop SQL/MX Reference Manual—523725-004 2 -244
UPDATE STATISTICS Statement SQL/MX Statements UPDATE STATISTICS Statement Considerations for UPDATE STATISTICS Examples of UPDATE STATISTICS The UPDATE STATISTICS statement updates the histogram statistics for one or more groups of columns within a table. These statistics are used to devise optimized access plans. In addition to histogram statistics, UPDATE STATISTICS generates physical statistics (index level, nonempty block count, and EOF) for partitions of SQL/MX tables.
UPDATE STATISTICS Statement SQL/MX Statements CLEAR deletes some or all histograms for the table table. Use this option when new applications no longer use certain histogram statistics. If you do not specify column-group-list, all histograms for table are deleted. If you specify column-group-list, only columns in the group list are deleted.
UPDATE STATISTICS Statement SQL/MX Statements For more information about specifying columns, see Generating and Clearing Statistics for Columns on page 2-250. EVERY COLUMN The EVERY COLUMN keyword indicates that histogram statistics are to be generated for each individual column of table and any multicolumns that make up the primary key and indexes. For example, table has columns A, B, C, D defined, where A, B, C compose the primary key.
UPDATE STATISTICS Statement SQL/MX Statements If you specify the SAMPLE clause without additional options, a row sample is used to read 2 percent of the rows in the table, with a maximum of 2 million rows. If you specify the ROWCOUNT option, NonStop SQL/MX reads 2 percent of c, with a maximum of 2 million rows. If you do not specify the SAMPLE clause, table has fewer rows than specified, or the sample size is greater than the system limit. NonStop SQL/MX reads all rows from table.
Considerations for UPDATE STATISTICS SQL/MX Statements See SAMPLE Clause on page 7-8. Considerations for UPDATE STATISTICS Physical Statistics Physical statistics (index level, nonempty block count, and EOF) are generated for UPDATE STATISTICS statements unless you use the CLEAR option. Using Statistics Use UPDATE STATISTICS to collect and save statistics on columns. The SQL compiler uses histogram statistics to determine the selectivity of predicates, indexes, and tables.
Considerations for UPDATE STATISTICS SQL/MX Statements periods, and timeout errors do not occur. If the lock is held for a longer time, multiple retry attempts help to complete concurrent operations with minimum timeout interruption. Generating and Clearing Statistics for Columns To generate statistics for particular columns, name each column, or name the first and last columns of a sequence of columns in the table. For example, suppose that a table has consecutive columns CITY, STATE, ZIP.
Considerations for UPDATE STATISTICS SQL/MX Statements Sample Option When you use the SAMPLE option, the UPDATE STATISTICS statement estimates the unique entry counts for each column for each histogram interval. The estimated unique entry counts tend to be more accurate for those columns that have fewer unique entries than the sampled number of rows.
Examples of UPDATE STATISTICS SQL/MX Statements Managing SQL/MP Histograms Before you drop an SQL/MP table you should perform UPDATE STATISTICS with the CLEAR option. Otherwise, orphan histograms for that table are left on the system. However, if you drop an SQL/MP table before performing this step, use UPDATE STATISTICS with the CLEAR option to remove orphan tables: 1. Create a dummy table in the catalog where the primary partition of the table you dropped resided: CREATE TABLE trash (a int); 2.
Examples of UPDATE STATISTICS SQL/MX Statements • Suppose that a construction company has an ADDRESS table of potential sites and a DEMOLITION_SITES table that contains some of the columns of the ADDRESS table. The primary key is ZIP. Join these two tables on two of the columns in common: SELECT COUNT(AD.number), AD.street, AD.city, AD.zip, AD.state FROM address AD, demolition_sites DS WHERE AD.zip = DS.zip AND AD.type = DS.type GROUP BY AD.street, AD.city, AD.zip, AD.
VALUES Statement SQL/MX Statements VALUES Statement Considerations for VALUES Examples of VALUES The VALUES statement starts with the VALUES keyword followed by a sequence of row value constructors, each of which is enclosed in parentheses. It displays the results of the evaluation of the expressions and the results of row subqueries within the row value constructors. VALUES (row-value-constructor) [,(row-value-constructor)]...
Examples of VALUES SQL/MX Statements • This VALUES statement displays the results of the expressions and the row subquery in the lists: VALUES ('a','b',UPSHIFT('c')), ((SELECT jobdesc FROM job WHERE jobcode=300),'d',NULL); (EXPR) -----------------a SALESREP (EXPR) -----b d (EXPR) -----C ? --- 2 row(s) selected.
Examples of VALUES SQL/MX Statements HP NonStop SQL/MX Reference Manual—523725-004 2 -256
3 Embedded-Only SQL/MX Statements This section describes the syntax and semantics of NonStop SQL/MX statements that you can embed only in programs written in C, C++, COBOL, or Java. In NonStop SQL/MX Release 2.x, mixing embedded SQL calls to NonStop SQL/MP and NonStop SQL/MX from the same application process is not supported. You cannot run these statements, or specific forms of these statements, in MXCI: C/COBOL ALLOCATE CURSOR Statement on page 3-3 Allocates an SQL cursor.
Embedded-Only SQL/MX Statements DECLARE SCHEMA Declaration on page 3-32 Sets default schema for unqualified object names in static SQL statements within a compilation unit. DESCRIBE Statement on page 3-33 Uses an SQLDA to return descriptions of output variables (usually SELECT columns) and input parameters for a prepared statement. END DECLARE SECTION Declaration on page 3-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-32. DECLARE CATALOG is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DECLARE CURSOR Declaration DECLARE CURSOR Declaration Considerations for DECLARE CURSOR C Examples of DECLARE CURSOR COBOL Examples of DECLARE CURSOR Publish/Subscribe Examples of DECLARE CURSOR C/COBOL The DECLARE CURSOR declaration or statement specifies a cursor in a host program. It associates the name of the cursor with a query expression that specifies the rows to be retrieved.
Embedded-Only SQL/MX Statements DECLARE CURSOR Declaration See SELECT Statement on page 2-178 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-54. Pub/Sub WITH HOLD | WITHOUT HOLD specifies whether (WITH) or not (WITHOUT) an application keeps cursors open across transaction boundaries.
Embedded-Only SQL/MX Statements Considerations for DECLARE CURSOR GLOBAL | LOCAL specifies the scope of the value specification for an ext-cursor-name. The default is LOCAL. The scope of a GLOBAL cursor is the SQL session. The scope of a LOCAL cursor is the module or compilation unit in which DECLARE CURSOR appears. ext-statement-name is a value specification—a character literal or host variable with character data type.
Embedded-Only SQL/MX Statements • • C Examples of DECLARE CURSOR If the READONLY_CURSOR attribute is set to TRUE (the default setting), you must declare cursors with the FOR UPDATE clause for the named columns or all columns to be updatable. (This READONLY_CURSOR setting improves cursor performance.
Embedded-Only SQL/MX Statements • COBOL Examples of DECLARE CURSOR This SQL statement defines a dynamic updatable cursor: EXEC SQL BEGIN DECLARE SECTION; char query[50]; ... EXEC SQL END DECLARE SECTION; ... strcpy(query,"SELECT COL1, COL2, COL3, COL4" " FROM SALES.PARTS"); ... EXEC SQL PREPARE curspec FROM :query; ...
Embedded-Only SQL/MX Statements Publish/Subscribe Examples of DECLARE CURSOR Publish/Subscribe Examples of DECLARE CURSOR Suppose that these SQL/MP tables and index (and the metadata mappings) have been created: CREATE TABLE $db.dbtab.tab1 (a int, b int, c int); CREATE TABLE $db.dbtab.tab2 (a int, b int, c int); CREATE INDEX $db.dbtab.itab1 ON tab1(b, c); CREATE SQLMP ALIAS cat.sch.tab1 $db.dbtab.tab1; CREATE SQLMP ALIAS cat.sch.tab2 $db.dbtab.
Embedded-Only SQL/MX Statements DECLARE MPLOC Declaration DECLARE MPLOC Declaration Considerations for DECLARE MPLOC C Examples of DECLARE MPLOC COBOL Examples of DECLARE MPLOC The DECLARE MPLOC declaration is a compiler directive that sets the default volume and subvolume for unqualified Guardian physical object names in static SQL statements that follow the declaration within a compilation unit. C/COBOL DECLARE MPLOC is used by the preprocessor when the INVOKE directive is not fully qualified.
Considerations for DECLARE MPLOC Embedded-Only SQL/MX Statements Considerations for DECLARE MPLOC C/COBOL Preprocessor and INVOKE Directive The way you specify DECLARE MPLOC affects whether the preprocessor preserves or overrides the INVOKE directive: DECLARE MPLOC is specified as... INVOKE Directive Preprocessor Action \node.$vol.subvol.filename table is not fully qualified and does not contain \node. Overrides the INVOKE directive with DECLARE MPLOC names. \node.$vol.subvol.
Embedded-Only SQL/MX Statements COBOL Examples of DECLARE MPLOC COBOL Examples of DECLARE MPLOC • Set the default volume and subvolume: EXEC SQL DECLARE MPLOC '$MYVOL.MYSUBVOL' END-EXEC.
Embedded-Only SQL/MX Statements DECLARE NAMETYPE Declaration DECLARE NAMETYPE Declaration The DECLARE NAMETYPE declaration is a compiler directive that sets the default NAMETYPE attribute value to ANSI or NSK for static SQL statements that follow the declaration within a compilation unit. C/COBOL DECLARE NAMETYPE is used by the preprocessor when the INVOKE directive is not fully qualified. DECLARE NAMETYPE is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DECLARE SCHEMA Declaration DECLARE SCHEMA Declaration The DECLARE SCHEMA declaration is a compiler directive that sets the default schema (and optionally, the catalog) for unqualified object names in static SQL statements that follow the declaration within a compilation unit. The DECLARE CATALOG declaration also sets the default catalog. See DECLARE CATALOG Declaration on page 3-21. DECLARE SCHEMA is an SQL/MX extension that you use only in embedded SQL programs.
Embedded-Only SQL/MX Statements DESCRIBE Statement DESCRIBE Statement C Examples of DESCRIBE COBOL Examples of DESCRIBE C/COBOL The DESCRIBE statement obtains information, including data types of columns, about dynamic input and output parameters contained in a prepared statement. A parameter is a placeholder for a value to be supplied when the statement executes.
Embedded-Only SQL/MX Statements C Examples of DESCRIBE GLOBAL | LOCAL specifies the scope of the prepared statement. The default is LOCAL. A GLOBAL prepared statement can be described and executed within the SQL session. A LOCAL prepared statement can be described and executed only within the module or compilation unit in which it was prepared.
Embedded-Only SQL/MX Statements • COBOL Examples of DESCRIBE Prepare a statement, allocate input and output descriptor areas, and describe the input and output descriptor areas: ... strcpy(stmt_buffer,"SELECT * FROM EMPLOYEE" " WHERE EMPNUM = CAST(? AS NUMERIC(4) UNSIGNED)"); ... EXEC SQL PREPARE S1 FROM :stmt_buffer; ... desc_max = 1; EXEC SQL ALLOCATE DESCRIPTOR 'in_args' WITH MAX :desc_max; desc_max = 6; EXEC SQL ALLOCATE DESCRIPTOR 'out_cols' WITH MAX :desc_max; ...
Embedded-Only SQL/MX Statements • COBOL Examples of DESCRIBE Prepare a statement and allocate and describe the input and output descriptor areas: ... MOVE "SELECT * FROM EMPLOYEE" & " WHERE EMPNUM = CAST(? AS NUMERIC(4) UNSIGNED)" TO stmt-buffer. ... EXEC SQL PREPARE S1 FROM :stmt-buffer END-EXEC. ... MOVE 1 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'in_args' WITH MAX :desc-max END-EXEC. MOVE 6 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'out_cols' WITH MAX :desc-max END-EXEC. ...
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 or an SQLJ iterator on the next row of the result table defined by the cursor specification or the iterator and retrieves values from that row, leaving the cursor or iterator positioned at that row.
Embedded-Only SQL/MX Statements C/COBOL FETCH Statement cursor-name is an SQL identifier—the name of the cursor being used to fetch a row of values. The cursor must be open. See Identifiers on page 6-54. C/COBOL 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.
Embedded-Only SQL/MX Statements Java Considerations for FETCH INTO argument-list specifies host variables. The number of row values must be equal to the 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. :variable-name is a variable specification—a host variable.
Embedded-Only SQL/MX Statements Considerations for FETCH FETCH returns a five-character status code to SQLSTATE, whose values include: 00000 The FETCH was successful. 02000 The result table is empty or the end of the table was encountered. 22xxx Data exception condition. For more information on the ANSI SQL:1999 SQLSTATE class and subclass values, see the SQL/MX Programming Manual for C and COBOL.
Embedded-Only SQL/MX Statements C Examples of FETCH FETCH also returns an integer status code to SQLCODE as: 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-52. 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 or the SQLJ customizer. If you do not specify a MODULE directive, the preprocessor or customizer 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 Java C Examples of MODULE Directive Used by the Customizer The SQLJ customizer creates a module definition file, containing only SQL statements, as one of its output files. The customizer writes the header of the module definition file as: MODULE module-name NAMES ARE ISO88591 ; TIMESTAMP DEFINITION ( creation_timestamp ) ; The customizer gets the module-name from the MODULE directive, if one exists, at the beginning of your embedded SQLJ 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-134.
Embedded-Only SQL/MX Statements COBOL Examples of OPEN COBOL Examples of OPEN • Declare and open a cursor, using FETCH to retrieve data, then closing the cursor: EXEC SQL DECLARE cursor1 CURSOR FOR SELECT COL1, COL2, COL3 FROM PARTS WHERE COL1 >= :hostvar ORDER BY COL1 READ UNCOMMITTED ACCESS END-EXEC. ... EXEC SQL OPEN cursor1 END-EXEC. ... EXEC SQL FETCH cursor1 INTO :hostvar1, :hostvar2, :hostvar3 END-EXEC. ... EXEC SQL CLOSE cursor1 END-EXEC.
Embedded-Only SQL/MX Statements SET (Assignment) Statement SET (Assignment) Statement C Examples of Assignment Statement C/COBOL An assignment statement in a compound statement assigns a value to a host variable so that subsequent statements in the containing compound statement can reference and use the value of that host variable. SET is an SQL/MX extension that you use only in embedded SQL programs in C or COBOL.
C Examples of Assignment Statement Embedded-Only SQL/MX Statements assignment-source specifies a list of value expressions, a list of rowset expressions, the NULL specification, or a subquery. These values are to be inserted into the assignment-target. subquery | {expression | rowset-expression | NULL} [,{expression | rowset-expression | NULL}]... is a value expression, rowset expressions, NULL, or the result of a subquery. NULL can be assigned to a host variable of any type.
Embedded-Only SQL/MX Statements SET DESCRIPTOR Statement SET DESCRIPTOR Statement SQL Item Descriptor Area of SET DESCRIPTOR Considerations for SET DESCRIPTOR C Examples of SET DESCRIPTOR COBOL Examples of SET DESCRIPTOR C/COBOL The SET DESCRIPTOR statement changes specified information in an SQL descriptor area. An application program can either set the count of item descriptors with information or set the value of a specific field within a specific item.
Embedded-Only SQL/MX Statements SQL Item Descriptor Area of SET DESCRIPTOR ROWSET_SIZE = value-specification sets the length of rowsets specified in the item descriptors from value-specification, a literal with exact numeric data type or a host variable. value-specification is the common length of all rowsets described in the descriptor. VALUE item-number set-item-info [,set-item-info]... sets the value of a specific field within a specific item.
SQL Item Descriptor Area of SET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-5. SET DESCRIPTOR Descriptor Area Items (page 1 of 2) Field Data Type and Description CHARACTER_SET_NAME Character string. One-part character set name. DATETIME_CODE Exact numeric, scale 0. Codes for datetime type: 1 date; 2 time; 3 timestamp.
Considerations for SET DESCRIPTOR Embedded-Only SQL/MX Statements Table 3-5. SET DESCRIPTOR Descriptor Area Items (page 2 of 2) Field Data Type and Description SCALE Exact numeric, scale 0. Scale for exact numeric types. SCALE specifies the number of digits to the right of the decimal point. TYPE Exact numeric, scale 0.
Embedded-Only SQL/MX Statements Considerations for SET DESCRIPTOR col_num = 1; data_ind = -1; EXEC SQL SET DESCRIPTOR :upd_desc VALUE :col_num INDICATOR_DATA = :data_ind, VARIABLE_DATA = :data_pic_2; printf("SQLCODE after SET DESCRIPTOR is %d \n", SQLCODE); EXEC SQL EXECUTE P_UPD USING SQL DESCRIPTOR :upd_desc; printf("SQLCODE after EXECUTE = %ld\n", SQLCODE); DECIMAL Data Types and SET DESCRIPTOR When a host variable is defined as the DECIMAL data type in an embedded program, there are two ways to set t
Embedded-Only SQL/MX Statements Considerations for SET DESCRIPTOR " VALUES (cast(? as decimal(3,0) unsigned));"); desc_max = 1; EXEC SQL ALLOCATE DESCRIPTOR 'in_desc3' WITH MAX :desc_max; printf("SQLCODE after allocate descriptor is %d\n", SQLCODE); EXEC SQL PREPARE FROM :insert_buf; printf("SQLCODE after prepare is %d\n", SQLCODE); desc_val = 1; type_val = -301; strncpy(decimal_3_unsigned, " ", sizeof(decimal_3_unsigned)); strcpy(decimal_3_unsigned, " 999"); precision = 3; scale = 0; length = 5; EXEC SQL
Embedded-Only SQL/MX Statements C Examples of SET DESCRIPTOR VARIABLE_POINTER is not supported in COBOL. Embedded COBOL does not support the pointer type. Processing Items in a Descriptor Area You can retrieve the number of filled-in descriptor items for input parameters and set fields for a specific item. Use the number of filled-in descriptor items to construct a loop to set values for individual parameters.
Embedded-Only SQL/MX Statements COBOL Examples of SET DESCRIPTOR COBOL Examples of SET DESCRIPTOR • Allocate a descriptor area, describe the input parameters of a dynamic SQL statement, and use the descriptor area to set values for the parameters: - MOVE 1 TO desc-max. EXEC SQL ALLOCATE DESCRIPTOR 'in_sqlda' WITH MAX :desc-max END-EXEC. ... MOVE "UPDATE employee " SET salary = salary * 1.1 " WHERE jobcode = CAST(? AS NUMERIC(4) unsigned)" TO hv-sql-statement.
WHENEVER Declaration Embedded-Only SQL/MX Statements WHENEVER Declaration Considerations for WHENEVER C Examples of WHENEVER COBOL Examples of WHENEVER C/COBOL The WHENEVER declarative statement specifies an action to take when an error, warning, or no-rows-found condition occurs. The preprocessor inserts code after every embedded SQL statement to check values of SQLSTATE and jump to the appropriate routine to handle the error, warning, or no-rows-found condition.
Considerations for WHENEVER Embedded-Only SQL/MX Statements condition-action specifies the action to take: CONTINUE Continue with next statement. GOTO target Pass control to the target location. CALL C-function Execute the named C function. PERFORM COBOL-routine Execute the named COBOL routine. If you do not specify an action, NonStop SQL/MX discontinues checking for the specified condition. target is a host label identifier that specifies a target location in a C program.
Embedded-Only SQL/MX Statements C Examples of WHENEVER C Examples of WHENEVER • The effect of this statement is the same as if you had written a C statement that tests for an SQLSTATE of 02000 and executes a C continue statement: WHENEVER NOT FOUND CONTINUE; • WHENEVER sets actions for all embedded SQL statements that physically follow it in the program. In this example, if statement_2 caused an error, control continues at label x. ... EXEC SQL EXEC SQL EXEC SQL EXEC SQL EXEC SQL ... label_x: ...
Embedded-Only SQL/MX Statements COBOL Examples of WHENEVER HP NonStop SQL/MX Reference Manual—523725-004 3- 90
4 MXCI Commands This section describes the syntax and semantics of MXCI commands. MXCI commands are NonStop SQL/MX extensions that typically affect attributes of an MXCI session. You can run these commands only through MXCI, with the exceptions noted: ADD DEFINE Command on page 4-3 Creates DEFINEs for Guardian file names. ALTER DEFINE Command on page 4-5 Changes DEFINEs for Guardian file names. CD Command on page 4-7 Changes the current working directory.
MXCI Commands OBEY Command on page 4-41 Executes MXCI commands and statements from a file. This file is referred to as an OBEY command file. REPEAT Command on page 4-43 Reexecutes a command. You can also use the exclamation point (!) command. RESET PARAM Command on page 4-44 Clears the values of the specified parameter or all the parameters in the current session. SET LIST_COUNT Command on page 4-46 Sets the maximum number of rows to be displayed for the next SELECT statement.
ADD DEFINE Command MXCI Commands ADD DEFINE Command Considerations for ADD DEFINE Examples of ADD DEFINE The ADD DEFINE command creates a new DEFINE in the current MXCI session. (ADD DEFINE is similar to the TACL command ADD DEFINE and the OSS shell command add_define.) You can use defines only for SQL/MP objects. You can use ADD DEFINE only within an MXCI session. ADD DEFINE define [,CLASS MAP], FILE [\node.][[$volume.]subvol.]filename define is the name for the new DEFINE.
Considerations for ADD DEFINE MXCI Commands If the Guardian physical name includes a reserved word, consider using the CREATE SQLMP ALIAS statement, instead of the ADD DEFINE command, to create a logical name mapping. Considerations for ADD DEFINE Scope of ADD DEFINE A DEFINE stays in effect until you change or delete it or until you exit the current session. A user can delete a DEFINE within MXCI.
ALTER DEFINE Command MXCI Commands ALTER DEFINE Command Considerations for ALTER DEFINE Examples of ALTER DEFINE The ALTER DEFINE command changes a DEFINE in the current MXCI session. (ALTER DEFINE is similar to the TACL command ALTER DEFINE.) You can use ALTER DEFINE only within an MXCI session. ALTER DEFINE define [,CLASS MAP], FILE [\node.][[$volume.]subvol.]filename define is the name of the existing DEFINE to change.
Examples of ALTER DEFINE MXCI Commands Examples of ALTER DEFINE • Alter a DEFINE that assigns the logical name =ORDERS to the table whose Guardian physical name is $MYVOL.SALES.ORDERS: ALTER DEFINE =ORDERS, FILE $MYVOL.SALES.
CD Command MXCI Commands CD Command The CD command is an MXCI command that 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 [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 You can look for similar values by specifying only part of the characters of module-name combined with the “*” (asterisk) wild-card characters. If you omit the module clause, DISPLAY USE OF will search for all modules. These are all valid specifications: module 'CAT.SCH.M1' module 'CAT.sch.*' module 'CAT.*.
Examples of DISPLAY USE OF MXCI Commands Module: CAT.SCH.CURSOMEM Object: \NODE1.$DATA08.ORDERS.T071CH Object: \NODE1.$DATA08.ORDERS.T071M Object: \NODE1.$DATA08.ORDERS.T071S Object: \NODE1.$DATA08.ORDERS.T071T Object: \NODE1.$DATA08.ORDERS.T071U Module: CAT.SCH.TESTE001M Table: \NODE1.$DATA08.ORDERS.RSWORKS ... (and so on for all modules). • Display objects for all modules matching wild card “c*M”: >>display use of module 'CAT.*.c*M'; Module: CAT.SCH.constraintM Index: \NODE1.$DATA08.ORDERS.TI(CAT.SCH.
MXCI Commands Examples of DISPLAY USE OF Object: \NODE1.$DATA08.ORDERS.T11 Module: TANDEM_SYSTEM_NSK.SCH.INS1M Modules not loaded: Module: SUPER.SUPER.MXOLTP Error: -8809 Module: SUPER.SUPER.NOWAITOLTM Error: -8809 Module: SUPER.SUPER.UPDATETESTM Error: -8809 Module: SUPER.SUPER.
DISPLAY_EXPLAIN Command MXCI Commands DISPLAY_EXPLAIN Command Considerations for DISPLAY_EXPLAIN Examples of DISPLAY_EXPLAIN The DISPLAY_EXPLAIN command generates and displays the result of the EXPLAIN function, describing an access plan for a SELECT, INSERT, DELETE, UPDATE, or CALL statement. For a description of the result table of the EXPLAIN function, see EXPLAIN Function on page 9-55. You can use DISPLAY_EXPLAIN only within an MXCI session.
Examples of DISPLAY_EXPLAIN MXCI Commands Purpose of the EXPLAIN Function Result The EXPLAIN function result is an access plan. You can use the access plan to tune queries and to help determine whether to add or drop indexes for a table in a database. For more information about access plans, see the SQL/MX Query Guide. Examples of DISPLAY_EXPLAIN • Display all columns in the result of the EXPLAIN function for the specified statement: DISPLAY_EXPLAIN SELECT * FROM persnl.employee WHERE salary > 40000.
Examples of DISPLAY_EXPLAIN MXCI Commands buffer_size: 31000 record_length: 48 ? EXPL_NAME__ 211864141076058828 3 ROOT 2 ? 2.4783301E+000 9.8001182E-002 1.1864653E-001 CPU_TIME: 0.002373 IO_TIME: 0.020647 MSG_TIME: 0 IDLETIME: 0.098 PROBES: 1 select_list: indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.EMPNUM), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.FIRST_NAME), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.LAST_NAME), indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.DEPTNUM), 450, indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.
Examples of DISPLAY_EXPLAIN MXCI Commands end_key: (indexcol(\SAMDBCAT.PERSNL.EMPLOYEE.EMPNUM) = 65535) scan_type: file_scan SAMDBCAT.PERSNL.EMPLOYEE scan_direction: forward key_type: simple lock_mode: not specified access_mode: not specified columns_retrieved: 6 fast_scan: used fast_replydata_move: used This use of the DISPLAY_EXPLAIN command first prepares the statement named EXPL_NAME from the SELECT statement and then displays all the columns of the result of the EXPLAIN function applied to EXPL_NAME.
Examples of DISPLAY_EXPLAIN MXCI Commands This output shows the sequence numbers, the operators, parallel information, and the cardinality for the operators. Using the sequence numbers, you can create a query tree that visually shows the query plan. For more information about parallelism and examples of how to build, display and interpret query trees, see the SQL/MX Query Guide. The DESCRIPTION column contains information about parallelism for an operator.
DISPLAY_QC Command MXCI Commands DISPLAY_QC Command Considerations for DISPLAY_QC Examples of DISPLAY_QC The DISPLAY_QC command generates and displays selected data from the result of the QUERYCACHE function. For a description of the result table of the QUERYCACHE function, see the QUERYCACHE Function on page 9-109. 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-113. 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 is an MXCI command that displays statistics about the last DML or PREPARE statement executed within the current MXCI session. Use DISPLAY STATISTICS only within an MXCI session.
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 information about the history buffer, see HISTORY Command on page 4-31. You can use FC only within an MXCI session. FC [text | [-]number] text is the beginning text of a command in the MXCI history buffer. Case is not significant in matching the text to a command.
Examples of FC MXCI Commands Examples of FC • Reexecute the most recent command that begins with SH: >>FC SH; >>SHOW SESSION; .. Pressing Return executes the SHOW SESSION command. • Correct a statement entered incorrectly: >>SELECR * FROM MYTABLE; *** ERROR[15001] A syntax error at or before: selecr * from $boy000.persnl.employee; ^ >>FC; >>SELECR * FROM MYTABLE; .. T >>SELECT * FROM MYTABLE; .. Pressing Return executes the corrected SELECT statement.
HISTORY Command MXCI Commands HISTORY Command The HISTORY command displays recently executed MXCI commands, identifying each command by a number you can use to reexecute or edit the command with FC. See FC Command on page 4-29. You can use HISTORY only within an MXCI session. HISTORY [number] number is the number of commands to display. The default number is 10.
INFO DEFINE Command MXCI Commands INFO DEFINE Command INFO DEFINE is an MXCI command that displays the logical and physical names of DEFINEs in the current MXCI session. (INFO DEFINE is similar to the TACL command INFO DEFINE and the OSS shell command info_define.) INFO DEFINE [ALL] ALL displays information about all the DEFINEs. If you do not specify ALL, the INFO DEFINE command displays information about the current class MAP DEFINEs, which are associated with the names of tables, views, or partitions.
INVOKE Command MXCI Commands INVOKE Command Examples of INVOKE The INVOKE command generates a record description that corresponds to a row in the specified table or view. The record description includes a data item for each column in the table or view except the SYSKEY column; it includes the SYSKEY column of a view only if the view explicitly listed the column in its definition. You can use this version of INVOKE only within an MXCI session.
LOG Command MXCI Commands LOG Command Considerations for LOG Examples of LOG The LOG command starts or stops MXCI logging to a disk file. When logging is in effect, MXCI writes the commands you enter to a file (in addition to executing them) and writes the output of the commands to the file. Use LOG only within an MXCI session. LOG [log_file [COMMAND[S]] [CLEAR]] log_file is the name of a file to which MXCI writes the commands you use and the command output.
Examples of LOG MXCI Commands To ensure that log information is retained for a session, use a unique name for each log file. Examples of LOG • Start logging only commands to an OSS text file in the current directory, clearing the file first: >>LOG myfile COMMANDS CLEAR; • Stop logging: >>LOG; After you exit MXCI, you can copy the file to the Guardian environment by using the OSS cp command. For example: cp myfile /G/data06/tempjb/myfile Exit OSS.
LS Command MXCI Commands LS Command Considerations for LS Examples of LS LS is an MXCI command that 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: -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 information 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 information 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 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-76. 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 the parameters in the prepared SQL statement with the SET PARAM command prior to issuing the EXECUTE statement.
Examples of SET PARAM MXCI Commands • The PROJECT table has a SHIP_TIMESTAMP column. This UPDATE statement uses the character literal in the ?SHIP parameter to set the value: SET PARAM ?SHIP '1998-04-03 21:05:36.143'; UPDATE persnl.project SET ship_timestamp = CAST (?SHIP AS TIMESTAMP(3)); • The PROJECT table has an EST_COMPLETE column. This UPDATE statement uses the character literal in the ?EST parameter to set the value: SET PARAM ?EST 60; UPDATE persnl.
SET SHOWSHAPE Command MXCI Commands SET SHOWSHAPE Command Considerations for SET SHOWSHAPE Examples of SET SHOWSHAPE The SET SHOWSHAPE command allows you to display access plans in effect. The effect of SET SHOWSHAPE is to generate the output of the SHOWSHAPE command for multiple SQL statements. See SHOWSHAPE Command on page 4-89. You can use SET SHOWSHAPE only within an MXCI session.
Considerations for SET SHOWSHAPE MXCI Commands Considerations for SET SHOWSHAPE Default Control Query Shape For those statements that do not have a shape—for example, the CREATE SCHEMA statement—a control query shape (CQS) of the form CONTROL QUERY SHAPE ANYTHING is issued. CONTROL QUERY SHAPE ANYTHING resets the effect of any preceding CQSs. Its use is especially important when CQSs are being generated from an input file of commands and statements.
Examples of SET SHOWSHAPE MXCI Commands • To turn off the display of access plans, enter: SET SHOWSHAPE OFF; • To write results of queries, which are provided in an input file named examples, and their plans to an output file named plans, enter: SET SHOWSHAPE INFILE /G/data06/judy/examples OUTFILE plans; HP NonStop SQL/MX Reference Manual—523725-004 4- 52
SET STATISTICS Command MXCI Commands SET STATISTICS Command The SET STATISTICS command allows you to specify whether to display statistics after each SQL statement executes. SET STATISTICS {ON | OFF} ON displays statistics automatically after each statement executes. OFF turns off the automatic display of statistics. Note. The default setting when you start MXCI is STATISTICS OFF. For a description of the statistics displayed, see DISPLAY STATISTICS Command on page 4-22.
SET TERMINAL_CHARSET Command MXCI Commands SET TERMINAL_CHARSET Command The SET TERMINAL_CHARSET command is used to set the character set for messages that an interactive SQL/MX client can send to or receive from NonStop SQL/MX. Examples of such messages include commands, SQL statements or query results generated during a MXCI session. SET TERMINAL_CHARSET 'value' value is any one of the fifteen character set names enclosed in single quotes. The default value is 'ISO88591'.
SET WARNINGS Command MXCI Commands SET WARNINGS Command The SET WARNINGS command is used to turn the display of warnings on or off during an MXCI session. An MXCI session starts with the warnings on. You can use SET WARNINGS only within an MXCI session. SET WARNINGS {ON | OFF} Examples of SET WARNINGS • Suppose that T1 is a table containing one row.
SH Command MXCI Commands SH Command SH is an MXCI command that 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 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-76. 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-163.
SHOW SESSION Command MXCI Commands SHOW SESSION Command Examples of SHOW SESSION SHOW SESSION displays attributes of the current MXCI session. You can use SHOW SESSION (or ENV) only within an MXCI session. SHOW SESSION SHOW SESSION displays these attributes: CURRENT DIRECTORY Path name of the current server directory. You can use the CD command to change it. HOME DIRECTORY Default directory. LIST_COUNT Current list count. LOG FILE Current log file. MESSAGEFILE Current message file.
Examples of SHOW SESSION MXCI Commands Examples of SHOW SESSION • A SHOW SESSION command and its output: >>SHOW SESSION +>; ---------------------------------Current Environment ---------------------------------CURRENT DIRECTORY /usr/manager/bin HOME DIRECTORY /usr/manager LIST_COUNT 5 LOG FILE MESSAGEFILE /usr/manager/bin/mxcierrors.cat TERMINAL CHARSET ISO88591 MESSAGEFILE LANG US English MESSAGEFILE VRSN {2003-12-11 13:56 NSK:SQUAW/SUPER.
SHOWCONTROL Command MXCI Commands SHOWCONTROL Command Examples of SHOWCONTROL The SHOWCONTROL command displays the access plan, controls, and system defaults in effect. Use SHOWCONTROL only within an MXCI session.
Examples of SHOWCONTROL MXCI Commands MATCH FULL specifies that attribute-name must be the same as the attribute name used in a CONTROL QUERY DEFAULT statement. MATCH PARTIAL specifies that attribute-name must be included in the attribute name used in a CONTROL QUERY DEFAULT statement. The default is MATCH PARTIAL. If attribute-name is a reserved word, such as MAX, MIN, or TIME, you must capitalize attribute-name and delimit it within double quotes (").
Examples of SHOWCONTROL MXCI Commands • Display output when CONTROL TABLE has not been executed in the current session: SHOWCONTROL TABLE; No CONTROL TABLE settings are in effect. --- SQL operation complete. • Issue multiple CONTROL TABLE statements followed by a SHOWCONTROL TABLE: CONTROL TABLE PERSNL.JOB MDAM 'OFF'; --- SQL operation complete. CONTROL TABLE * TIMEOUT '3000'; --- SQL operation complete. SHOWCONTROL TABLE; CONTROL TABLE SAMDBCAT.PERSNL.
Examples of SHOWCONTROL MXCI Commands • Change the TIMEOUT attribute and then issue a SHOWCONTROL DEFAULT for TIME, which is a reserved word: CONTROL QUERY DEFAULT TIMEOUT '2000'; --- SQL operation complete. SHOWCONTROL DEFAULT "TIME", MATCH PARTIAL; CONTROL QUERY DEFAULT TIMEOUT 2000 Current DEFAULTS STREAM_TIMEOUT TIMEOUT -1 2000 --- SQL operation complete. In this example, the TIME name matches the TIMEOUT and STREAM_TIMEOUT attributes.
Examples of SHOWCONTROL MXCI Commands • Display all settings and defaults in effect: >>showcontrol all; .. No CONTROL QUERY SHAPE settings are in effect. No CONTROL SESSION settings are in effect. No CONTROL TABLE settings are in effect. No CONTROL QUERY DEFAULT settings are in effect.
Examples of SHOWCONTROL MXCI Commands MDAM_SCAN_METHOD ON MIN_MAX_OPTIMIZATION ON MP_SUBVOLUME SKMXDB MP_SYSTEM \ANUPAMA MP_VOLUME $DATA08 MSCF_ET_REMOTE_MSG_TRANSFER 0.
SHOWDDL Command MXCI Commands 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. SHOWDDL {[PROCEDURE] procedure-name }| {object-name [,SQLMP]} procedure-name is [[catalog-name.
MXCI Commands • Considerations for SHOWDDL When used on an SQL/MP table through an SQL/MP alias, SHOWDDL displays the DDL of the SQL/MP table using equivalent SQL/MX syntax. Differences Between SHOWDDL Output and Original DDL • • • • • SHOWDDL displays SQL/MX system-created indexes as user-created indexes. In the output of SHOWDDL, each system-created index is preceded by the comment '--The following index is a system-created index--'.
Considerations for SHOWDDL MXCI Commands • • • • • • • • • • • • • • The NCHAR data type is displayed as a CHAR CHARACTER SET default-char-set showing the current default national character set (either UCS2 or ISO88591.) All ANSI names in the output are fully qualified. All physical location names are fully expanded. SHOWDDL displays constraint names even though they might not have been specified during the creation of the constraint.
Considerations for SHOWDDL MXCI Commands • • • • • • • • The LOCATION clause for SQL/MP tables is not displayed because it is invalid syntax because its physical location name is not a valid SQL/MX location name. The SMF logical name is displayed instead of the physical volume name (PHYSVOL) for SQL/MP tables located on SMF volumes. SHOWDDL does not display individual ALTER TABLE ADD COLUMN statements for added columns in SQL/MP tables as they are for SQL/MX tables.
Examples of SHOWDDL MXCI Commands • • • • • • SHOWDDL displays only whether an SQL/MP table has DCOMPRESS on or off and does not distinguish between compression methods 1 and 2. DCOMPRESS is displayed only with the SQLMP option. KEYTAG is displayed as an unsigned small integer because of how it is stored. KEYTAG is entered as two bytes of char data, but SHOWDDL shows the converted values. KEYTAG is displayed only with the SQLMP option.
Examples of SHOWDDL MXCI Commands , CONSTRAINT CAT.SCH.T1_102261179_0003 CHECK (CAT.SCH.T1.N IS NOT NULL AND CAT.SCH.T1.C IS NOT NULL) NOT DROPPABLE ) LOCATION \FIGARO.$DATA1.ZSDQXXBK.B7VVVW00 NAME FIGARO_DATA1_ZSDQXXBK_B7VVVW00 ATTRIBUTES MAXEXTENTS 600 STORE BY (C DESC, N ASC) ; -- The following index is a system created index -CREATE UNIQUE INDEX T1_102261179_0004 ON CAT.SCH.T1 ( C ASC ) LOCATION \FIGARO.$DATA2.ZSDUXXBK.
Examples of SHOWDDL MXCI Commands NAME FIGARO_DATA_ZSDADM53_VZBRLI00 -- HASH PARTITION -- ( -- The following partition is offline --ADD LOCATION \FIGARO.$DATA.ZSDWWWWW.AADZ1200 -NAME FIGARO_$DATA_ZSDWWWWW_AADZ1200 -- ) STORE BY (B ASC, C DESC) ; >>showddl t1; CREATE TABLE CAT.SCH.T1 ( C1 INT NO DEFAULT -- NOT NULL NOT DROPPABLE , C2 INT NO DEFAULT -- NOT NULL NOT DROPPABLE , C3 INT DEFAULT NULL , CONSTRAINT CAT.SCH.T1_104871911_0089 PRIMARY KEY (C1 ASC, C2 ASC) NOT DROPPABLE , CONSTRAINT CAT.SCH.
Examples of SHOWDDL MXCI Commands NO AUDITCOMPRESS; --- SQL operation complete. >>CREATE INDEX IDXA on T1 CHECK SID > 1000; --- SQL operation complete. >>CREATE UNIQUE INDEX UIDX ON T1 (A); --- SQL operation complete. >>CREATE CONSTRAINT C1 on T1 CHECK SID > 1000; --- SQL operation complete.
Examples of SHOWDDL MXCI Commands --- SQL operation complete. ; • This is an example of SHOWDDL on an SQL/MP table using the SQLMP syntax option. File names are shown fully qualified. >>CREATE TABLE T1 (name CHAR(10) DEFAULT 'nobody' HEADING 'NAME', SID LARGEINT NOT NULL, PRIMARY KEY (SID DESC), SSN INT UNSIGNED NOT NULL, birthdate DATE NOT NULL ) PARTITION ( \FIGARO.$DATA14.DEANCAT.
Examples of SHOWDDL MXCI Commands SET MYNEWROW.B = MYNEWROW.B + MYOLDROW.D; >>SHOWDDL T074T3; CREATE TABLE CAT.SCH.T074T3 ( A INT NO DEFAULT -- NOT NULL NOT DROPPABLE , B INT DEFAULT NULL , C CHAR(8) CHARACTER SET ISO88591 COLLATE DEFAULT DEFAULT NULL , D INT DEFAULT NULL , CONSTRAINT CAT.SCH.T074T3_102459148_0001 PRIMARY KEY (A ASC) NOT DROPPABLE , CONSTRAINT CAT.SCH.T074T3_102459148_0000 CHECK (CAT.SCH.T074T3.A IS NOT NULL) NOT DROPPABLE ) LOCATION \FIGARO.$DATA.ZSDADM53.
Examples of SHOWDDL MXCI Commands PARAMETER STYLE JAVA CONTAINS SQL NOT DETERMINISTIC ISOLATE ; >>showddl procedure T110_IO_NN; CREATE PROCEDURE CAT.SCH.T110_IO_NN ( IN IN1 NUMERIC(9,3), OUT OUT2 NUMERIC(9,3) ) EXTERNAL NAME 't110.T110_io_nn (java.math.BigDecimal,java.math.
SHOWLABEL Command MXCI Commands SHOWLABEL Command Considerations for SHOWLABEL Examples of SHOWLABEL The SHOWLABEL command displays file-label information for SQL/MX objects. This information includes the object version, physical location, and other characteristics. Supported objects are tables, trigger temporary tables, views, and indexes. SHOWLABEL is an SQL/MX extension. SHOWLABEL {[namespace ] object-name | location-name } [, DETAIL ] namespace is: TABLE | INDEX object-name is: [catalog.][schema.
Considerations for SHOWLABEL MXCI Commands • • Indexes Triggers Considerations for SHOWLABEL Every SQL object includes a logical file label to store the object’s file attributes and information about its dependent objects. The resource fork is a new file that contains structural descriptions of a table. When an SQL/MX object is created, two physical files are instantiated: the data fork and the resource fork. The data fork is where the user data resides.
Considerations for SHOWLABEL MXCI Commands LastModTimestamp Date, time, and Julian timestamp indicating when the object’s data was last modified. LastOpenTimestamp Date, time, and Julian timestamp of last open time. NEVER OPENED is generated if the object has never been opened (for example, timestamp=0). SMDtable Indicates whether the object is a system metadata (SMD) table. User metadata tables are not SMD tables. File Organization The file organization of the object (for example, key-sequenced).
Examples of SHOWLABEL MXCI Commands Max Extents Maximum number of extents. EOF The relative byte address of the first byte of the next available block. Extents Allocated Number of extents currently allocated for the file. Index Levels Number of index levels used for index blocks. SHOWLABEL, DETAIL Output SHOWLABEL, DETAIL returns the SHOWLABEL output and some additional information. This table describes the additional information provided by SHOWLABEL, DETAIL.
Examples of SHOWLABEL MXCI Commands RedefTimestamp: ) CreationTimeStamp: ) LastModTimestamp: ) LastOpenTimeStamp: 29 Feb, 2004 20:34:18 ( 211944875658652063 29 Feb, 2004 20:31:24 ( 211944875484237505 29 Feb, 2004 20:31:24 ( 211944875484237505 NEVER OPENED SMDtable: F File Organization: Key-sequenced Block Length: 4096 File Code: 550 AuditCompress: T Audited: T (If F, a Utility operation is in progress or has failed) Broken: F Buffered: T ClearOnPurge: F Corrupt: F (If T, a Utility operation is in progre
Examples of SHOWLABEL MXCI Commands RedefTimestamp: ) CreationTimeStamp: ) LastModTimestamp: ) LastOpenTimeStamp: SecurityTimestamp: ) 29 Feb, 2004 20:34:18 ( 211944875658652063 29 Feb, 2004 20:31:24 ( 211944875484237505 29 Feb, 2004 20:31:24 ( 211944875484237505 NEVER OPENED 29 Feb, 2004 20:31:24 ( 211944875484152346 SMDtable: F File Organization: Key-sequenced Block Length: 4096 File Code: 550 AuditCompress: T Audited: T (If F, a Utility operation is in progress or has failed) Broken: F Buffered: T Cl
Examples of SHOWLABEL MXCI Commands 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 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: >>showlabel \CARNAG.$CHINA.ZSDQHSJZ.
Examples of SHOWLABEL MXCI Commands 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 Partition Ar
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-37 and SET SHOWSHAPE Command on page 4-50. Use SHOWSHAPE only within an MXCI session. SHOWSHAPE statement statement is an SQL DML statement.
Examples of SHOWSHAPE MXCI Commands • Display the access plan for the given statement: SET NAMETYPE NSK; SET MPLOC $DATA06.PERSNL; SHOWSHAPE SELECT first_name, last_name, deptnum, salary FROM persnl.employee WHERE salary > (SELECT MAX (salary) FROM persnl.employee WHERE deptnum = 1500); control query shape hybrid_hash_join(partition_access( sort_groupby(scan(path 'EMPLOYEE', forward, mdam off))), partition_access(scan(path 'EMPLOYEE', forward, mdam off))); --- SQL operation complete.
5 SQL/MX Utilities A utility is a tool that runs within NonStop SQL/MX or from the OSS shell and performs such tasks as importing data, duplicating files, fixing database discrepancies, and migrating metadata. SQL/MX utilities can be run from MXCI or from the OSS command line. For a description of MXCI, see MXCI SQL/MX Conversational Interface on page 1-2. For information about OSS, see the Open System Services User’s Guide. You must be the owner of a schema to use BACKUP or RESTORE against SQL/MX tables.
Privileges Required to Execute Utilities SQL/MX Utilities PURGEDATA Utility on page 5-72 Purges data from tables, indexes, or partitions. RECOVER Utility on page 5-76 Determines the state of a failed utility operation and restores recoverable objects. VERIFY Operation on page 5-78 Reports whether SQL/MX objects and programs are consistently described in file labels, resource forks, and metadata. Privileges Required to Execute Utilities Utility Privileges Required BACKUP Be the schema owner.
Checking File Locks SQL/MX Utilities Checking File Locks When you run the DUP, import, MODIFY, POPULATE INDEX or PURGEDATA utilities, they lock files. If the operation fails before completion, you need to check the file locks to determine if you need to run the RECOVER utility to undo or resume the failed partition operation. To find out whether a failed partition operation needs to be recovered, issue this query from an MXCI prompt: select substring(o.object_name from 1 for 40) as object_name, o.
DUP Utility SQL/MX Utilities DUP Utility Syntax Description of DUP Considerations for DUP DUP is a syntax-based utility that can be executed through MXCI. The DUP utility copies SQL/MX tables and optionally their indexes and constraints. DUP source-target-list [ mapping ][,dup-option [, dup-option]...] source-target-list is: { source-table TO target-table } source-table is: [[catalog].schema.]object target-table is: [{catalog | *}.{schema | *}.]object mapping is: { LOCATION (volume-map) [, volume-map ] ..
Syntax Description of DUP SQL/MX Utilities Syntax Description of DUP source-target-list specifies the source-table and target-table names. source-table specifies the fully qualified name for the table to be copied. The form of the name is catalog-name.schema-name.table-name, where each part is an SQL identifier. If you do not specify the catalog and schema parts of the source-table, DUP uses the default catalog and schema values for that session. target-table specifies the name of the target table.
Syntax Description of DUP SQL/MX Utilities INDEX[ES] [{ON [(index-list)] | OFF }] is an optional clause that specifies how dependent indexes are copied. INDEX[ES] is the same as INDEX[ES] ON. Unpopulated indexes are not duplicated. ON [(index-list)] duplicates all user-created and system-generated indexes. If the source and target tables reside in the same catalog and schema, you must specify index-list to identify the new index names. The default is ON.
Syntax Description of DUP SQL/MX Utilities constraints and are duplicated if you specify CONSTRAINTS ON. NOT DROPPABLE constraints are always duplicated. ON duplicates all DROPPABLE unique, not null, primary key, and check constraints. The default is ON. If the source table has unique or droppable primary key constraints, the INDEX option must be set to ON, otherwise DUP returns an error. constraint-list is a list of constraint-maps. constraint-map specifies the target constraint name.
Considerations for DUP SQL/MX Utilities Considerations for DUP • • • • • You must have all privileges for the source table and own the schema where the target table will reside or be the super ID. Referential integrity constraints and triggers are ignored. The source table can exist on a remote node and be referenced by the current DUP operation if the remote node is visible to the local node. The target table can also exist in a catalog and schema that reside on a visible remote node.
Considerations for DUP SQL/MX Utilities To serialize these utility operations, NonStop SQL/MX has the concept of a DDL lock. This is a lock that prevents database structure changes from occurring while a utility request is executing. A utility request informs SQL that it is running, perform commands in as many transactions as necessary, then informs SQL that the operation has completed. While the utility request is running, no conflicting DDL or utility operation can occur.
Examples of DUP SQL/MX Utilities Examples of DUP • This example copies the partitions of the source table (using a different catalog and schema) to the same locations: DUP mycat.myschema.mytable1 TO mycat1.myschema1.*; • This example copies the partitions of the source table on $data1 and $data2 to the partitions of the target table on $data2 and $data3 respectively.
FIXUP Operation SQL/MX Utilities FIXUP Operation Considerations for FIXUP Operation Examples of FIXUP Operation FIXUP is an OSS command-line utility run from mxtool that repairs problems in the SQL/MX database that cannot be repaired by normal operations. mxtool utility-operation utility-operation is: FIXUP {guardian-option | object-option} guardian-option is LABEL guardian-file g-opts guardian-file is [\node.]$volume.subvolume.
FIXUP Operation SQL/MX Utilities { -a= { on | off } toggles the audit attribute on the label. If the audit attribute is ON and you issue a request to turn it on, FIXUP returns a warning that the audit attribute is already on. If the audit attribute is OFF and you issue a request to turn it off, FIXUP returns a warning. You must be the super ID to perform this operation. If you turn off auditing for the table, this invalidates online dumps.
FIXUP Operation SQL/MX Utilities 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. If the object has partitions on remote nodes, FIXUP displays a warning and continues. If an update to the label or metadata fails, the operation fails.
Considerations for FIXUP Operation SQL/MX Utilities Considerations for FIXUP Operation If you change the redefinition timestamp of the label, all executor opens are invalidated. The next time the executor tries to open the file, a similarity check is performed. If it fails, programs are recompiled. The redefinition timestamp is updated whenever the corrupt attribute, broken attribute, or audit attribute is changed. If the table has remote partitions, you must run FIXUP on each remote node.
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 Examples of import The import utility imports data from an input file in ASCII or UCS2 format into an SQL/MX table. The import utility executes at the OSS or MXCI command prompt using the command-line options described next. You cannot directly execute the import utility from programs. Note. You can use DataLoader/MX, in conjunction with import, to load and maintain SQL/MP and SQL/MX databases.
import Utility SQL/MX Utilities If you want to import data to the table mycat.mysch."%&*()", you must specify the delimited table name within the import command: import 'mycat.mysch.”%&*()”' -I myinput.dat The delimited name is enclosed within a pair of double quotes (") and the fully qualified name of the destination table and the data is enclosed in single quotes (‘). -I input-filename specifies the name of the input file that contains the data to import.
import Utility SQL/MX Utilities -IP proc-name directs import to accept data from a DataLoader process, proc-name. -L max-errors directs import to ignore the specified number of parsing errors without terminating. Executor errors due to constraint violation are not included in this count. -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.
Considerations for import SQL/MX Utilities -U format-filename specifies the name of an OSS or Guardian text file that contains format specifications for input-filename. Using a format file is optional. format-filename must be an OSS text file (an odd-unstructured file, type 180) or a Guardian text file (type 101). You must specify the file name in OSS format (for example: /usr/bin/input.txt or /G/USER/DATA/INPUT). -W file-type specifies the input file type.
Considerations for import SQL/MX Utilities DDL Locks When import uses the fast insert technique, a DDL lock is held on the object for the entire duration of the operation. This strategy prevents any concurrent import operation or any DDL or utility operation on this table until the first import using the fast insert technique is complete.
Considerations for import SQL/MX Utilities Format File Sections for import A format file is optional and, if used, consists of up to four sections. You specify the format file by using the option -U format-filename. A sample format file is provided in the import example (see Format File Describing the Data).
Considerations for import SQL/MX Utilities NormalizeDate=normalize Y or N. Default is N; no datetime normalization. [COLUMN FORMAT] col=field_name,skip [,NullDefault_flag] The source field name and whether to skip the field in the source data file. If data is to be stored in the target table, field_name must be the name of the target column. skip is Y or N. Default is N: do not skip. NullDefault_flag is Y or N. Default is N: no null or default flag preceding the data.
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-26. 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 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. For example: 135,"Jackson,Jane",100 East St.,Cupertino,CA,95014 If your field data contains default field qualifier of single quote ("), enclose this field data within field qualifiers.
Considerations for import SQL/MX Utilities target column, you can specify two field delimiters with the appropriate number of blanks between the delimiters. Default Values for Delimited Data Input Files For a delimited input file, if a column in the target table does not allow null, using two consecutive field delimiters directs import to use the default value for the column (instead of null for the column). For example, a column defined as NOT NULL might have space as its default value.
Considerations for import SQL/MX Utilities import converts the character data in the input file to the appropriate data types as defined in the target table. The data types of the values in an input record must be compatible with the data types of the columns in the destination table. Use the -Z option to specify the character set for the data being imported.
Considerations for import SQL/MX Utilities • If the interval value to be imported is INTERVAL '03-04' YEAR TO MONTH, specify the field without the keywords in the input data file as: 03-04 Datetime Normalization NonStop SQL/MX supports the three standard ANSI SQL:1999 datetime formats, which can be loaded without normalization.
Examples of import SQL/MX Utilities online dumps. After the import operation completes, you must perform a new TMF online dump for all partitions of the table. If multiple import processes are started on different partitions of a table without indexes, the first import operation turns auditing off for all the partitions of the table. In this scenario only the first import operation would benefit from the efficient insert technique.
Examples of import SQL/MX Utilities DateDelimiter=/ TimeDelimiter=: FourDigitYear=Y DecimalSymbol=. [COLUMN FORMAT] col=id,N col=company,N col=phone,N col=fax,N [DELIMITED FORMAT] FieldDelimiter=, RowDelimiter=\n Qualifier=" import Load Command This import command imports data into the COMPANY table from the delimited input file named COINPUT using the format file FORMFILE: import cat.sch.
Examples of import SQL/MX Utilities [FIXED WIDTH FORMAT] col=id,1,11 col=company,12,175 col=phone,187,12 col=fax,199,12 RecordLength=66 import Load Command This import command imports data into the COMPANY table from the fixed width input file named COINPUT using the format file FORMFILE: import cat.sch.company -i COINPUT -u FORMFILE -w FIXED Parallel Load for import Use parallel load when the destination table is partitioned.
Examples of import SQL/MX Utilities You might specify the three import commands as: C:\>import corpcat.persnl.employee -I empfile -C 2999 -T 500 C:\>import corpcat.persnl.employee -I empfile -C 1999 -F 3000 -T 500 C:\>import corpcat.persnl.employee -I empfile -C 1999 -F 5000 -T 500 The count of 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.
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 metadata from a previous version of SQL/MX into system metadata tables of SQL/MX Release 2.x. migrate handles full or partial migrations. For instructions on how to migrate metadata, see the SQL/MX Installation and Management Guide. For migrating stored procedures, see the SQL/MX Guide to Stored Procedures in Java.
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. For information about limitations on online operations, see Considerations for MODIFY on page 5-54.
Reuse an Existing Partition of a Range Partitioned Table SQL/MX Utilities LOCATION [\node.]$volume[.subvolume.file-name] | [KEY=] {FIRST | LAST} PARTITION | [KEY=] key-value is a location for a partition, or the partitioning key (the FIRST KEY) value (key-value) of a partition, to be modified. If the partition is the primary partition, you can also specify the partition using the FIRST PARTITION phrase.
SQL/MX Utilities Manage Partitions of Range Partitioned Tables and Indexes Manage Partitions of Range Partitioned Tables and Indexes Use MODIFY to manage range partitions of SQL/MX tables and indexes. You must manage tables and indexes separately regardless of their relationship. Both offline and online operations are supported. For information about limitations on online operations, see Considerations for MODIFY on page 5-54.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities commit-options is: { COMMIT WORK [ WHEN READY ] { [ { AFTER time } ] { [ { BEFORE time } ] } } } [[catalog.]schema.]object is the name of the range partitioned object. If you do not specify the schema and catalog name, NonStop SQL/MX uses the default catalog and schema of your MXCI session. object is a table or an index, depending on the TABLE or INDEX keyword.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities add-move-boundary-range is the boundary range. | [KEY=] FIRST KEY UPTO [KEY=] key-value [KEY=] key-value [THRU [KEY=] LAST KEY] specifies the partitioning range add-move-boundary-range of a partition to be split and then added to a new partition.
Manage Partitions of Range Partitioned Tables and Indexes SQL/MX Utilities | | LOCATION [\node.]$volume[.subvolume.file-name] [KEY=] {FIRST | LAST} PARTITION [KEY=] key-value is a location for a partition, or the partitioning key (the FIRST KEY) value (key-value) of a partition, to be modified. If the partition is the primary partition, you can also specify the partition using the FIRST PARTITION phrase.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities the size of the primary extent and secondary extents separately. If you do not specify EXTENT, MODIFY uses the extent size values of the source partition. See EXTENT on page 8-6 and MAXEXTENTS on page 8-8. WITH SHARED ACCESS [commit-options] specifies that the operation is an online operation. If you do not specify commit-options, the default is COMMIT WHEN READY.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities new-partition is: LOCATION [\node.]$volume[.subvolume.file-name] [[catalog.]schema.]object is the name of the object. If you do not specify the schema and catalog name, MODIFY uses the current default schema and catalog of your MXCI session. object is a table or an index, depending on the TABLE or INDEX keyword. DROP [PARTITION] WHERE partition-identification is the hash partition to be dropped.
Manage Partitions of Hash Partitioned Tables and Indexes SQL/MX Utilities Otherwise, the values of the primary partition apply. partition-identification is optional only when the object has only one partition. partition-identification describes the partition. LOCATION partition | {FIRST | LAST} PARTITION | [KEY=] VALUE(partition-number) is a location for a partition, or the partitioning key (the FIRST KEY) value (key-value) of a partition, to be moved or dropped.
Manage Partitions of Hash 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 value of the source partition. See EXTENT on page 8-6 and MAXEXTENTS on page 8-8.
Manage System-Clustered Tables SQL/MX Utilities When you add a hash partition, a subset of data from existing partitions is redistributed to the new partition. Manage System-Clustered Tables A system-clustered table has no primary key and no STORE BY clause. Its primary key defaults to the SYSKEY. 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.
Considerations for MODIFY 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 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-8.
Considerations for MODIFY SQL/MX Utilities • • • • • • Dropping an existing empty partition. Moving an existing partition to a new location. Splitting an existing partition and then moving the first or last part of the data to a new partition. 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.
Considerations for MODIFY SQL/MX Utilities The setting in the SYSTEM_DEFAULTS table applies to all partition operations in the current node unless you override it by using a CONTROL QUERY DEFAULT statement. You can issue the statement from MXCI, and the setting from this statement applies only to subsequent requests within the same MXCI.
Considerations for MODIFY SQL/MX Utilities MODIFY and Table Reloading Some of MODIFY’s options start a FUP RELOAD process that runs in the background. Until this process completes, you cannot do DDL or utility operations on the file. You can monitor the reload process’s progress with this command: FUP STATUS physical-file-name If FUP STATUS returns a RELOAD COMPLETED message and the physical file is not being opened by another process, you can start the next MODIFY operation.
Examples of MODIFY SQL/MX Utilities Examples of MODIFY • Move all records of an existing range partition to a new location: MODIFY TABLE tab1 MOVE PARTITION WHERE LOCATION $data02 TO LOCATION $data03; • Move records of an existing range partition, whose key is equal to 10000 to the last key, to a new location: MODIFY TABLE tab1 MOVE PARTITION WHERE KEY = VALUE (10000) THRU KEY = LAST KEY TO LOCATION $data02 EXTENT (512, 512) MAXEXTENTS 256; • Move the second partition of a hash partitioned table to
mxexportddl Utility SQL/MX Utilities mxexportddl Utility Considerations for mxexportddl mxexportddl is an OSS command-line utility that captures user SQL/MX metadata and saves it in XML format. mxexportddl {-I input-table-name | -S catalog-name.schema-name | -H} [-O export-metadata-file-name] [-C] mxexportddl must be lowercase. -I input-table-name specifies the fully qualified name for the SQL/MX Release 2.x table whose metadata is to be imported. The form of the name is catalog-name.schemaname.
Considerations for mxexportddl SQL/MX Utilities -O export-metadata-file-name [-C] is the name of a OSS text file that will contain the export metadata output created by mxexportddl. The file name is an OSS file that can include an optional path specification. This file’s file type should be .xml. If the output file exists and you do not specify the -C option, output is appended to the existing file. The existing output file must have the proper XML export metadata header tags.
MXGNAMES Utility SQL/MX Utilities MXGNAMES Utility Considerations for MXGNAMES Examples of MXGNAMES MXGNAMES is a Guardian program that is run from a TACL prompt or an OBEY command file. It converts one or more ANSI table names into a list of corresponding Guardian file names, appropriately formatted for TMF or BACKUP/RESTORE 2.
MXGNAMES Utility SQL/MX Utilities SQLMX-table-name is a single fully qualified SQLMX table name entered directly on the command line output-format indicates what subsystem the output file is to be used with: -BR2 indicates output should be formatted for use with the BR2 RESTORE command.
Considerations for MXGNAMES SQL/MX Utilities -HELP displays help for the utility. Considerations for MXGNAMES You must have READ/WRITE access to the Guardian subvolume where you are executing MXGNAMES. Input and output of MXGNAMES is in standard Guardian EDIT files, which have these characteristics: • • Guardian file code of 101 Maximum line length of 255 characters You can use other tools or programs to capture data for use with MXGNAMES.
Examples of MXGNAMES SQL/MX Utilities location $VOL1.ZSD0126B.BXNW1R00 hash partition by (c4) ( add location $VOL2.ZSD0126B.BXNW2R00 , add location $VOL3.ZSD0126B.BXNW3R00 , add location $VOL4.ZSD0126B.BXNW4R00 ) ; create unique index T126B_NDX1 on CAT.SCH.T126B(C2, C1) LOCATION $vol1.zsd0126b.qdx1g100 hash partition by (c2) ( add location $VOL2.ZSD0126B.QDX1G200 , add location $VOL3.ZSD0126B.QDX1G300 , add location $VOL4.ZSD0126B.QDX1G400 , add location $VOL5.ZSD0126B.
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.ZSD0126A.BXNL1R00 NAME PART_A_Z_1 PARTITION ( ADD FIRST KEY (1000) LOCATION \NSK.$VOL2.ZSD0126A.
Examples of MXGNAMES SQL/MX Utilities $VOL4.ZSD0126A.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.ZSD0126A.BXNL6R00 \PNODE.$VOL1.ZSD0126A.QDXWG100 \PNODE.$VOL2.ZSD0126A.QDXWG200 \PNODE.$VOL3.ZSD0126A.QDXWG300 \PNODE.$VOL4.ZSD0126A.QDXWG400 \PNODE.$VOL1.ZSD0126A.BXNW1R00 \PNODE.$VOL2.ZSD0126A.BXNW2R00 \PNODE.$VOL3.ZSD0126A.BXNW3R00 \PNODE.$VOL4.ZSD0126A.BXNW4R00 \PNODE.$VOL1.ZSD0126A.QDX1G100 \PNODE.$VOL2.ZSD0126A.QDX1G200 \PNODE.$VOL3.ZSD0126A.QDX1G300 \PNODE.$VOL4.ZSD0126A.QDX1G400 \PNODE.$VOL5.ZSD0126A.
mxtool Utility SQL/MX Utilities mxtool Utility mxtool is an OSS command-line utility that performs various utility functions. mxtool utility-operation utility-operation is { FIXUP fixup operation GOAWAY goaway operation HELP [help options] INFO info operation VERIFY verify operation | | | | } help options is { ALL | FIXUP | GOAWAY | INFO | VERIFY } mxtool utility-operation executes this utility, which must appear in lowercase letters. utility-operation is the operation to be performed.
POPULATE INDEX Utility SQL/MX Utilities POPULATE INDEX Utility Considerations for POPULATE INDEX Examples of POPULATE INDEX POPULATE INDEX is a syntax-based utility that can be executed through MXCI. The POPULATE INDEX utility loads SQL/MX indexes. POPULATE INDEX index-name ON [[catalog.]schema.]table-name Syntax Description of POPULATE INDEX [[catalog.]schema.]index-name is the name of the index to populate. If you specify the catalog and schema, they must be the same as that defined for table-name.
Considerations for POPULATE INDEX SQL/MX Utilities loaded, specify RECOVER with the CANCEL option to roll back the operation. If you run the RECOVER operation with the incorrect option, RECOVER displays an error message so you can rerun it with the correct option. For information, see Checking File Locks on page 5-3. No restart facility is provided to recover partially-loaded data. • • • To avoid TMF limitations if a large amount of data is to be moved, POPULATE INDEX runs in multiple TMF transactions.
Examples of POPULATE INDEX SQL/MX Utilities Examples of POPULATE INDEX • This example loads the specified index from the specified table: POPULATE INDEX mycat.myschema.myindex ON mycat.myschema.mytable; • This example loads the specified index from the specified table, which uses the default catalog and schema: POPULATE INDEX mycat.myschema.
PURGEDATA Utility SQL/MX Utilities PURGEDATA Utility Considerations for PURGEDATA Examples of PURGEDATA PURGEDATA is a syntax-based utility that can be executed through MXCI. The PURGEDATA utility deletes all data from an SQL/MX table and its related indexes or from specified partitions of tables that have no indexes. PURGEDATA table-name [list-of-partitions] [IGNORE_TRIGGER] table-name is: [ [catalog.]schema.
Syntax Description of PURGEDATA SQL/MX Utilities this list. PURGEDATA returns errors if the specified partitions do not exist, if dependent indexes exist on the table, and if the source object does not exist. partition-map describes a partition or range of partitions: guardian-name specifies the partially or fully qualified Guardian name that identifies the partition. If you specify only the volume, all partitions on the volume that belong to the object are affected.
Considerations for PURGEDATA SQL/MX Utilities Considerations for PURGEDATA • • • • • • • You must have ALL privileges on the table. An error is returned if you specify a list-of-partitions for a hash-partitioned table. For hash-partitioned objects, data must be purged from the entire table. table-name can exist on a remote node and be referenced by the current PURGEDATA operation if the remote node is visible to the local node.
Examples of PURGEDATA SQL/MX Utilities Examples of PURGEDATA • This example purges the data in the specified table. If the table has indexes, their data is also purged. PURGEDATA mycat.myschema.mytable; • This example purges the data in the specified partition, which has a Guardian name: PURGEDATA mycat.myschema.mytable WHERE LOCATION $DATA1.ZSD009TO.QZ780000; • This example purges data from all partitions of the table: PURGEDATA mycat.myschema.
RECOVER Utility SQL/MX Utilities RECOVER Utility Considerations for RECOVER Examples of RECOVER RECOVER is a syntax-based utility that can be executed through MXCI. The RECOVER utility determines the state of a failed utility operation and executes its recovery procedure. RECOVER completes the failed utility operation by rolling back the entire operation or by completing the operation.
Considerations for RECOVER SQL/MX Utilities CANCEL If you specify CANCEL, RECOVER attempts to undo the effects of the failed utility operation. Otherwise, recovery fails. The default is CANCEL. RESUME If you specify RESUME, RECOVER attempts to carry the failed utility operation to its completion. Otherwise, the recovery fails. Considerations for RECOVER • • You must have the privileges required to perform the utility you are recovering.
VERIFY Operation SQL/MX Utilities VERIFY Operation Considerations for VERIFY Examples of VERIFY VERIFY is an OSS command-line utility run from mxtool that reports whether SQL/MX objects and programs are consistently described in file labels, resource forks, and metadata. mxtool utility-operation utility-operation is: VERIFY { object-option | file-option } object-option is: catalog.schema.object name is catalog.schema.object file option is: PART [\node.]$volume.subvol.
Considerations for VERIFY SQL/MX Utilities If you do not specify \node, the default is the Guardian system named in your =_DEFAULTS define. You can find the Guardian (physical) file name by using the SHOWLABEL command. For example: SHOWLABEL CAT.SCH.T1, DETAIL; For information on this command, see SHOWLABEL Command on page 4-78. Considerations for VERIFY You must have SELECT privilege for all columns of the table you are verifying.
Examples of VERIFY SQL/MX Utilities • • • • 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. Operations that change metadata or labels such as DDL, partition management, PURGEDATA, and UPDATE STATISTICS statements cannot run concurrently.
Examples of VERIFY SQL/MX Utilities 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.T1000300 NAME SQUAW_DATA08_ZSDVVVVV_T1000300 EXTENT (16, 512) MAXEXTENTS 200 , ADD FIRST KEY (3000) LOCATION \SQUAW.$DATA08.ZSDVVVVV.
Examples of VERIFY SQL/MX Utilities \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.ZSDVVVVV.T1000400 Verifying resource fork for partition: \SQUAW.$DATA08.ZSDVVVVV.T1000400 Verifying constraints: \SQUAW.$DATA08.ZSDVVVVV.
6 SQL/MX Language Elements NonStop SQL/MX language elements, which include data types, expressions, functions, identifiers, literals, and predicates, occur within the syntax of SQL/MX statements and MXCI commands. The statement and command topics support the syntactical and semantic descriptions of the language elements in this section.
SQL/MX Language Elements Catalogs Catalogs SQL/MX Catalogs An SQL/ MX catalog is a named logical object that contains descriptions of a set of schemas. You can access SQL/MX objects with the three-part name of the actual object. The ANSI SQL:1999 catalog name is an SQL identifier. In SQL/MX Release 2.x, ANSI catalogs do not have any physical representation, nor do they have a physical relationship to SQL/MP catalogs.
Character Sets SQL/MX Language Elements Character Sets When you install NonStop SQL/MX, you are prompted to set the character set default to UCS2 or ISO88591. If you do not specify a character set, the default is UCS2. Once it is set, you cannot change it. After you have set the character set default, when you create SQL/MX tables, NCHAR data type fields use this character set as the default.
SQL/MX Language Elements Restrictions on Using Character Set Data In SQL/MP, a character data type has an associated character set and collation that can be implicitly or explicitly specified. Internally, the ISO88591 character set is implemented as an 8-bit data type, while the UCS2, KANJI, and KSC5601 character sets are implemented as 16-bit data types. The CHAR data type can be associated with any of the character sets. The NCHAR data type is typically associated with the UCS2 character set.
SQL/MX Language Elements Collations Collations A collation is an object that contains rules for a collating sequence (the sequence in which characters are ordered for sorting), case, and character class and character string equivalence. Every character set has a collation. See Character Sets on page 6-3. To be compared, character strings must be from the same character set.
SQL/MX Language Elements Columns Columns Examples of Derived Column Names A column is a vertical component of a table and is the relational representation of a field in a record. A column contains one data value for each row of the table. A column value is the smallest unit of data that can be selected from or updated in a table. Each column has a name that is an SQL identifier and is unique within the table or view that contains the column.
SQL/MX Language Elements Column Default Settings Column Default Settings You can define specific default settings for columns when the table is created. The CREATE TABLE statement defines the default settings for columns within tables. The default setting for a column is the value inserted in a row when an INSERT statement omits a value for a particular column. Examples of Derived Column Names • These two examples show how to use names for derived columns.
Constraints SQL/MX Language Elements Constraints An SQL/MX constraint is an object that protects the integrity of data in a table by specifying a condition that all the values in a particular column or set of columns of the table must satisfy. NonStop SQL/MX enforces these constraints on SQL/MP and SQL/MX tables: CHECK Column or table constraint specifying a condition must be satisfied for each row in the table. For SQL/MX tables, check constraints cannot contain non-ISO88591 string literals.
SQL/MX Language Elements Creating and Dropping Constraints on SQL/MP Tables Constraint Names When you create a constraint, you can either specify a name for it or allow a name to be generated by NonStop SQL/MX. You can optionally specify both column and table constraint names. Constraint names are three-part logical names. Constraints have their own namespace within a schema, so a constraint name can have the same name as a table, index, or view.
SQL/MX Language Elements Correlation Names Correlation Names A correlation name is a name you can associate with a table reference that is a table, view, or subquery in a SELECT statement to: • • • Distinguish a table or view from another table or view referred to in a statement Distinguish different uses of the same table Make the query shorter A correlation name can be explicit or implicit.
SQL/MX Language Elements Database Objects Database Objects A database object is an SQL entity that exists in a namespace, maps to a Guardian file in most cases, and is registered in the system catalog. SQL/MX Release 2.x includes SQL/MX objects. SQL/MX DML statements can access both SQL/MX and SQL/MP objects. The subsections listed below describe these SQL/MX objects. Collations Constraints Indexes Partitions SQL/MP Aliases Stored Procedures Tables Triggers Views Ownership In SQL/MX Release 2.
SQL/MX Language Elements Database Object Names Database Object Names Logical Names for SQL/MX Objects Physical Names for SQL/MP Objects Logical Names for SQL/MP Objects DEFINE Names for SQL/MP Objects SQL/MX Object Namespaces Considerations for Database Object Names SQL/MX DML statements can refer to SQL/MX database objects and SQL/MP database objects. To refer to a database object in a statement, use an appropriate database object name.
SQL/MX Language Elements Logical Names for SQL/MP Objects You can choose to use physical names to refer to SQL/MP tables and views by setting the NAMETYPE attribute to NSK. If the NAMETYPE is NSK, NonStop SQL/MX automatically qualifies a physical table or view name with the current default node, volume, and subvolume names unless you explicitly specify these names with the object name. In SQL/MX releases earlier than SQL/MX Release 2.
SQL/MX Language Elements SQL/MX Object Namespaces You cannot use DEFINE names to refer to SQL/MX tables, views, partitions, or stored procedures. The advantages of using DEFINEs rather than Guardian physical names are: • DEFINE names are easier to understand than Guardian names. For example, the name =CUSTOMERS is simpler than the physical name \SYS.$VOL2.SALES.CSTMERS. See ADD DEFINE Command on page 4-3. • DEFINE names provide location independence.
SQL/MX Language Elements Considerations for Database Object Names You can use the CREATE SQLMP ALIAS command within your application to create the needed mappings from logical to physical names. This command has the form: CREATE SQLMP ALIAS catalog-name.schema-name.table-name [\node.]$volume.subvol.filename When this command is executed, a mapping is inserted as a row in the OBJECTS table. SQL/MP aliases are simulated ANSI names that represent the underlying Guardian physical names of SQL/MP objects.
Data Types SQL/MX Language Elements Data Types SQL/MX data types are either character, datetime, interval, or numeric (exact or approximate): Character String Data Types on page 6-20 Fixed-length and variable-length character data types. Datetime Data Types on page 6-24 DATE, TIME, and TIMESTAMP data types. Interval Data Types on page 6-30 Year-month intervals (years and months) and day-time intervals (days, hours, minutes, seconds, and fractions of a second).
SQL/MX Language Elements Comparable and Compatible Data Types Datetime Data Types Values of type datetime are mutually comparable and mutually assignable only if the types have the same datetime fields. A DATE, TIME, or TIMESTAMP value can be compared with another value only if the other value has the same data type. All comparisons are chronological.
Comparable and Compatible Data Types SQL/MX Language Elements In addition, if you are using an SQL/MP table that contain FLOAT columns (REAL, DOUBLE PRECISION) with user default values specified, a similarity check for the table with the compile-time default value might fail for some values, and NonStop SQL/MX will recompile the query. For some queries that use the default value, you might not be able to access a float column with a default value near the boundary value for Tandem float values.
SQL/MX Language Elements Comparable and Compatible Data Types You can select the rows from the table: >>select * from $vol.subvol.tfloat; C1 C2 C3 ----------- ----------- ------------------------10 ? -1.15792089237316160E+077 --- 1 row(s) selected.
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 Character String Data Types NCHAR Columns in SQL/MP Tables In NonStop SQL/MX and NonStop SQL/MP, the NCHAR type specification is equivalent to: • • • NATIONAL CHARACTER NATIONAL CHAR CHAR ... CHARACTER SET ..., where the character set is the default character set for NCHAR Similarly, you can use NATIONAL CHARACTER VARYING, NATIONAL CHAR VARYING, and VARCHAR ... CHARACTER SET ... .
SQL/MX Language Elements Datetime Data Types Datetime Data Types Considerations for 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.
Datetime 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 Interval Data Types Considerations for Interval Data Types SQL/MP Considerations for Interval Data Types Values of interval data type represent durations of time in year-month units (years and months) or in day-time units (days, hours, minutes, seconds, and fractions of a second).
SQL/MX Language Elements Interval Data Types point, and the fractional-precision is the number of digits of precision after the decimal point. The default for leading-precision is 2, and the default for fractional-precision is 6. The maximum for leading-precision is 18, and the maximum for fractional-precision is 6. Considerations for Interval Data Types Interval Leading Precision The maximum for the leading-precision depends on the number of fields in the interval and on the fractional-precision.
Interval Data Types SQL/MX Language Elements SQL/MP Considerations for Interval Data Types Selecting INTERVAL Columns in SQL/MP Tables SQL/MP INTERVAL values represent durations of time in year-month units (years and months), in day-time units (days, hours, minutes, seconds, and fractions of a second), or in subsets of those units. A specific INTERVAL data type consists of a subset or range of these fields and a specified number of significant digits for the FRACTION field if it exists.
SQL/MX Language Elements Numeric Data Types ------------###### ###### ... NonStop SQL/MX returns a warning indicating that you selected an unsupported data type with undefined contents. Numeric Data Types Numeric data types are either exact or approximate. A numeric data type is compatible with any other numeric data type, but not with character, datetime, or interval data types.
SQL/MX Language Elements Numeric Data Types SMALLINT [SIGNED|UNSIGNED] specifies an exact numeric column—a two-byte binary integer, SIGNED or UNSIGNED. The column stores integers in the range unsigned 0 to 65535 or signed -32768 to +32767. The default is SIGNED. INT[EGER] [SIGNED|UNSIGNED] specifies an exact numeric column—a four-byte binary integer, SIGNED or UNSIGNED. The column stores integers in the range unsigned 0 to 4294967295 or signed -2147483648 to +2147483647. The default is SIGNED.
SQL/MX Language Elements Numeric Data Types There is no default. You must specify either 9(integer) or V9 (scale). FLOAT [( precision )] specifies an approximate numeric column. The column stores floating-point numbers and designates from 1 through 52 bits of precision. The range is from +/- 2.2250738585072014e-308 through +/-1.7976931348623157e+308 stored in 8 bytes. An IEEE FLOAT precision data type is stored as an IEEE DOUBLE, that is, in 8 bytes, with the specified 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-39 Operands can be combined with the concatenation operator (||). Example: 'HOUSTON,' ||' TEXAS' Datetime Value Expressions on page 6-40 Operands can be combined in specific ways with arithmetic operators.
Datetime 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 Value
SQL/MX Language Elements Datetime Value Expressions In this syntax diagram, the data type of a datetime primary is DATE, TIME, or TIMESTAMP. The data type of an interval term is INTERVAL.
Datetime Value Expressions SQL/MX Language Elements Datetime value expressions are built from operands that can be: • • • • • • • • • Interval value expressions Datetime or interval literals Host variables of type DATE, TIME, TIMESTAMP, and INTERVAL Dynamic parameters Column references with datetime or interval values Host variables of type INTERVAL Dynamic parameters Datetime or interval value functions Any aggregate functions, sequence functions, scalar subqueries, CASE expressions, or CAST expression
Datetime Value Expressions SQL/MX Language Elements In the last expression, the datetime primary is this scalar subquery: ( SELECT ship_timestamp FROM project WHERE projcode=1000 ) The preceding subquery returns a value with TIMESTAMP data type. Therefore, the data type of the result is TIMESTAMP.
SQL/MX Language Elements • Datetime Value Expressions Add an interval value qualified by YEAR to a datetime value: SELECT start_date + INTERVAL '1' YEAR FROM persnl.project WHERE projcode = 1000; (EXPR) ---------1997-04-10 --- 1 row(s) selected. • Subtract an interval value qualified by MONTH from a datetime value: SELECT ship_timestamp - INTERVAL '1' MONTH FROM persnl.project WHERE projcode = 134; (EXPR) -------------------------1996-12-01 00:00:00.000000 --- 1 row(s) selected.
SQL/MX Language Elements Interval Value Expressions Interval Value Expressions SQL/MP Considerations for Interval Value Expressions Considerations for Interval Value Expressions Examples of Interval Value Expressions The operands of an interval value expression can be combined in specific ways with addition and subtraction operators. In this syntax diagram, the data type of a datetime expression is DATE, TIME, or TIMESTAMP; the data type of an interval term or expression is INTERVAL.
SQL/MX Language Elements Interval Value Expressions numeric-primary is: unsigned-numeric-literal | column-reference | numeric-type-host-variable | dynamic parameter | numeric-value-function | aggregate-function | sequence-function | scalar-subquery | CASE-expression | CAST-expression | (numeric-expression) interval-qualifier is: start-field TO end-field | single-field start-field is: {YEAR | MONTH | DAY | HOUR | MINUTE} [(leading-precision)] end-field is: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND [(frac
Interval Value Expressions SQL/MX Language Elements If the interval expression is the difference or sum of interval operands, the interval qualifiers of the operands are either year-month or day-time. If you are updating or inserting a value that is the result of adding or subtracting two interval qualifiers, the interval qualifier of the result depends on the interval qualifier of the target column.
Interval Value Expressions SQL/MX Language Elements Restrictions on Operations You can use datetime and interval operands with arithmetic operators in an interval value expression only in these combinations: Operand 1 Operator Operand 2 Result Type Datetime – Datetime Interval Interval + or – Interval Interval Interval * or / Numeric Interval Numeric * Interval Interval This table lists valid combinations of datetime and interval arithmetic operators, and the data type of the result: O
Interval Value Expressions SQL/MX Language Elements • If you subtract a datetime value from another datetime value, and you specify the interval qualifier, you must allow for the maximum number of digits in the result for the precision. For example: (CURRENT_TIMESTAMP - ship_timestamp) DAY(4) TO SECOND(6) • If you are updating a value that is the result of adding or subtracting two interval values, an SQL error occurs if the source value does not fit into the target column's range of interval fields.
Numeric Value Expressions SQL/MX Language Elements -----------1000 2000 2500 3000 4000 5000 --------------------1355 02:58:57.087086 1264 02:43:57.087086 1111 02:13:57.087086 1172 03:03:57.087086 1172 00:58:57.087086 1165 01:48:55.975986 --- 6 row(s) selected. Numeric Value Expressions Considerations for Numeric Value Expressions Examples of Numeric Value Expressions The operands of a numeric value expression can be combined in specific ways with arithmetic operators.
SQL/MX Language Elements • • • • Numeric Value Expressions Host variables of type NUMERIC, PIC S9()V9(), DECIMAL, SMALLINT, INTEGER, LARGEINT, FLOAT, REAL, and DOUBLE PRECISION Dynamic parameters Numeric value functions Aggregate functions, sequence functions, scalar subqueries, CASE expressions, or CAST expressions that return numeric values Considerations for Numeric Value Expressions Order of Evaluation 1. 2. 3. 4. 5.
SQL/MX Language Elements Numeric Value Expressions The maximum precision for exact numeric data types is 18 digits. The maximum precision for the REAL data type is approximately 7 decimal digits, and the maximum precision for the DOUBLE PRECISION data type is approximately 16 digits.
Rowset Expressions SQL/MX Language Elements Examples of Numeric Value Expressions These are examples of numeric value expressions: -57 Numeric literal. salary * 1.10 The product of the values in the SALARY column and a numeric literal. unit_price * qty_ordered The product of the values in the UNIT_PRICE and QTY_ORDERED columns. 12 * (7 - 4) An expression whose operands are numeric literals. COUNT (DISTINCT city) Function applied to the values in a column.
Identifiers SQL/MX Language Elements Identifiers SQL/MP Considerations for Identifiers Examples of Identifiers SQL identifiers are names used to identify tables, views, columns, and other SQL entities. The two types of identifiers are regular and delimited. A delimited identifier is enclosed in double quotes ("). An identifier of either type can contain up to 128 characters.
SQL/MP Considerations for Identifiers SQL/MX Language Elements your catalogs and the name ZONE for a schema within that catalog. You can pass these delimited identifier names as command-line arguments to an OSS hosted preprocessor invocation by using an escape character for their quotes. mxsqlco prog.cob -g moduleSchema="\"TIME\".\"ZONE\"" Suppose that prog.cob has this module directive: EXEC SQL MODULE progmod END-EXEC.
SQL/MX Language Elements Examples of Identifiers "1995 SALES" "CUSTOMER-BILLING-INFORMATION" "%&*()" Because delimited identifiers are case-sensitive, NonStop SQL/MX treats the identifier "mytable" as different from the identifiers "MYTABLE" or "MyTable". Trailing spaces in a delimited identifier are truncated. For example, "mytable " is equivalent to "mytable". You can use reserved words as delimited identifiers.
SQL/MX Language Elements Indexes Indexes An index is an ordered set of pointers to rows of a table. Each index is based on the values in one or more columns. An index is stored in a key-sequenced file. There is always a one-to-one correspondence between index rows and base table rows.
Keys SQL/MX Language Elements Keys NonStop SQL/MX supports these types of keys: Clustering Keys First (Partition) Keys Index Keys Primary Keys SYSKEYs Clustering Keys NonStop SQL/MX organizes records of a table or index by using a b-tree based on the “clustering key”. Values of the clustering key act as logical row-ids. The set of columns that make up the clustering key must guarantee uniqueness.
First (Partition) Keys SQL/MX Language Elements Table 6-1. Construction of the Clustering Key (page 2 of 2) STORE BY key column list Primary Key Specified DROPPABLE Attribute Clustering Key No Not applicable Key column list + SYSKEY Yes DROPPABLE Key column list + SYSKEY. Primary key enforced by unique index. Yes NOT DROPPABLE If STORE BY column list matches the primary key column list, NonStop SQL/MX uses the STORE BY column list.
SQL/MX Language Elements Index Keys Partitioning character columns must derive from the ISO88591 character set and cannot be floating-point data columns. Index Keys An index is stored in a key-sequenced file. There is always a one-to-one correspondence between index rows and base table rows.
SQL/MX Language Elements Primary Keys For a unique index, the clustering key of the index is composed of the first of these items. The clustering key of the index cannot exceed 255 bytes, but the entire row (including the clustering key of the index) can contain up to 510 bytes. For a nonunique index, the clustering key of the index is composed of both items. The clustering key cannot exceed 255 bytes. Because the clustering key includes all the columns in the table, each row is also limited to 255 bytes.
Literals SQL/MX Language Elements Literals A literal is a constant you can use in an expression, in a statement, or as a parameter value. Literals are stored in columns of tables according to how you specify the column definitions in a CREATE TABLE statement. An SQL literal can be one of these data types: Character String Literals on page 6-62 A series of characters enclosed in single quotes.
SQL/MX Language Elements Character String Literals You can specify string literals using hexadecimal code values in DML statements. [_character-set | N] X'hex-code-value... ' | [_character-set | N] X'[space…]hex-code-value[[space…] hex-code-value...][space…]' _character-set specifies the character set ISO88591 or UCS2. If you omit the character set specification, the default is whatever character set default you set when you installed NonStop SQL/MX. See Character Sets on page 6-3.
SQL/MX Language Elements Character String Literals When specifying string literals: • Do not put a space between the character set qualifier (for example, _KANJI) and the character string literal (for example, 'abcd'). If you use this character string literal in a statement, NonStop SQL/MX returns an error: _KANJI 'abcd' • • • • To specify a single quotation mark within a string literal, use two consecutive single quotation marks.
Datetime 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/MP Tables on page 6-23. Inserting Into or Updating SQL/MP Kanji Columns NonStop SQL/MX supports inserting into or updating columns with the KANJI or KSC data type in SQL/MP tables. The only restriction is that the data being written to the table contains an even number of bytes.
Datetime Literals SQL/MX Language Elements Examples of Datetime Literals A datetime literal is a DATE, TIME, or TIMESTAMP constant you can use in an expression, in a statement, or as a parameter value. Datetime literals have the same range of valid values as the corresponding datetime data types.
Datetime Literals SQL/MX Language Elements 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.msssss' The literal is followed by the qualifier, consisting of an optional start field and an end field.
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.
Interval Literals SQL/MX Language Elements SQL/MP Start Field SQL/MP End Field Equivalent SQL/MX Type SECOND FRACTION(y) SECOND(2,y) 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.
SQL/MX Language Elements Numeric Literals Numeric Literals A numeric literal represents a numeric value. Numeric literals can be represented as an exact numeric literal (without an exponent) or as an approximate numeric literal by using scientific notation (with an exponent). exact-numeric-literal is: [+|-]unsigned-integer[.[unsigned-integer]] | [+|-].
Numeric Literals SQL/MX Language Elements Examples of Numeric Literals • These are all numeric literals, along with their display format: Literal Display Format in MXCI 477 477 580.45 580.45 +005 5 -.3175 -.3175 1300000000 1300000000 99. 99 -0.123456789012345678 -.123456789012345678 99E-2 9.9000000E-001 12.3e+5 1.
SQL/MX Language Elements MXCI Parameters MXCI Parameters Examples of MXCI Parameters Typically, you use parameters (both within MXCI and in embedded SQL) so that you can prepare an SQL statement and then execute it later, providing different values for each execution. Within an MXCI file to be obeyed, you can also use parameters for values so that an SQL statement within the file can execute with different values.
Working With MXCI Parameters SQL/MX Language Elements • • If the parameter is character and the target column has datetime data type, you must CAST the parameter to have the same data type as the target column. If the parameter is character or numeric and the target column has INTERVAL data type, you must CAST the parameter to have the INTERVAL data type. Working With MXCI Parameters Use these statements with MXCI parameters: SET PARAM Command on page 4-47 Sets the value of an MXCI-named parameter.
SQL/MX Language Elements Examples of MXCI Parameters Examples of MXCI Parameters • The PROJECT table has a START_DATE column. This UPDATE statement uses the character literal in the ?STARTDAY parameter to set the START_DATE column value in the PROJECT table: SET PARAM ?STARTDAY '1999-11-15'; UPDATE persnl.project SET start_date = CAST(?STARTDAY AS DATE); • Suppose that the PROJECT table has an EST_COMPLETE column whose default value is INTERVAL '30' DAY.
SQL/MX Language Elements Null Null Null is a special symbol, independent of data type, that represents an unknown. The SQL/MX keyword NULL represents null. Null indicates that an item has no value. For sorting purposes, null is greater than all other values. You cannot store null in a column by using either INSERT or UPDATE, unless the column allows null. A column that allows null can be null at any row position. A nullable column has extra bytes associated with it in each row.
SQL/MX Language Elements Defining Columns That Allow or Prohibit Null Defining Columns That Allow or Prohibit Null The CREATE TABLE and ALTER TABLE statements define the attributes for columns within tables. A column allows nulls unless the column definition includes the NOT NULL clause or the column is part of the primary key of the table.
Defining Columns That Allow or Prohibit Null SQL/MX Language Elements Null in DISTINCT, GROUP BY, and ORDER BY Clauses In evaluating the DISTINCT, GROUP BY, and ORDER BY clauses, NonStop SQL/MX considers all nulls to be equal. Additional considerations for these clauses are: DISTINCT Nulls are considered duplicates; therefore, a result has at most one null. GROUP BY The result has at most one null group. ORDER BY Nulls are considered greater than nonnull values.
SQL/MX Language Elements Partitions Partitions Typically, there is a one-to-one correspondence between a table definition and a physical file. However, large tables, or tables with special performance requirements, might require partitioning into multiple physical files. A partition is the part of a table or index that resides on a single disk volume. Each table or index consists of at least one partition. A nonpartitioned table or index consists of exactly one partition.
SQL/MX Language Elements SQL/MX Tables In this scenario, suppose that you have a database with ten 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-50. For more information on this feature, see Creating Partitions Automatically on page 2-90. 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 this 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.
Quantified Comparison Predicates 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 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 table-subquery provides the values for the comparison. The number of values returned by the row-value-constructor must be equal to the number of values specified by the table-subquery, and the data types of values returned by the row-valueconstructor must be comparable to the data types of values returned by the table-subquery. See Subquery on page 6-108.
Quantified Comparison Predicates SQL/MX Language Elements 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.10: SELECT empnum, first_name, last_name, salary FROM persnl.employee WHERE salary > ALL (SELECT salary FROM persnl.employee WHERE jobcode = 420); EMPNUM -----1 23 29 ...
Rowset Predicates SQL/MX Language Elements The inner query providing the comparison values yields these results: SELECT partnum FROM sales.odetail WHERE qty_ordered > 5; Part/Num -------2403 5100 5103 6301 6500 .... --- 60 row(s) selected. The SELECT statement using this inner query yields these results.
SQL/MX Language Elements Schemas Schemas The ANSI SQL:1999 schema name is an SQL identifier that is unique for a given ANSI catalog name. NonStop SQL/MX automatically qualifies a schema name with the current default catalog name unless you explicitly specify a catalog name with the schema name: catalog.schema The three-part logical name of the form catalog.schema.object is an ANSI name. The parts catalog and schema denote the ANSI-defined catalog and schema.
SQL/MX Language Elements Search Condition Search Condition A search condition is used to choose rows from tables or views, depending on the result of applying the condition to rows. The condition is a Boolean expression consisting of predicates combined together with OR, AND, and NOT operators.
SQL/MX Language Elements Considerations for Search Condition Considerations for Search Condition Order of Evaluation SQL evaluates search conditions in this order: 1. 2. 3. 4. Predicates within parentheses NOT AND OR Column References Within a search condition, a reference to a column refers to the value of that column in the row currently being evaluated by the search condition. Subqueries If a search condition includes a subquery and the subquery returns no values, the predicate evaluates to null.
Rowset Search Condition SQL/MX Language Elements • Select rows by using a search condition composed of three comparison predicates, two of which are joined by an OR operator (within parentheses), and where the result of the OR and the first comparison predicate are joined by an AND operator: SELECT partnum, S.suppnum, suppname FROM invent.supplier S, invent.partsupp PS WHERE S.suppnum = PS.suppnum AND (partnum < 3000 OR partnum = 7102); PARTNUM ------212 244 255 ...
SQL/MX Language Elements SQL/MP Aliases SQL/MP Aliases In product versions prior to SQL/MX Release 2.x, you referenced SQL/MP database objects using their Guardian physical names. In SQL/MX Release 2.x you can create SQL/MP aliases that map logical object names to physical Guardian locations. SQL/MP aliases are simulated ANSI names that represent the underlying Guardian physical names of SQL/MP objects. True ANSI names do not exist for SQL/MP objects.
SQL/MX Language Elements Subquery When you use rowset-search-condition in a subquery, all the individual search-conditions in the rowset are applied successively. The result table is the union of all the rows selected by these successive applications. Using rowsets in a subquery implies that the entire rowset in the subquery is evaluated and the result table passed on the outer query.
SQL/MX Language Elements Tables A subquery within the WHERE clause of another subquery is at a different level, however, so this query has two levels of nesting: SELECT * FROM TABLE1 WHERE A = (SELECT P FROM TABLE2 WHERE Q = (SELECT X FROM TABLE3 WHERE Y = 2)) Correlated Subqueries When Providing Comparison Values In the search condition of a subquery, when you refer to columns of any table or view defined in an outer query, the reference is called an outer reference.
Triggers SQL/MX Language Elements An SQL/MX table is described in an SQL/MX schema and stored in a physical file in the Guardian environment. An SQL/MX table name can be a fully qualified ANSI name of the form catalog-name.schema-name.object-name. Base Tables and Views In some descriptions of SQL, tables created with a CREATE TABLE statement are referred to as base tables to distinguish them from views, which are referred to as logical tables.
SQL/MX Views SQL/MX Language Elements An view is a logical table created with the CREATE VIEW statement and derived by projecting a subset of columns, restricting a subset of rows, or both, from one or more base tables or other views. You cannot create a view that references both an SQL/MP table and an SQL/MX table. SQL/MX Views The distinction between protection and shorthand views does not exist for SQL/MX views. To create a view, you must have SELECT privileges for the objects underlying the view.
7 SQL/MX Clauses Clauses are used by SQL/MX statements to specify default values, ways to sample or sort data, how to store physical data, how to partition file, and other details. This section describes these clauses for SQL/MX objects: DEFAULT Clause on page 7-2 Specifies a default value for a column being created. PARTITION Clause on page 7-5 Creates one or more secondary partitions for a table or index.
DEFAULT Clause SQL/MX Clauses DEFAULT Clause Considerations for DEFAULT Examples of DEFAULT The DEFAULT option of the CREATE TABLE or ALTER TABLE table-name ADD COLUMN statement specifies a default value for a column being created. The default value is used when a row is inserted in the table without a value for the column.
Considerations for DEFAULT SQL/MX Clauses DEFAULT CURRENT_TIME specifies the default value for the column as the value returned by the CURRENT_TIME function at the time of the operation that assigns a value to the column. This default can occur only with a column whose data type is TIME. DEFAULT CURRENT_TIMESTAMP specifies the default value for the column as the value returned by the CURRENT_TIMESTAMP function at the time of the operation that assigns a value to the column.
Examples of DEFAULT SQL/MX Clauses Examples of DEFAULT • This example uses DEFAULT clauses on CREATE TABLE to specify default column values: CREATE TABLE items ( item_id CHAR(12) NO DEFAULT ,description CHAR(50) DEFAULT NULL ,num_on_hand INTEGER DEFAULT 0 NOT NULL ,PRIMARY KEY (item_id) NOT DROPPABLE ); • This example uses DEFAULT clauses on CREATE TABLE to specify default column values: CREATE TABLE persnl.
PARTITION Clause SQL/MX Clauses PARTITION Clause Considerations for PARTITION Examples of Partitions The PARTITION clause of the CREATE INDEX and CREATE TABLE statements creates one or more secondary partitions for a table or index. NonStop SQL/MX supports range partitioning and hash partitioning. For information, see Partitions on page 6-82. 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 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. See the STORE BY Clause on page 7-22.
SAMPLE Clause SQL/MX Clauses SAMPLE Clause Considerations for SAMPLE Examples of SAMPLE The SAMPLE clause of the SELECT statement specifies the sampling method used to select a subset of the intermediate result table of a SELECT statement. The intermediate result table consists of the rows returned by a WHERE clause or, if there is no WHERE clause, the FROM clause. See SELECT Statement on page 2-178. SAMPLE is an SQL/MX extension.
SAMPLE Clause SQL/MX Clauses You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table. Each row is picked with a probability of r%, where r is the sample size in PERCENT. Therefore, the actual size of the resulting sample is approximately r% of N. The number of rows picked follows a binomial distribution with mean equal to r * N/100.
Considerations for SAMPLE SQL/MX Clauses You can determine the actual size of the sample. Suppose that there are N rows in the intermediate result table. If the size s of the sample is specified as a number of rows, the actual size of the resulting sample is the minimum of s and N. PERIODIC rows-size EVERY number-rows ROWS [SORT BY colname [ASC[ENDING] | DESC[ENDING]] [,colname [ASC[ENDING] | DESC[ENDING]]]...] directs NonStop SQL/MX to choose the first rows from each block (or period) of contiguous rows.
Examples of SAMPLE SQL/MX Clauses Cluster sampling can be done only on a base table, not on intermediate results. Cluster sampling is generally faster than sampling individual rows because fewer blocks are read from disk. In random row and periodic sampling, the entire result table being sampled is read, and each row in the table is processed. In cluster sampling, only the disk blocks that are part of the result table are read and processed.
Examples of SAMPLE SQL/MX Clauses 27000.12 136000.00 37000.40 ... --- 50 row(s) selected. • Return the SALARY of 50 sales people. In this case, the table is clustered on EMPID. If the optimizer chooses a plan to access rows using the primary access path, the result consists of salaries of the 50 sales people with the smallest employee identifiers. SELECT salary FROM salesperson SAMPLE FIRST 50 ROWS; SALARY ----------175500.00 137000.10 136000.00 138000.40 75000.00 90000.00 ... --- 50 row(s) selected.
Examples of SAMPLE SQL/MX Clauses • Compute the average salary of a random 10 percent of the sales people. You will get a different result each time you run this query because it is based on a random sample. SELECT AVG(salary) FROM salesperson SAMPLE RANDOM 10 PERCENT; (EXPR) -------------------61928.57 --- 1 row(s) selected. • Compute the average salary of a random 10 percent of the sales people using cluster sampling where each cluster is 4 blocks.
Examples of SAMPLE SQL/MX Clauses • Compute the average salary of a random 10 percent of sales people belonging to the CORPORATE department. The sample is taken from the join of the SALESPERSON and DEPARTMENT tables. You will get a different result each time you run this query because it is based on a random sample. SELECT AVG(salary) FROM salesperson S, department D WHERE S.DNUM = D.DNUM AND D.NAME = 'CORPORATE' SAMPLE RANDOM 10 PERCENT; (EXPR) --------------------106250.000 --- 1 row(s) selected.
Examples of SAMPLE SQL/MX Clauses • In this example, both the tables are sampled first and then joined. This query computes the average salary and the average sale amount generated from a random 10 percent of all the sales people and 20 percent of all the sales transactions. SELECT AVG(salary), AVG(amount) FROM ( SELECT salary, empid FROM salesperson SAMPLE RANDOM 10 PERCENT ) AS S, ( SELECT amount, empid FROM sales SAMPLE RANDOM 20 PERCENT ) AS T WHERE S.empid = T.empid; (EXPR) --------45000.
Examples of SAMPLE SQL/MX Clauses • The BALANCE option enables stratified sampling. Retrieve the age and salary of 1000 sales people such that 50 percent of the result are male and 50 percent female. SELECT age, sex, salary FROM salesperson SAMPLE FIRST BALANCE WHEN sex = 'male' THEN 15 ROWS WHEN sex = 'female' THEN 15 ROWS END ORDER BY age; AGE SEX SALARY ----------22 22 22 22 ... -----male male female male ... ----------28000.00 90000.00 136000.00 37000.40 ... --- 30 row(s) selected.
Examples of SAMPLE SQL/MX Clauses • This query shows an example of stratified sampling where the conditions are not mutually exclusive: SELECT * FROM sales SAMPLE RANDOM BALANCE WHEN amount > 10000 THEN 100 PERCENT WHEN product = 'PCGOLD, 30MB' THEN 25 PERCENT WHEN region = 'W' THEN 40 PERCENT ELSE 10 PERCENT END; EMPID ----1 23 29 32 39 75 ... PRODUCT -------------------PCGOLD, 30MB PCDIAMOND, 60MB GRAPHICPRINTER, M1 GRAPHICPRINTER, M2 GRAPHICPRINTER, M3 LASERPRINTER, X1 ... REGION -----E W N S S W ..
SEQUENCE BY Clause SQL/MX Clauses SEQUENCE BY Clause Considerations for SEQUENCE BY Examples of SEQUENCE BY The SEQUENCE BY clause of the SELECT statement specifies the order in which to sort the rows of the intermediate result table for calculating sequence functions. This option is used for processing time-sequenced rows in data mining applications. See SELECT Statement on page 2-178. 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—523725-004 7- 34
8 SQL/MX File Attributes The ATTRIBUTE file option describes physical characteristics of files (including files that contain tables, indexes, or partitions) that can affect the performance of applications that use the files. File attributes are set when a file (or an object that resides in a file) is created. If you do not specify ATTRIBUTE values in the statement that creates an object (such as CREATE TABLE or CREATE INDEX), NonStop SQL/MX uses default values for file attributes.
ALLOCATE/DEALLOCATE SQL/MX File Attributes ALLOCATE/DEALLOCATE ALLOCATE is a Guardian file attribute that reserves disk space for a file. DEALLOCATE frees disk space previously reserved for the file that does not contain data. ALLOCATE applies to tables and indexes. Allocate disk space in advance to ensure that space is available when needed and to avoid processing errors caused by full or fragmented disks during normal allocation-on-demand.
AUDITCOMPRESS SQL/MX File Attributes AUDITCOMPRESS The AUDITCOMPRESS file attribute controls whether TMF audit records for the file are compressed. Compressed audit records omit unchanged columns from the before and after images of updated rows. Uncompressed audit records allow you to read complete rows in the audit trail but require more space. You set the AUDITCOMPRESS attribute for a table with CREATE TABLE or ALTER TABLE.
BLOCKSIZE SQL/MX File Attributes BLOCKSIZE The BLOCKSIZE file attribute specifies the number of bytes in a block. Set the BLOCKSIZE attribute for a table or index with CREATE TABLE or CREATE INDEX statements. You cannot change the BLOCKSIZE attribute of an existing table or index. BLOCKSIZE number-bytes The default is BLOCKSIZE 4096. number-bytes is an integer that specifies the number of bytes in a block. Block size must be 4096 bytes. If you specify a different block size, an error is returned.
CLEARONPURGE SQL/MX File Attributes CLEARONPURGE The CLEARONPURGE file attribute controls erasure of data from the disk when a file is deleted. You set the CLEARONPURGE attribute for an SQL/MX table with CREATE TABLE or ALTER TABLE. You set the CLEARONPURGE attribute for an SQL/MX index with CREATE INDEX or ALTER INDEX. CLEARONPURGE | NO CLEARONPURGE The table default is NO CLEARONPURGE. The index default for the CLEARONPURGE attribute is the table value at index creation.
EXTENT SQL/MX File Attributes EXTENT EXTENT is a Guardian file attribute that sets the size of the extents (units of contiguous disk space) that will be allocated for a file or partition of a file. EXTENT applies to tables and indexes and is set when a file or partition is created. EXTENT ext-size | (pri-ext-size [, sec-ext-size ]) ext-size, pri-ext-size, sec-ext-size is: integer [PAGE[S] ] The default is 16 pages for the primary extent and 64 pages for each secondary extent.
Considerations for EXTENT 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 SQL/MX File Attributes MAXEXTENTS MAXEXTENTS is a file attribute that specifies the maximum number of extents that can be allocated 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. You set the attribute for an index with CREATE INDEX or ALTER INDEX.
9 SQL/MX Functions and Expressions This section describes the syntax and semantics of specific functions and expressions that you can use in NonStop SQL/MX statements. The functions and expressions are categorized according to their functionality.
Character String Functions SQL/MX Functions and Expressions Note that columns and expressions can be arguments of an aggregate function. The expressions cannot contain aggregate functions or subqueries. An aggregate function can accept an argument specified as DISTINCT, which eliminates duplicate values before the aggregate function is applied. Only one DISTINCT aggregate function is allowed at each level of a SELECT statement.
Character String Functions SQL/MX Functions and Expressions LPAD Function on page 9-79 Replaces the leftmost specified number of characters in a character expression with a padding character. LTRIM Function on page 9-80 Removes leading spaces from a character string. OCTET_LENGTH Function on page 9-101 Returns the length of a character string in bytes. POSITION Function on page 9-105 Returns the position of a specified substring within a character string. You can also use LOCATE.
Datetime Functions SQL/MX Functions and Expressions Datetime Functions These functions use either a datetime value expression as an argument or return a result of datetime data type: CONVERTTIMESTAMP Function on page 9-32 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-85 Returns an integer value in the range 1 through 12 that represents the corresponding month of the year. MONTHNAME Function on page 9-86 Returns a character literal that is the name of the month of the year (January, February, and so on). QUARTER Function on page 9-108 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-55 Returns the exponential value (to the base e) of a numeric value expression. FLOOR Function on page 9-63 Returns the largest integer less than or equal to a numeric value expression. LOG Function on page 9-72 Returns the natural logarithm of a numeric value expression. LOG10 Function on page 9-73 Returns the base 10 logarithm of a numeric value expression.
Sequence Functions SQL/MX Functions and Expressions Sequence Functions Sequence functions operate on ordered rows of the intermediate result table of a SELECT statement that includes a SEQUENCE BY clause. Sequence functions are categorized generally as difference, moving, offset, or running. Difference sequence functions: DIFF1 Function on page 9-49 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-136 Returns the sum of nonnull values of a column expression up to and including the current row. RUNNINGVARIANCE Function on page 9-138 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-67 Returns the last nonnull value for the specified column expression.
SQL/MX Functions and Expressions Table-Valued Stored Functions Table-Valued Stored Functions Table-valued stored functions are system-defined functions that generate a result table. Use these functions anywhere a table reference can be used in a SELECT statement or the SELECT form of a subquery: EXPLAIN Function on page 9-55 Builds a result table that describes the access plan of a DML statement, which can then be queried by a SELECT statement.
SQL/MX Functions and Expressions ABS Function ABS Function The ABS function returns the absolute value of a numeric value expression. ABS is an SQL/MX extension. ABS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the ABS function. The result is returned as an unsigned numeric value if the precision of the argument is less than 10 or as a LARGEINT if the precision of the argument is greater than or equal to 10.
SQL/MX Functions and Expressions ACOS Function ACOS Function The ACOS function returns the arccosine of a numeric value expression as an angle expressed in radians. ACOS is an SQL/MX extension. ACOS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the ACOS function. The range for the value of the argument is from -1 to +1. See Numeric Value Expressions on page 6-50. Examples of ACOS • This function returns the value 3.
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-39.
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-50. 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-50. Examples of ATAN • This function returns the value 8.72766423249958400E-001 or approximately 0.
SQL/MX Functions and Expressions ATAN2 Function ATAN2 Function The ATAN2 function returns the arctangent of the x and y coordinates, specified by two numeric value expressions, as an angle expressed in radians. ATAN2 is an SQL/MX extension. ATAN2 (numeric-expression-x,numeric-expression-y) numeric-expression-x,numeric-expression-y are SQL numeric value expressions that specify the value for the x and y coordinate arguments of the ATAN2 function. See Numeric Value Expressions on page 6-50.
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 the result-expressions must have comparable data types, and at least one of the result-expressions must return nonnull.
Examples of CASE SQL/MX Functions and Expressions For example, if result-expression-1 and result-expression-2 have data type NUMERIC(5) and result-expression-3 has data type NUMERIC(8,5), the result data type is NUMERIC(10,5). If any data type of the result expressions is approximate numeric, the result data type is approximate numeric with precision equal to the maximum of the precisions of the result expressions.
Examples of CASE SQL/MX Functions and Expressions HALL ... KATHRYN SYSTEM ANALYST --- 62 row(s) selected. • Use a searched CASE to return LAST_NAME, FIRST_NAME and a value based on SALARY that depends on the value of DEPTNUM: SELECT last_name, first_name, deptnum, CASE WHEN deptnum = 9000 THEN salary * 1.10 WHEN deptnum = 1000 THEN salary * 1.12 ELSE salary END FROM persnl.employee; LAST_NAME FIRST_NAME ---------------- -----------GREEN ROGER HOWARD JERRY RAYMOND JANE ... --- 62 row(s) selected.
SQL/MX Functions and Expressions CAST Expression CAST Expression Considerations for CAST Valid Conversions for CAST Examples of CAST The CAST expression converts data to the data type you specify. CAST ({expression | NULL} AS data-type) expression | NULL specifies the operand to convert to the data type data-type. If the operand is an expression, then data-type depends on the data type of expression and follows the rules outlined in Valid Conversions for CAST.
Examples of CAST SQL/MX Functions and Expressions • • • • • A date value to a character string or to a TIMESTAMP (NonStop SQL/MX fills in the time part with 00:00:00.00). A time value to a character string or to a TIMESTAMP (NonStop SQL/MX fills in the date part with the current date). A timestamp value to a character string, a DATE, a TIME, or another TIMESTAMP with different fractional seconds precision.
SQL/MX Functions and Expressions CEILING Function CEILING Function The CEILING function returns the smallest integer, represented as a FLOAT data type, greater than or equal to a numeric value expression. CEILING is an SQL/MX extension. CEILING (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the CEILING function. See Numeric Value Expressions on page 6-50. Examples of CEILING • This function returns the integer value 3.
CHAR Function SQL/MX Functions and Expressions CHAR Function The CHAR function returns the character that has the specified code value, which must be of exact numeric with scale 0. CHAR is an SQL/MX extension. CHAR(code-value, [,char-set-name]) code-value is a valid code value in the character set in use. char-set-name can be ISO88591, KANJI, KSC5601, or UCS2. The returned character will be associated with the character set specified by char-set-name with the DEFAULT collation. The default is ISO88591.
SQL/MX Functions and Expressions CHAR_LENGTH Function CHAR_LENGTH Function Considerations for CHAR_LENGTH SQL/MP Considerations for CHAR_LENGTH Examples of CHAR_LENGTH The CHAR_LENGTH function returns the number of characters in a string. You can also use CHARACTER_LENGTH. CHAR[ACTER]_LENGTH (string-value-expression) string-value-expression specifies the string value expression for which to return the length in characters.
Examples of CHAR_LENGTH SQL/MX Functions and Expressions This SELECT statement returns the same values for the character length and the octet length of the ISO88591 column. One character of an ISO88591 character set is equivalent to one byte. SELECT CHAR_LENGTH(col_char) AS CHARLENGTH_CHAR, OCTET_LENGTH(col_char) AS OCTETLENGTH_CHAR FROM tab; CHARLENGTH_CHAR --------------- OCTETLENGTH_CHAR ---------------- 10 10 --- 1 row(s) selected.
SQL/MX Functions and Expressions • Examples of CHAR_LENGTH The PROJDESC column in the PROJECT table has data type VARCHAR(18). This function returns the actual length of the column value—not 18 for shorter strings— because it is a VARCHAR value: SELECT CHAR_LENGTH (projdesc) FROM persnl.project; (EXPR) ---------14 13 13 17 9 9 --- 6 row(s) selected.
SQL/MX Functions and Expressions CODE_VALUE Function CODE_VALUE Function The CODE_VALUE function returns an unsigned integer (INTEGER UNSIGNED) that is the code point of the first character in a character value expression that can be associated with any character sets allowed. CODE_VALUE is an SQL/MX extension. CODE_VALUE(character-value-expression) character-value-expression is a character string.
SQL/MX Functions and Expressions CONCAT Function CONCAT Function The CONCAT function returns the concatenation of two character value expressions as a character string value. You can also use the concatenation operator (||). CONCAT is an SQL/MX extension. CONCAT (character-expr-1, character-expr-2) character-expr-1, character-expr-2 are SQL character value expressions (of data type CHAR or VARCHAR) that specify two strings of characters.
SQL/MX Functions and Expressions Examples of CONCAT To specify the type assignment of the parameter, use the CAST expression on the parameter as: CAST(?p AS CHAR(7)) || '2002' In this example, the parameter is not truncated, and the result of the concatenation is 5 March 2002. Examples of CONCAT Suppose that the LOGFILE table has been created in NonStop SQL/MP as: CREATE TABLE $sys.stats.
SQL/MX Functions and Expressions CONVERTTIMESTAMP Function CONVERTTIMESTAMP Function The CONVERTTIMESTAMP function converts a Julian timestamp to a value with data type TIMESTAMP. CONVERTTIMESTAMP is an SQL/MX extension. CONVERTTIMESTAMP (julian-timestamp) julian-timestamp is an expression that evaluates to a Julian timestamp, which is a LARGEINT value.
SQL/MX Functions and Expressions COS Function COS Function The COS function returns the cosine of a numeric value expression, where the expression is an angle expressed in radians. COS is an SQL/MX extension. COS (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the COS function. See Numeric Value Expressions on page 6-50. Examples of COS • This function returns the value 9.39680940386503936E-001, or approximately 0.
SQL/MX Functions and Expressions COSH Function COSH Function The COSH function returns the hyperbolic cosine of a numeric value expression, where the expression is an angle expressed in radians. COSH is an SQL/MX extension. COSH (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the COSH function. See Numeric Value Expressions on page 6-50. Examples of COSH • This function returns the value 1.
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 CURRENT_USER Function CURRENT_USER Function The CURRENT_USER function returns the current Guardian user ID as variable-length character data in the form group.name. CURRENT_USER The CURRENT_USER function is equivalent to the SESSION_USER Function on page 9-141 and the USER Function on page 9-172. Examples of CURRENT_USER • Retrieve the user name value for the current user: SELECT CURRENT_USER FROM logfile; (EXPR) ----------------------DCS.TSHAW ...
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-40.
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-40.
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-40.
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-40.
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-50. 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-50. Examples of EXP • This function returns the value 3.49034295746184208E+000, or approximately 3.4903: EXP (1.
SQL/MX Functions and Expressions Considerations for EXPLAIN attributes. See the MODULE Directive on page 3-71. For information on module management attributes, see the SQL/MX Programming Manual for C and COBOL or the SQL/MX Programming Manual for Java. The module name is enclosed in single quotes and is case-sensitive. If a module name is uppercase, the value you specify within single quotes must be uppercase. For example: 'MYCAT.MYSCH.MYPROG' MXCI NULL explains statements prepared in the MXCI session.
Considerations for EXPLAIN SQL/MX Functions and Expressions Using EXPLAIN and DISPLAY_EXPLAIN The result of the EXPLAIN function for a specific DML statement can be generated either by using the EXPLAIN function or the DISPLAY_EXPLAIN command. Use the EXPLAIN function only for prepared statements. The DISPLAY_EXPLAIN command displays all the columns of the result table of the EXPLAIN function.
Considerations for EXPLAIN SQL/MX Functions and Expressions Column Name Data Type Description OPERATOR CHAR(30) Current node type; one of these: Operator CALL CURSOR_DELETE CURSOR_UPDATE ESP_EXCHANGE EXPLAIN EXPR FILE_SCAN FILE_SCAN_UNIQUE HASH_GROUPBY HASH_PARTIAL_GR..._LEAF HASH_PARTIAL_GR...
Examples of EXPLAIN SQL/MX Functions and Expressions Column Name Data Type Description SUBSET_DELETE SUBSET_UPDATE TRANSPOSE TUPLE_FLOW TUPLELIST UNIQUE_DELETE UNIQUE_UPDATE UNPACK VALUES DAM subset DAM subset Data mining Join Tuple DAM unique DAM unique Rowset Tuple LEFT_CHILD_ SEQ_NUM INT Sequence number for the first child operator of the current node (or operator); null if node has no child operators.
Examples of EXPLAIN SQL/MX Functions and Expressions The DISPLAY_EXPLAIN command display for the prepared statement named FINDEMP is identical to the DISPLAY_EXPLAIN command display shown under DISPLAY_EXPLAIN Command on page 4-13.
Examples of EXPLAIN SQL/MX Functions and Expressions --- 7 row(s) selected. The second plan is forced by this CONTROL QUERY SHAPE statement: control query shape nested_join( partition_access(scan), partition_access(scan('JOB'))); PREPARE FINDEMP2 FROM SELECT last_name, first_name, deptnum, employee.jobcode, jobdesc FROM employee, job WHERE deptnum = 3100 AND employee.jobcode = job.
SQL/MX Functions and Expressions EXTRACT Function EXTRACT Function The EXTRACT function extracts a datetime field from a datetime or interval value expression. It returns an exact numeric value. EXTRACT (datetime-field FROM extract-source) datetime-field is: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND extract-source is: datetime-expression | interval-expression See Datetime Value Expressions on page 6-40 and Interval Value Expressions on page 6-45.
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-50. Examples of FLOOR • This function returns the integer value 2.
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-40.
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-39.
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-50. Examples of LOG • This function returns the value 6.93147180559945504E-001, or approximately 0.
SQL/MX Functions and Expressions LOG10 Function LOG10 Function The LOG10 function returns the base 10 logarithm of a numeric value expression. LOG10 is an SQL/MX extension. LOG10 (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the LOG10 function. The value of the argument must be greater than zero. See Numeric Value Expressions on page 6-50. Examples of LOG10 • This function returns the value 1.
LOWER Function SQL/MX Functions and Expressions LOWER Function Considerations for LOWER Examples of LOWER The LOWER function downshifts characters. LOWER can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the LOWER function is equal to the result returned by the LCASE function.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Considerations for LOWER SQL/MX Functions and Expressions Table 9-1.
Examples of LOWER SQL/MX Functions and Expressions Examples of LOWER • Suppose that your CUSTOMER table includes an entry for Hotel Oregon. Select the column CUSTNAME and return the result in uppercase and lowercase letters by using the UPPER and LOWER functions: SELECT custname,UPPER(custname),LOWER(custname) FROM sales.customer; (EXPR) ----------------... Hotel Oregon (EXPR) ------------------... HOTEL OREGON (EXPR) -----------------... hotel oregon --- 17 row(s) selected.
SQL/MX Functions and Expressions LPAD Function LPAD Function The LPAD function replaces the leftmost specified number of characters in a character expression with a padding character. LPAD is an SQL/MX extension. LPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-39. count specifies the number of characters to be replaced in character-expr.
LTRIM Function SQL/MX Functions and Expressions LTRIM Function The LTRIM function removes leading spaces from a character string. LTRIM is an SQL/MX extension. LTRIM (character-expression) character-expression is an SQL character value expression and specifies the string from which to trim leading spaces. See Character Value Expressions on page 6-39.
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-40.
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-40.
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-40.
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-39.
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 funcNonStop tion searches for a given substring in a character string. If the substring is found, 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.
SQL/MX Functions and Expressions POWER Function POWER Function The POWER function returns the value of a numeric value expression raised to the power of an integer value expression. You can also use the exponential operator **. POWER is an SQL/MX extension. POWER (numeric-expression-1,numeric-expression-2) numeric-expression-1,numeric-expression-2 are SQL numeric value expressions that specify the values for the base and exponent arguments of the POWER function. See Numeric Value Expressions on page 6-50.
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-40.
QUERYCACHE Function SQL/MX Functions and Expressions QUERYCACHE Function Considerations for QUERYCACHE Examples of QUERYCACHE The query plan cache automatically collects statistics regarding its use. When invoked, the QUERYCACHE table-valued stored function collects and returns the current state of these statistics in a single row table. The statistics are reinitialized when an mxcmp session is started and each mxcmp session maintains an independent set of statistics.
Considerations for QUERYCACHE SQL/MX Functions and Expressions Column Name Data Type Description MAX_NUM_VICTIMS INT Maximum number of plans that can be removed from the cache to make room for a new entry. NUM_ENTRIES INT Total number of entries in the cache. NUM_PINNED INT Total number of pinned entries. NUM_COMPILES INT Total number of complete compile requests (excludes DESCRIBE and SHOWSHAPE commands). NUM_RECOMPILES INT Total number of recompilations.
Examples of QUERYCACHE SQL/MX Functions and Expressions Column Name Data Type Description NUM_DISPLACED INT Number of entries removed from the cache to make room for new entries or as a consequence of a resizing of the cache or a recompilation. OPTIMIZATION_LEVEL CHAR(10) Indicates the current level of query optimization. Can be 0, 1, 2, 3, 4, or 5. PINNING_STATE CHAR(4) Current state of pinning, ON or OFF.
SQL/MX Functions and Expressions • Examples of QUERYCACHE Display selected query plan caching statistics from the same query: SELECT NUM_RETRIES, OPTIMIZATION_LEVEL FROM TABLE (QUERYCACHE ()); NUM_RETRIES OPTIMIZATION_LEVEL ---------- -----------------0 3 --- 1 row(s) selected.
SQL/MX Functions and Expressions QUERYCACHEENTRIES Function QUERYCACHEENTRIES Function The query plan cache automatically collects statistics on each entry of the cache. When invoked, the QUERYCACHEENTRIES table-valued function collects and returns these statistics in a table with one row for each entry of the cache. The statistics are reinitialized when an mxcmp session is started. Each mxcmp session maintains an independent set of statistics. The QUERYCACHEENTRIES function is an SQL/MX extension.
Considerations for QUERYCACHEENTRIES SQL/MX Functions and Expressions Result of the QUERYCACHEENTRIES Function The result table of the QUERYCACHEENTRIES function describes the query plan caching information for each entry in the query plan cache. For 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. Entry number 0 is the most recently used entry.
Considerations for QUERYCACHEENTRIES SQL/MX Functions and Expressions Column Name Data Type Description SHAPE CHAR(1024) Required CONTROL QUERY SHAPE of the query associated with this entry. Blank if no required shape. ISOLATION_LEVEL CHAR(20) Transaction isolation level for this entry. Can be READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE, or NOT SPECIFIED. ACCESS_MODE CHAR(20) Transaction access mode value associated with this entry.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions Examples of QUERYCACHEENTRIES • Display all information contained in the QUERYCACHEENTRIES table. Note that the output has been formatted for readability. >>SET SCHEMA SAMDBCAT.PERSNL; --- SQL operation complete. >SELECT * FROM EMPLOYEE; Employee/Number First Name -------------- -------------1 ROGER 23 JERRY 29 JANE . . . --- 62 row(s) selected.
Examples of QUERYCACHEENTRIES SQL/MX Functions and Expressions NUM_PARAMS ---------0 0 0 PARAM_TYPES ----------- AVERAGE_HIT_TIME ---------------41 0 0 SHAPE ------- PLAN_LENGTH ----------31752 24504 29144 IS_PINNED --------OFF OFF OFF ISOLATION_LEVEL --------------READ COMMITTED READ COMMITTED READ COMMITTED COMPILATION_TIME ----------------334 54 96 ACCESS_MODE -----------READ/WRITE READ/WRITE READ/WRITE AUTO_COMMIT ----------ON ON ON ROLLBACK_MODE -------------NOT SPECIFIED NOT SPECIFIED NOT
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-50. Examples of RADIANS • Return the value 7.85398150000000160E-001, or approximately 0.
SQL/MX Functions and Expressions REPEAT Function REPEAT Function The REPEAT function returns a character string composed of the evaluation of a character expression repeated a specified number of times. REPEAT is an SQL/MX extension. REPEAT (character-expr, count) character-expr specifies the source string from which to return the specified number of repeated strings. The source string is an SQL character value expression. The operand is the result of evaluating character-expr.
SQL/MX Functions and Expressions REPLACE Function REPLACE Function The REPLACE function returns a character string where all occurrences of a specified character string in the original string are replaced with another character string. REPLACE is an SQL/MX extension. REPLACE (char-expr-1, char-expr-2, char-expr-3) char-expr-1, char-expr-2, char-expr-3 are SQL character value expressions. The operands are the result of evaluating the character expressions.
SQL/MX Functions and Expressions RIGHT Function RIGHT Function The RIGHT function returns the rightmost specified number of characters from a character expression. RIGHT is an SQL/MX extension. RIGHT (character-expr, count) character-expr specifies the source string from which to return the rightmost specified number of characters. The source string is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-39.
SQL/MX Functions and Expressions ROWS SINCE Function ROWS SINCE Function The ROWS SINCE function is a sequence function that returns the number of rows counted since the specified condition was last true in the intermediate result table ordered by a SEQUENCE BY clause in a SELECT statement. See SEQUENCE BY Clause on page 7-18. ROWS SINCE is an SQL/MX extension. ROWS SINCE [INCLUSIVE] (condition [,max-rows]) INCLUSIVE specifies the current row is to be considered.
Examples of ROWS SINCE SQL/MX Functions and Expressions Examples of ROWS SINCE Suppose that SEQFCN has been created as: CREATE TABLE $db.mining.seqfcn (I1 INTEGER,I2 INTEGER,TS TIMESTAMP); Within MXCI, the ANSI alias name has been mapped as: CREATE SQLMP ALIAS db.mining.seqfcn $db.mining.
SQL/MX Functions and Expressions RPAD Function RPAD Function The RPAD function replaces the rightmost specified number of characters in a character expression with a padding character. RPAD is an SQL/MX extension. RPAD (character-expr,count [,pad-character]) character-expr is an SQL character value expression. The operand is the result of evaluating character-expr. See Character Value Expressions on page 6-39. count specifies the number of characters to be replaced in character-expr.
RTRIM Function SQL/MX Functions and Expressions RTRIM Function The RTRIM function removes trailing spaces from a character string. RTRIM is an SQL/MX extension. RTRIM (character-expression) character-expression is an SQL character value expression and specifies the string from which to trim trailing spaces. See Character Value Expressions on page 6-39.
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-40.
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-41 and the USER Function on page 9-172 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 SIGN Function SIGN Function The SIGN function returns an indicator of the sign of a numeric value expression. If the value is less than zero, the function returns -1 as the indicator. If the value is zero, the function returns 0. If the value is greater than zero, the function returns 1. SIGN is an SQL/MX extension. SIGN (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the SIGN function.
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-50. Examples of SIN • This function returns the value 3.42052233254419920E-001, or approximately 0.
SQL/MX Functions and Expressions SINH Function SINH Function The SINH function returns the hyperbolic sine of a numeric value expression, where the expression is an angle expressed in radians. SINH is an SQL/MX extension. SINH (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the SINH function. See Numeric Value Expressions on page 6-50. Examples of SINH • This function returns the value 1.60191908030082600E+000, or approximately 1.
SQL/MX Functions and Expressions SPACE Function SPACE Function The SPACE function returns a character string consisting of a specified number of spaces. SPACE is an SQL/MX extension. SPACE (length [,char-set-name]) length specifies the number of characters to be returned. The number count must be a value greater than or equal to zero of exact numeric data type and with a scale of zero. length cannot exceed 4096. char-set-name can be ISO88591, KANJI, KSC5601, or UCS2. The default is ISO88591.
SQL/MX Functions and Expressions SQRT Function SQRT Function The SQRT function returns the square root of a numeric value expression. SQRT is an SQL/MX extension. SQRT (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the SQRT function. The value of the argument must not be a negative number. See Numeric Value Expressions on page 6-50. Examples of SQRT • This function returns the value 5.19615242270663312E+000, or approximately 5.
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-50. Examples of TAN • This function returns the value 3.64008908293626896E-001, or approximately 0.
SQL/MX Functions and Expressions TANH Function TANH Function The TANH function returns the hyperbolic tangent of a numeric value expression, where the expression is an angle expressed in radians. TANH is an SQL/MX extension. TANH (numeric-expression) numeric-expression is an SQL numeric value expression that specifies the value for the argument of the TANH function. See Numeric Value Expressions on page 6-50. Examples of TANH • This function returns the value 8.
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-122. THIS is an SQL/MX extension.
SQL/MX Functions and Expressions Example of THIS The table SEQFCN has columns I1 and TS with data that is sequenced by column TS: I1 TS 6215 TIMESTAMP '1950-03-05 08:32:09' 28174 TIMESTAMP '1951-02-15 14:35:49' 19058 TIMESTAMP '1955-05-18 08:40:10' 4597 TIMESTAMP '1960-09-19 14:40:39' 31966 TIMESTAMP '1964-05-01 16:41:02' • Return the number of rows since the condition I1 less than a previous row became true: SELECT ROWS SINCE (THIS(I1) < I1) AS ROWS_SINCE_THIS FROM mining.
TRANSLATE Function SQL/MX Functions and Expressions TRANSLATE Function The TRANSLATE function translates a character string from a source character set to a target character set. TRANSLATE(character-value-expression USING translation-name) character-value-expression is a character string. translation-name is one of these translation names: Translation Name Source Character Set Target Character Set Comments ISO8859XToUCS2 (X in 1) ISO8859X UCS2 No data loss is possible.
SQL/MX Functions and Expressions TRANSLATE Function translation and the maximum length equal to the fix length or maximum variable length of the source character-value-expression. If you enter an illegal translation-name, NonStop SQL/MX returns an error. If the character set for character-value-expression is different from the source character set as specified in the translation-name, NonStop SQL/MX returns an error.
TRIM Function SQL/MX Functions and Expressions TRIM Function The TRIM function removes leading and trailing characters from a character string. TRIM ([[trim-type] [trim-char] FROM] trim-source) trim-type is: LEADING | TRAILING | BOTH trim-type specifies whether characters are to be trimmed from the leading end (LEADING), trailing end (TRAILING), or both ends (BOTH) of trim-source. If you omit trimtype, the default is BOTH.
SQL/MX Functions and Expressions UCASE Function UCASE Function Considerations for UCASE Examples of UCASE The UCASE function upshifts characters. UCASE can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UCASE function is equal to the result returned by the UPPER or UPSHIFT function.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
Considerations for UCASE SQL/MX Functions and Expressions Table 9-2.
SQL/MX Functions and Expressions Table 9-3.
SQL/MX Functions and Expressions Table 9-3.
SQL/MX Functions and Expressions Table 9-3.
Examples of UCASE SQL/MX Functions and Expressions Table 9-4. Three-Character UCS2 Mapping (page 2 of 2) Titlecase characters Three-Character Uppercase Expansions 0x1FE7 0x03A5 0x0308 0x0342 0x1FF7 0x03A9 0x0342 0x0399 0xFB03 0x0046 0x0046 0x0049 Examples of UCASE • Suppose that your CUSTOMER table includes an entry for Hotel Oregon.
UPPER Function SQL/MX Functions and Expressions UPPER Function The UPPER function upshifts characters. UPPER can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UPPER function is equal to the result returned by the UPSHIFT or UCASE function.
UPSHIFT Function SQL/MX Functions and Expressions UPSHIFT Function The UPSHIFT function upshifts characters. UPSHIFT can appear anywhere in a query where a value can be used, such as in a select list, an ON clause, a WHERE clause, a HAVING clause, a LIKE predicate, an expression, or as qualifying a new value in an UPDATE or INSERT statement. The result returned by the UPSHIFT function is equal to the result returned by the UPPER or UCASE function.
SQL/MX Functions and Expressions • Examples of UPSHIFT 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.
SQL/MX Functions and Expressions USER Function USER Function The USER function returns the current Guardian user ID as variable-length character data in the form group.name. USER The USER function is equivalent to the CURRENT_USER Function on page 9-41 and the SESSION_USER Function on page 9-141. Examples of USER • Retrieve the user name value for the current user: SELECT USER FROM logfile; (EXPR) -----------------------------------------DCS.TSHAW ... --- 5 row(s) selected.
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-40.
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-40.
SQL/MX Functions and Expressions HP NonStop SQL/MX Reference Manual—523725-004 9 -180 Examples of YEAR
10 Metadata Tables This section describes: Changes to SQL/MP Metadata SQL/MX Metadata Catalogs SQL/MX Metadata Schemas and Tables System Schema Tables Definition Schema Tables System Defaults Table User Metadata Tables (UMD): Histogram Tables MXCS Metadata Tables 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 statistics for SQL/MX objects.
Changes to SQL/MP Metadata Metadata Tables without the surrounding double quotes, and with two consecutive double quotes collapsed into one double quote. • Unless otherwise stated, CHAR(n) in the data type field without a character set qualifier is associated with the ISO88591 character set. All character types are searched or sorted with the DEFAULT (binary) collation with the PAD SPACE characteristic. For SQL/MX Release 2.
SQL/MX Metadata Catalogs Metadata Tables SQL/MX Metadata Catalogs There is one system catalog per node where NonStop SQL/MX has been initialized. It is stored in NONSTOP_SQLMX_nodename on the Data Access Manager volume specified as the system metadata volume during installation.There are five schemas in the system catalog: • • • • • DEFINITION_SCHEMA_VERSION_vernum. MXCS_SCHEMA SYSTEM_DEFAULTS_SCHEMA SYSTEM_SCHEMA SYSTEM_SQLJ_SCHEMA You can create as many user catalogs as you wish on a node.
Definition Schema Tables: Schema DEFINITION_SCHEMA_VERSION_vernum Metadata Tables Within system metadata tables, each object or partition is identified by a unique ID (UID). A UID is a 64-bit number, unique within the node, generated and assigned to the object or partition at the time it is created.
System Defaults Tables (User Metadata Tables): Schema SYSTEM_DEFAULTS_SCHEMA Metadata Tables TRIGGER_USED Table on page 10-26 Describes how triggers use objects VWS Table on page 10-27 Views in the catalog VW_COL_TBLS Table on page 10-27 Base tables referenced by columns of a view VW_COL_TBL_COLS Table on page 10-28 Base table columns used in views VW_COL_USAGE Table on page 10-28 Columns used in views VW_TBL_USAGE Table on page 10-28 Tables referenced by views System Defaults Tables (User Met
Histogram Tables Metadata Tables NAME2ID Table on page 10-79 Associates service or data source name to ID RESOURCEPOLICIES Table on page 10-80 Governing information *In addition, UMD tables exist here. Histogram Tables These tables contain histograms that show how data is distributed with respect to a column or a group of columns within a table. These statistics enable the optimizer to create efficient access plans.
System Schema Tables Metadata Tables System Schema Tables ALL_UIDS Table ALL_UIDS is a metadata table in NONSTOP_SQLMX_nodename.
CATSYS Table Metadata Tables CATSYS Table CATSYS is a metadata table in NONSTOP_SQLMX_nodename.
SCHEMATA Table Metadata Tables SCHEMATA Table SCHEMATA is a metadata table in NONSTOP_SQLMX_nodename.SYSTEM_SCHEMA that lists all schemas that have definitions on the node.
Definition Schema Tables Metadata Tables Definition Schema Tables ACCESS_PATHS Table ACCESS_PATHS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that describes physical instances of data in the catalog. (A physical instance of data is a simple table, an index, or a partition of a table or index.
ACCESS_PATH_COLS Table Metadata Tables Column Name Data Type Description 15 LOCK_LENGTH INT Reserved for future use 16 AUDITED CHAR(2) Y if this path is audited N if not 17 AUDIT_COMPRESS CHAR(2) Y if audit is compressed N if not 18 CLEAR_ON_PURGE CHAR(2) Y if deleted records are cleared N if not 19 BUFFERED CHAR(2) Reserved for future use 20 RECORD_PACKED CHAR(2) Reserved for future use 21 DATA_COMPRESSED CHAR(2) Reserved for future use 22 INDEX_COMPRESSED CHAR(2) Reserved for f
CK_COL_USAGE Table Metadata Tables CK_COL_USAGE Table CK_COL_USAGE is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that lists columns referenced by search conditions of check constraints in the catalog.
COLS Table Metadata Tables Column Name Data Type Description 5 COLUMN_NAME CHAR(128) Column name 6 COLUMN_SIZE LARGEINT Data bytes in column 7 SQL_DATA_TYPE CHAR(18) One of these SQL data types: CHARACTER DATE DATETIME SIGNED DECIMAL UNSIGNED DECIMAL DOUBLE FLOAT SIGNED INTEGER INTERVAL UNSIGNED BP INT UNSIGNED INTEGER SIGNED LARGEINT SIGNED NUMERIC UNSIGNED NUMERIC REAL SIGNED SMALLINT UNSIGNED SMALLINT TIME TIMESTAMP VARCHAR LONG VARCHAR 8 CHARACTER_SET CHAR(40) Character set 9 ENCODING
COLS Table Metadata Tables Column Name Data Type Description 11 FS_DATA_TYPE INT File system data type.
COLS Table Metadata Tables Column Name Data Type Description 17 DEFAULT_CLASS CHAR(2) Default defined by: Blank No default CD Current default ND Null default UD User default UF User defined function default If CD, the value of the column depends on its data type: DATE Current date TIME Current time TIMESTAMP Current timestamp 18 LOGGABLE CHAR(2) Reserved for future use 19 DATETIME_START_ FIELD INT First field if type datetime or INTERVAL: 1 if year 2 if month 3 if day 4 if hour 5 if minute 6 if
COL_PRIVILEGES Table Metadata Tables COL_PRIVILEGES Table COL_PRIVILEGES is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores grant information for columns in the catalog: Column Name Data Type Description *1 TABLE_UID LARGEINT UID of table *2 COLUMN_NUMBER INT Position within table (first column is 0) *3 GRANTOR INT Security ID of grantor (or of owner if grantor is super ID acting for owner) *4 GRANTOR_TYPE CHAR(2) S if system grant U if user grant *5 GRANTEE INT If GRANTE
DDL_LOCKS Table Metadata Tables DDL_LOCKS Table DDL_LOCKS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that is used for control locking of the base table so that utility operations in progress are protected against conflicting DDL operations: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of lock 2 BASE_OBJECT_UID LARGEINT UID of locked object 3 TIME_LOCK_REQUESTED LARGEINT Lock creation time 4 TIME_LOCK_ALTERED LARGEINT Time when the lock was last altered 5 OPERATI
MP_PARTITIONS Table Metadata Tables MP_PARTITIONS Table MP_PARTITIONS is a metadata table in DEFINITION_SCHEMA that stores partition names of SQL/MP tables that have SQL/MX aliases: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of table; link to OBJECTS 2 MPPARTITION_NAME CHAR(36) Name of NonStop SQL/MP partition system.volume.subvolume.
PARTITIONS Table Metadata Tables Column Name Data Type Description 6 CREATE_TIME LARGEINT Julian timestamp of creation time 7 REDEF_TIME LARGEINT Julian timestamp of redefinition time 8 CACHE_TIME LARGEINT Julian timestamp of cache time 9 OBJECT_FEATURE_VERSION INT Version of object 10 VALID_DEF CHAR(2) Y if definition valid N if not 11 OBJECT_SECURITY_CLASS CHAR(2) UM User metadata table UT User-defined table SM System metadata table 12 OBJECT_OWNER INT The integer representation o
REF_CONSTRAINTS Table Metadata Tables Column Name Data Type Description 12 EOF LARGEINT End of file indication at last UPDATE STATISTICS 13 PARTITION_STATUS CHAR(2) Status defined by: AV Available UO Unavailable, offline UC Unavailable, corrupt UD Unavailable, dropped UR Unavailable, re-created 14 DDL_IN_PROGRESS CHAR(2) Reserved for future use 15 FIRST_KEY VARCHAR(3000) User-specified first key in normalized form; otherwise, zero-length. If hash partitioned, a logical partition number.
REPLICAS Table Metadata Tables Column Name Data Type Description 7 DELETE_RULE CHAR(2) RE NA SD SN RESTRICT NO ACTION SET DEFAULT SET NULL * Indicates primary key REPLICAS Table REPLICAS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that stores the locations of views in the catalog.
ROUTINES Table Metadata Tables ROUTINES Table ROUTINES is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains SPJ-level attributes, one row for each stored procedure in Java (SPJ) created in this catalog. VARCHAR columns store letters as is (not converted to uppercase).
TBL_CONSTRAINTS Table Metadata Tables TBL_CONSTRAINTS Table TBL_CONSTRAINTS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains one entry for each unique, primary key, foreign, or check constraint on a table in the catalog: Column Name Data Type Description *1 CONSTRAINT_UID LARGEINT UID of constraint *2 CONSTRAINT_TYPE CHAR(2) Constraint type: C Check F Foreign P Primary key U Unique *3 TABLE_UID LARGEINT UID of table 4 DISABLED CHAR(2) Y if not enforced N if enforced 5 D
TEXT Table Metadata Tables Column Name Data Type Description *6 PRIVILEGE_TYPE CHAR(2) Privilege type: S SELECT I INSERT D DELETE U UPDATE R REFERENCES 7 IS_GRANTABLE CHAR(2) Y if granted with grant option N if not * Indicates primary key Grant information for individual columns is stored separately in the COL_PRIVILEGES table. All character columns store letters in uppercase except for GRANTOR and GRANTEE.
TRIGGERS_CAT_USAGE Table Metadata Tables Column Name Data Type Description 4 SUBJECT_UID LARGEINT UID of the table on which the trigger is defined 5 ACTIVATION_TIME CHAR(2) Activation time: B Before A After 6 OPERATION CHAR(2) Operation that fires the trigger: I INSERT D DELETE U UPDATE 7 GRANULARITY CHAR(2) Granularity: R Row S Statement 8 COLUMNS_IMPLICIT CHAR(2) Relevant only for UPDATE trigger: Y Yes N No 9 ENABLED CHAR(2) Current status of trigger: Y if enabled N if not 10 TRIGGE
TRIGGER_USED Table Metadata Tables TRIGGER_USED Table TRIGGER_USED is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that contains Information on how triggers use objects. It serves three purposes: • • • Given a table, return all the triggers of a certain operation that are defined on that table. Those triggers might be in other catalogs. For every local object (table or view), check if a trigger anywhere is using it.
VWS Table Metadata Tables VWS Table VWS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that lists views in the catalog: Column Name Data Type Description *1 OBJECT_UID LARGEINT UID of view 2 CHECK_OPTION CHAR(2) C if CASCADE L if LOCAL N if None 3 IS_UPDATABLE CHAR(2) Y if updating allowed N if not 4 IS_INSERTABLE CHAR(2) Y if inserting allowed N if not * Indicates primary key Text for views is stored separately in the TEXT table on the master node for the catalog.
VW_COL_TBL_COLS Table Metadata Tables VW_COL_TBL_COLS Table VW_COL_TBL_COLS is a metadata table in DEFINITION_SCHEMA_VERSION_vernum that records the base table columns referenced by each column of a view in the catalog: Column Name Data Type Description *1 VIEW_UID LARGEINT UID of referencing view *2 VIEW_COL_NUM INT Column number of referencing column (first is 0) *3 UNDERLYING_CAT_UID LARGEINT UID of catalog of referenced table *4 UNDERLYING_SCH_UID LARGEINT UID of schema of referenced tab
System Defaults Table Metadata Tables System Defaults Table SYSTEM_DEFAULTS Table Overriding System-Defined Default Settings Default Attributes Examples of SYSTEM_DEFAULTS Table SYSTEM_DEFAULTS is a metadata table in the SYSTEM_DEFAULTS_SCHEMA of catalog NONSTOP_SQLMX_nodename. that you use to store system-level default settings that override some of the system-defined default settings.
Overriding System-Defined Default Settings Metadata Tables For some attributes, you can override a default setting by specifying an option within a statement or command. For example, you can set the transaction isolation level with the SELECT statement. If you do not enter an option when entering a command or do not provide some attribute associated with the execution of queries, NonStop SQL/MX uses a default setting.
Default Attributes Metadata Tables Default Attributes Default attributes control these activities: Constraint Droppable Options Data Types Function Control Histograms Isolation Level Locking Module Management National Character Set Nonaudited Tables Object Naming Partition Management Query Optimization and Performance Query Plan Caching Referential Action Row Maintenance Scratch Disk Management Sequence Functions Statement Atomicity Statement Recompilation Stored Procedures in Java Stream Access Table Man
Default Attributes Metadata Tables Attribute Description Category CATALOG Default ANSI catalog name. Object Naming on page 10-47 CROSS_PRODUCT_CONTROL Determines whether plans are eliminated that contain unnecessary cross-products. Query Optimization and Performance on page 10-53 DATA_FLOW_OPTIMIZATION Controls whether query plans are considered that have high data flow rates.
Default Attributes Metadata Tables Attribute Description Category 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-50 GEN_MAX_NUM_PART_ NODE_ENTRIES Controls the size of a partition list prepared by the compiler and used by the executor. Partition Management on page 10-50 GEN_PA_BUFFER_SIZE Buffer size for partition access.
Default Attributes Metadata Tables Attribute Description Category HIST_SAME_TABLE_PRED_ REDUCTION Controls overlap amount in predicate selectivity when multicolumn predicates are used. Histograms on page 10-40 HIST_SCRATCH_VOL Sets the physical volume for UPDATE STATISTICS temporary tables. Histograms on page 10-40 HIST_SECURITY_WARNINGS Controls whether warnings on histogram tables are displayed.
Default Attributes Metadata Tables Attribute Description Category MDAM_SCAN_METHOD Enables or disables the MultiDimensional Access Method. Query Optimization and Performance on page 10-53 MIN_MAX_OPTIMIZATION Enables or disables MINMAX optimization. Query Optimization and Performance on page 10-53 MP_SUBVOLUME Default NonStop operating system Guardian subvolume. Object Naming on page 10-47 MP_SYSTEM Default NonStop operating system Guardian system name.
Default Attributes Metadata Tables Attribute Description Category PARALLEL_NUM_ESPS Maximum number of parallel ESPs that work on a particular type of operator, like a join. Query Optimization and Performance on page 10-53 PM_OFFLINE_ TRANSACTION_ GRANULARITY Number of rows to be copied in an offline MODIFY transaction. Partition Management on page 10-50 PM_ONLINE_ TRANSACTION_ GRANULARITY Number of rows to be copied in an online MODIFY transaction.
Default Attributes Metadata Tables Attribute Description Category QUERY_CACHE_REQUIRED_ PREFIX_KEYS Determines how many and which columns of a composite primary or partition key are required for an equality key predicate to be considered cacheable. Query Plan Caching on page 10-58 QUERY_CACHE_STATEMENT_ PINNING Controls the pinning and unpinning of query cache entries.
Default Attributes Metadata Tables Attribute Description Category SCRATCH_FREESPACE_ THRESHOLD_PERCENT Amount of scratch space left on disks as a threshold. Scratch Disk Management on page 10-60 SIMILARITY_CHECK Determines whether similarity checks are made to either keep or recompile an access plan. Statement Recompilation on page 10-62 STREAM_TIMEOUT Default time for a fetch operation using stream access to wait for more rows before timing out.
Constraint Droppable Options Metadata Tables Constraint Droppable Options These table entries describe settings that enable NonStop SQL/MX to ensure that the defaults for certain constraints are set to NOT DROPPABLE: Attribute Setting NOT_NULL_CONSTRAINT_ DROPPABLE_OPTION Set to ON (DROPPABLE) or OFF (NOT DROPPABLE). This option is used if DROPPABLE or NOT DROPPABLE does not appear in the definition of a NOT NULL column constraint. The default is OFF.
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 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. Histogram interval reduction has more affect on complex queries, especially if the underlying data distribution is evenly distributed. The compiler reduces the number of histogram intervals for columns containing numeric data types and nonnumeric data type columns only if there is no join or range predicate.
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 Isolation Level This attribute determines how NonStop SQL/MX assigns transaction isolation levels: Attribute Setting ISOLATION_LEVEL The isolation level for a transaction. Set to: READ UNCOMMITTED READ COMMITTED REPEATABLE READ SERIALIZABLE The default is READ COMMITTED. See Transaction Isolation Levels on page 1-20. Transaction isolation levels are determined according to rules applied in this order: 1.
Locking Metadata Tables Locking These attributes determine how NonStop SQL/MX locks objects: Attribute Setting MAX_ROWS_LOCKED_ FOR_STABLE_ACCESS The maximum number of rows locked by DP2 in STABLE ACCESS mode before the buffer is returned to the file system. The number of rows which are actually locked depends on this number and the size of the buffer. To increase concurrency, you can decrease this value so that more messages are used to return the same amount of data. The default value is 1.
Module Management Metadata Tables Module Management This attribute determines where globally placed modules are generated: Attribute Setting MXCMP_PLACES_LOCAL_ MODULES Set to ON or OFF. If OFF, NonStop SQL/MX generates global modules in the USERMODULES directory. If ON and you do not specify mxcmp -g moduleLocal=OSS-dir on the command line, compiled modules are placed in the current OSS directory.
Nonaudited Tables Metadata Tables Nonaudited Tables This attribute enables NonStop SQL/MX to handle inserts, updates, and deletes against nonaudited SQL/MP tables: Caution. If the IUD_NONAUDITED_INDEX_MAINT is set to ON, NonStop SQL/MX allows DML operations on nonaudited tables without error or warning. Before you set this attribute, see the SQL/MX Comparison Guide for SQL/MP Users to understand index maintenance of nonaudited tables.
Object Naming Metadata Tables Attribute Setting SCHEMA Default schema (without catalog) name, used if no second part is specified in a three-part logical name. The schema name can be qualified by a catalog name, in which case this catalog name supersedes any settings for the CATALOG attribute. If not set, the user name of the current user becomes the default second part of the logical name. In SQL/MX Release 2.0, the three-part name is an ANSI name.
Object Naming Metadata Tables 2. For SQL statements issued through MXCI and embedded SQL, the compiler uses the SYSTEM_DEFAULTS table entry (if it exists). 3. For SQL statements issued through MXCI and embedded SQL, if these values are not set, the system-defined default setting for the NAMETYPE attribute is ANSI. Attribute Value ANSI for Logical Names If the NAMETYPE attribute is ANSI or is not specified, object names are determined according to rules applied in this order: 1.
Partition Management Metadata Tables the current physical location. SET MPLOC changes the values for default attributes MP_SYSTEM, MP_VOLUME and MP_SUBVOLUME. Use the SET MPLOC statement in MXCI. For embedded SQL, the SET MPLOC statement affects only dynamic embedded SQL. The DECLARE MPLOC statement affects only static embedded SQL.
Partition Management Metadata Tables Attribute Setting GEN_MAX_NUM_PART_ DISK_ENTRIES When a statically compiled statement references partitioned objects, this default is used to control the size of a partition list prepared by the compiler and is used by the executor when it first opens the object, to support node and disk autonomy.
Partition Management Metadata Tables Attribute Setting POS_LOCATIONS Physical locations of nonprimary partitions to be automatically created, specified as [\node.]$volume. You can specify multiple locations separated by commas. If you enter a space (“ “), NonStop SQL/MX chooses the locations of the second through last partitions at random. NonStop SQL/MX does not place partitions on these types of disks: audit trail volumes, nonaudited disks, optical disks, phantom disks, or SMS virtual disks.
Query Optimization and Performance Metadata Tables Query Optimization and Performance These attributes enable NonStop SQL/MX to optimize query execution: Attribute Setting ATTEMPT_ASYNCHRONOUS_ ACCESS Set to ON or OFF. When set to ON, the optimizer generates plans that access multiple partitions asynchronously (that is, at the same time). With asynchronous access, the optimizer does not use ESPs to access the partitions in parallel.
Query Optimization and Performance Metadata Tables Attribute Setting DP2_CACHE_4096_BLOCKS Specifies the number of 4 KB blocks allocated for the disk cache. This value is used by the compiler to determine the cost of a table/index scan operator. You should set the value of this attribute to the average value of 4 KB block disk cache settings for all volumes in the system. The current value for the number of 4 KB blocks allocated to a disk cache can be determined by using SCF.
Query Optimization and Performance Metadata Tables Attribute Setting GEN_PA_BUFFER_SIZE Combined with GEN_EIDR_BUFFER_SIZE, determines the buffer size for partition access operations. The two default settings must be equal. For OLTP applications, reducing buffer size to 4 KB can improve performance by reducing memory usage. For DSS applications, use the default. The default buffer size is 31 KB.
Query Optimization and Performance Metadata Tables Attribute Setting MSCF_ET_REMOTE_MSG_ TRANSFER The value of this default is used to factor in the cost of transferring messages to and from a remote node. It reflects the bandwidth of the physical communication link. You should set it to a value greater than the cost factor of transferring messages to or from a local node, which is 0.000046. Allowable values: 1.17549e-038 through 3.40282e+38. The default value is 0.00005.
Query Optimization and Performance Metadata Tables Attribute Setting PARALLEL_NUM_ESPS Set to the keyword SYSTEM or to the maximum number of ESPs (an unsigned positive integer) that should be used for a particular operator. If set to SYSTEM, NonStop SQL/MX calculates the value. If set to a number, the value must be less than the number of CPUs in the cluster. For more information about this setting, see the SQL/MX Query Guide. Allowable values: 1 through 4294967040. The default is SYSTEM (no maximum).
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 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 FALSE and the declarations omit FOR UPDATE or FOR READ ONLY, all columns are updatable. In SQL/MX, if READONLY_CURSOR is set to TRUE, DELETE WHERE CURRENT OF does not work without the FOR UPDATE clause.
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 UPD_ABORT_ON_ERROR Controls whether an error that occurs during the performance of an insert, update, or delete causes an abort. ON means that NonStop SQL/MX will abort a user transaction after an error in an IUD statement.
Statement Recompilation Metadata Tables Attribute Setting RECOMPILATION_ WARNINGS Set to ON or OFF. If set to ON, when a statement is automatically recompiled in an application (because of various factors), NonStop SQL/MX returns a warning message. A warning is also returned when a similarity check passes. Set this default to ON only to direct warning messages to an application when automatic recompilations take place or to notify it if a similarity check has passed.
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-218.
Trigger Management Metadata Tables Attribute Setting If the 3-part ANSI name exceeds the maximum OSS file name length of 248, it is truncated to 248 characters. Despite similarities in the resulting file names because of character replacement or file name truncation, the files are always distinguishable by the trailing timestamp portion of the name and the contents of the file, which always indicates the full ANSI name of the table. NonStop SQL/MX does not remove saved DDL files.
Examples of SYSTEM_DEFAULTS Table Metadata Tables Control query default TEMPORARY_TABLE_HASH_PARTITIONS '$data01,$data02:$data03'; If you specify more than one volume, the temporary table is hash partitioned over all those partitions. Range partitioning is not supported. If no system default is specified, NonStop SQL/MX uses the default location of the creator of the first trigger. If the default is changed, the change affects temporary tables created after the change.
User Metadata Tables (UMD): Histogram Tables Metadata Tables User Metadata Tables (UMD): Histogram Tables HISTOGRAMS Table HISTOGRAM_INTERVALS Table HISTOGRM Table HISTINTS Table Examples of Histogram Tables A histogram is a representation of a relationship in which each value of some dependent variable corresponds to a range of values of the associated independent variable or variables. For example, a histogram might be a chart showing the number of people in New York in various age ranges.
Creating Histogram Tables Metadata Tables reside in the same HISTOGRAMS and HISTOGRAM_INTERVAL or HISTINTS and HISTOGRM tables. You can specify the number of intervals for the table statistics in the UPDATE STATISTICS statement. If you do not specify the number of intervals, NonStop SQL/MX provides a default number based on the table size and other factors. The histogram tables are not automatically updated when you alter a table for which statistics are stored.
HISTOGRAMS Table Metadata Tables HISTOGRAMS Table The SQL/MX HISTOGRAMS table describes columns, interval count, total number of rows and number of unique rows, and the low and high values of column distribution for a table: 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 HISTOGRAM_INTERVALS table.
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-105 D DEALLOCATE DESCRIPTOR Statement on page 3-16 DEALLOCATE PREPARE Statement on page 3-18 DECLARE CATALOG Declaration on page 3-21 DECLARE CURSOR Declaration on page 3-22 DECLARE MPLOC Declaration on page 3-28 DECLARE NAMETYPE Declaration on page 3-31 DECLARE SCHEMA Declaration on page 3-32 DELETE DEFINE Command on page 4-8 DELETE Statement on page 2-110 DESCRIBE Statement on page 3-33 DISPLAY STATISTICS Command on page 4-22 DISPLAY_EXPLAIN Command on
F Quick Reference EXEC SQL Directive on page 3-38 EXECUTE IMMEDIATE Statement on page 3-39 EXECUTE Statement on page 2-134 EXIT Command on page 4-28 mxexportddl Utility on page 5-59 F FC Command on page 4-29 FETCH Statement on page 3-40 FIXUP Operation on page 5-11 G GET DESCRIPTOR Statement on page 3-47 GET DIAGNOSTICS Statement on page 3-56 GOAWAY Operation on page 5-15 GRANT Statement on page 2-141 GRANT EXECUTE Statement on page 2-145 H HISTORY Command on page 4-31 I IF Statement on page 3-62 impo
M Quick Reference M migrate Utility on page 5-38 MODIFY Utility on page 5-43 MODULE Directive on page 3-71 MXCI Command on page 4-40 MXGNAMES Utility on page 5-61 mxtool Utility on page 5-68 O OBEY Command on page 4-41 OPEN Statement on page 3-73 P POPULATE INDEX Utility on page 5-69 PREPARE Statement on page 2-163 PURGEDATA Utility on page 5-72 PURGEDATA Utility on page 5-72 R RECOVER Utility on page 5-76 REGISTER CATALOG Command on page 2-168 REPEAT Command on page 4-43 RESET PARAM Command on page 4-
T Quick Reference SET MPLOC Statement on page 2-214 SET NAMETYPE Statement on page 2-215 SET PARAM Command on page 4-47 SET SCHEMA Statement on page 2-216 SET SHOWSHAPE Command on page 4-50 SET STATISTICS Command on page 4-53 SET TABLE TIMEOUT Statement on page 2-218 SET TRANSACTION Statement on page 2-223 SET WARNINGS Command on page 4-55 SH Command on page 4-56 SHOW PARAM Command on page 4-57 SHOW PREPARED Command on page 4-58 SHOW SESSION Command on page 4-59 SHOWCONTROL Command on page 4-61 SHOWDDL Co
W Quick Reference HP NonStop SQL/MX Reference Manual—523725-004 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-55. 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—523725-004 B- 6
C Limits This appendix lists limits for various parts of NonStop SQL/MX: • Constraints ° • DROP SCHEMA CASCADE transaction limits ° • • • • ° • NonStop SQL/MX typically generates good plans up to 16 tables and tries to generate plans with acceptable performance for queries up to 40 tables. Beyond that limit, the queries require some tuning to compile and run. IN predicate ° 1900 expressions are allowed. Indexes ° The maximum combined length of the columns for an index is 255 bytes.
Limits • • ° There are no restrictions on the number of partitions an table can support, but beyond 512, performance and memory issues might occur. ° Partitions can be on the same physical disk as the main file (SQL/MP partitions must be on a different disk.) PFS usage is decreased in the file system ° Referential constraints ° • This issue affects the number of opens.
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 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—523725-004 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 referen
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 SQ
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 vendorspecific encoded character set standards: ISO88591, UCS2, KANJI and KSC5601.
Character Set Support Standard SQL and SQL/MX HP NonStop SQL/MX Reference Manual—523725-004 E- 8
Index A ABS function examples of 9-10 syntax diagram of 9-10 Access options summary of 1-6 DELETE statement use of 2-112 DML statements use of 1-6 INSERT statement use of 2-149 READ COMMITTED 1-7 READ UNCOMMITTED 1-7 REPEATABLE READ 1-7 SELECT statement use of 2-192 SERIALIZABLE 1-7 SKIP CONFLICT 1-8 SQL/MP considerations 1-28 STABLE 1-8 UPDATE statement use of 2-235 Access privileges ALL PRIVILEGES 2-141 DELETE 2-141 INSERT 2-141 REFERENCES 2-141 SELECT 2-141 tables 2-141 UPDATE 2-141 views 2-141, 2-143 AC
A Index ALLOCATE DESCRIPTOR statement (continued) syntax diagram of 3-6 ALLOCATE file attribute 8-2 ALL_UIDS metadata table 10-7 ALTER DEFINE command examples of 4-6 syntax diagram of 4-5 ALTER INDEX statement ALLOCATE within 8-2 authorization and availability requirements 2-8 CLEARONPURGE within 8-5 DEALLOCATE within 8-2 examples of 2-8 file attributes 2-7 MAXEXTENTS within 8-8 syntax diagram of 2-7 ALTER SQLMP ALIAS statement examples of 2-10 syntax diagram of 2-9 ALTER TABLE statement ALLOCATE within 8
B Index AUDITCOMPRESS file attribute (continued) CREATE TABLE use of 8-3 syntax diagram of 8-3 Audited tables CREATE TABLE considerations 2-88 DELETE considerations 2-115 INSERT considerations 2-156 transaction management 1-13 UPDATE considerations 2-239 Authorization ID 1-5 AVG function DISTINCT clause use of 9-16 examples of 9-17 operand requirements 9-16 syntax diagram of 9-16 B BEGIN DECLARE SECTION C examples of 3-9 COBOL examples of 3-10 C++ examples of 3-9 BEGIN WORK statement audited tables, effe
C Index CHAR function (continued) syntax diagram of 9-25 CHAR VARYING data type 6-20 Character sets description of 6-3 ISO88591 6-3 KANJI 6-3 KSC5601 6-3 setting default 6-62, 6-63, 6-64, 10-62 support standards E-7 UCS2 6-3 Character string data types CHAR and VARCHAR, differences 6-21 examples of literals 6-65 maximum storage lengths 6-22 Character string functions summary of 9-2 ASCII 9-12 CHAR 9-25 CHAR_LENGTH 9-26 CODE_VALUE 9-29 CONCAT 9-30 INSERT 9-65 LCASE 9-68 LEFT 9-69 LOCATE 9-70 LOWER 9-74 LPA
C Index Clustering key (continued) NONDROPPABLE PRIMARY KEY specification 2-79 STORE BY clause 7-22 STORE BY clause, CREATE TABLE 2-82 system-defined SYSKEY 6-61 CODE_VALUE function, syntax diagram of 9-29 Collations description of 6-5 SQL/MP considerations 1-30 COLS metadata table 10-12 Columns column reference 6-6 default values 6-7 qualified name 6-6 COL_PRIVILEGES metadata table 10-16 Comment (--), examples of 1-3 Comments, host language 3-38 COMMIT WORK statement C examples of 2-33 COBOL examples of
C Index CONTROL TABLE statement examples of 2-51 syntax diagram of 2-48 CONVERTTIMESTAMP function examples of 9-32 JULIANTIMESTAMP inverse relationship to 9-32 syntax diagram of 9-32 Correlation names examples of 6-10 purpose of 6-10 table reference use of 6-10 COS function examples of 9-33 syntax diagram of 9-33 COSH function examples of 9-34 syntax diagram of 9-34 COUNT function DISTINCT clause within 9-35 examples of 9-36 syntax diagram of 9-35 CREATE CATALOG statement authorization requirements 2-52 e
D Index Ctrl-Y, effect on MXCI session 4-28 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 examples of 9-37, 9-40 precision specification within 9-37, 9-40 syntax diagram of 9-37, 9-40 CURRENT_USER function examples of 9-41 syntax diagram of 9-41 Cursor position DELETE statement use of 2-113 UPDATE statement use of 2-236 Cursors allocating extended 3-3 specifying read
D Index Data types (continued) SMALLINT 6-34 fixed length character 6-21 interval 6-16, 6-30 Java 2-63 literals, examples of character string literals 6-65 datetime literals 6-68 interval literals 6-73 numeric literals 6-75 SQL/MX 2-63 varying length character 6-21 Database object names 6-12 Database object namespace 6-14 Database objects 6-11 Database sample tables D-1 DATASOURCES metadata table 10-78 DATA_FLOW_OPTIMIZATION default 10-53 DATEFORMAT function examples of 9-42 syntax diagram of 9-42 Datetim
D Index DEALLOCATE DESCRIPTOR statement examples of 3-17 syntax diagram of 3-16 DEALLOCATE file attribute 8-2 DEALLOCATE PREPARE statement C examples of 3-19 COBOL examples of 3-20 syntax diagram of 3-18 DECIMAL data type 6-34 DECLARE CATALOG declaration C examples of 3-21 COBOL examples of 3-21 scope of 3-21 syntax diagram of 3-21 DECLARE CURSOR declaration C examples of 3-25 COBOL examples of 3-26 default for updatability 3-24 Publish/Subscribe examples of 3-5, 3-27 query expression within 3-23 specifyi
D Index Default settings (continued) HIST_SECURITY_WARNINGS 10-43 INDEX_ELIMINATION_LEVEL 10-55 INSERT_VSBB 10-59 INTERACTIVE_ACCESS 10-62 ISOLATION_LEVEL 10-44 IUD_NONAUDITED_INDEX_MAINT 1 0-47 JOIN_ORDER_BY_USER 10-55 MATERIALIZE 10-64 MAX_ESPS_PER_CPU_PER_OP 1055 MAX_ROWS_LOCKED_FOR_STABLE _ACCESS 10-45 MDAM_SCAN_METHOD 10-55 MIN_MAX_OPTIMIZATION 10-55 MP_SUBVOLUME 10-48 MP_SYSTEM 10-48 MP_VOLUME 10-48 MSCF_ET_REMOTE_MSG_TRANSFE R 10-56 MXCMP_PLACES_LOCAL_MODULES 10-46 NAMETYPE 10-47 NATIONAL_CHARSET 1
D Index DEFINITION_SCHEMA_VERSION_vernum schema (continued) tables 10-4 DEF_MAX_HISTORY_ROWS default 10-61 DEGREES function examples of 9-48 syntax diagram of 9-48 DELETE access privilege 2-141, 2-170 DELETE DEFINE command examples of 4-8 syntax diagram of 4-8 DELETE statement access options 2-112 file organization requirement 2-111 MXCI examples of 2-115 Publish/Subscribe examples of 2-118 SET ON ROLLBACK clause 2-112 SET ROLLBACK clause 2-112 SKIP CONFLICT access 2-113 STREAM clause 2-111, 2-232 syntax
E Index DML statements See Data Manipulation Language (DML) statements DOUBLE PRECISION data type 6-35 DP2_CACHE_4096_BLOCKS default 10-54 DROP CATALOG statement authorization and availability requirements 2-119 examples of 2-119 syntax diagram of 2-119 DROP INDEX statement authorization and availability requirements 2-120 examples of 2-121 supporting a constraint 2-120 syntax diagram of 2-120 DROP PROCEDURE statement examples of 2-123 syntax diagram of 2-122 DROP SCHEMA statement authorization and availa
F Index END DECLARE SECTION (continued) C++ examples of 3-37 syntax diagram of 3-37 Entry-sequenced table 1-30 ENV command attributes displayed by 4-24 examples of 4-25 syntax diagram of 4-24 ENVIRONMENTVALUES metadata table 10-79 ERROR command examples of 4-26 syntax diagram of 4-26 Error messages 1-34 Exclamation point (!) command examples of 4-27 syntax diagram of 4-27 EXCLUSIVE lock mode 1-10 EXEC SQL directive examples of 3-38 syntax diagram of 3-38 terminating with END-EXEC in COBOL 3-38 terminating
G Index FFDC_DIALOUTS_FOR_MXCMP default 10-54 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-8 File options CREATE INDEX use of 2-54 CREATE TABLE use of 2-75 STORE BY 2-82, 7-22 File organizations entry-sequenced 1-30 key-sequenced 1-30 relative 1-30 restrictions on 1-30 First (partition) keys 6-59 Fixed-length character column 6-21 FIXUP
I Index Histogram tables (continued) examples of 10-74 HISTINTS 10-73 HISTOGRM 10-72 maintaining 10-69 purpose of 10-68 UPDATE STATISTICS use of 2-246 Histograms clearing 2-246, 2-252 controls 10-40 generating 2-245 HISTOGRAMS metadata table 10-70 HISTOGRAM_INTERVALS metadata table 10-71 HISTOGRM metadata table 10-72 HISTORY command examples of 4-31 syntax diagram of 4-31 HIST_NO_STATS_REFRESH_INTERVAL default 10-42 HIST_NO_STATS_ROWCOUNT default 10-42 HIST_NO_STATS_UEC default 10-42 HIST_PREFETCH default
J Index INSERT statement (continued) MXCI examples of 2-157 ORDER BY clause 2-152 query expression within 2-151 syntax diagram of 2-149 target column list 2-151 using host variables 2-155 VALUES specification within 2-155 INSERT statement (embedded) C examples of 2-159 COBOL examples of 2-159 Insertable views 2-109 INSERT_VSBB default 10-59 INTEGER data type 6-34 INTERACTIVE_ACCESS default 10-62 INTERVAL data inserting into SQL/MP columns 6-71 selecting from SQL/MP tables 6-32 Interval data type descripti
L Index Keys (continued) primary 6-61 SYSKEY 6-61 Key-sequenced table 1-30 KEY_COL_USAGE metadata table 10-17 KSC5601 character set 6-3 L LARGINT data type 6-34 LASTNOTNULL function examples of 9-67 syntax diagram of 9-67 LCASE function examples of 9-68 syntax diagram of 9-68 LEFT function examples of 9-69 syntax diagram of 9-69 LEFT join, description of 2-187 LIKE predicate CREATE TABLE 2-88 escape character within 6-97 examples of 6-98 NOT within 6-96 syntax diagram of 6-96 wild-card characters within
M Index Locking (continued) SERIALIZABLE access option 1-9 SHARE lock mode 1-10 LOG command concurrent MXCI sessions 4-34 examples of 4-35 log file, contents of 4-34 syntax diagram of 4-34 Log file 4-34 LOG function examples of 9-72 syntax diagram of 9-72 LOG10 function examples of 9-73 syntax diagram of 9-73 Logical name SQL/MP objects 6-13 SQL/MX objects 6-12 Logical operators NOT, AND, OR 6-105 search condition use of 6-105 LOWER function examples of 9-78 syntax diagram of 9-74 LPAD function examples o
M Index Metadata schemas (continued) SYSTEM_DEFAULTS_SCHEMA 10-5 SYSTEM_SCHEMA 10-3 SYSTEM_SQLJ_SCHEMA 10-6 Metadata tables ACCESS_PATHS 10-10 ACCESS_PATH_COLS 10-11 ALL_UIDS 10-7 ASSOC2DS 10-77 CATSYS 10-8 CAT_REFERENCES 10-8 CK_COL_USAGE 10-12 CK_TBL_USAGE 10-12 COLS 10-12 COL_PRIVILEGES 10-16 DATASOURCES 10-78 DDL_LOCKS 10-17 ENVIRONMENTVALUES 10-79 HISTINTS 10-73 HISTOGRAMS_nodename 10-70 HISTOGRAM_INTERVALS 10-71 HISTOGRM 10-72 KEY_COL_USAGE 10-17 MP_PARTITIONS 10-18 NAME2ID 10-79 OBJECTS 10-18 PARTI
N Index MONTHNAME function examples of 9-86 syntax diagram of 9-86 MOVINGAVG function examples of 9-88 syntax diagram of 9-87 MOVINGCOUNT function examples of 9-90 syntax diagram of 9-89 MOVINGMAX function examples of 9-92 syntax diagram of 9-91 MOVINGMIN function examples of 9-94 syntax diagram of 9-93 MOVINGSTDDEV function examples of 9-96 syntax diagram of 9-95 MOVINGSUM function examples of 9-98 syntax diagram of 9-97 MOVINGVARIANCE function examples of 9-100 syntax diagram of 9-99 MP_PARTITIONS metad
O Index NCHAR data (continued) selecting from SQL/MP tables 6-23 NCHAR data type associated character sets 6-4 description of 6-20 SQL/MP considerations 1-28, 6-23, 6-64 NCHAR VARYING data type 6-20 Nonaudited tables CREATE TABLE considerations 2-88 DELETE considerations 2-115 transaction management 1-13 NONSTOP_SQLMX_nodename.
P Index P PARALLEL_NUM_ESPS default 10-57 Parameter specification examples of 6-78 names 6-77 type assignments 6-76 Parameters in dynamic SQL, restrictions on use 2-164 PARTITION clause examples 7-7 syntax diagram of 7-5 Partition Overlay Specification (POS) default attributes 10-50 description of 2-90 Partitioning key CREATE INDEX, FIRST KEY specification 2-57 CREATE TABLE, FIRST KEY specification 2-84 Partitions automatic creation 2-90 description of 6-82 hash 6-82 hash, MODIFY utility 5-49 managing 5-4
Q Index Predicates summary of 6-84 BETWEEN 6-85 comparison 6-87 description of 6-84 EXISTS 6-91 IN 6-93 LIKE 6-96 NULL 6-98 quantified comparison 6-99 PREFERRED_PROBING_ORDER_FOR_N ESTED_JOIN default 10-57 PREPARE statement availability 2-164 C examples of 2-166 COBOL examples of 2-167 MXCI examples of 2-165 naming statements 2-165 scope of 2-164 syntax diagram of 2-163 Prepared SQL, statements for 2-3 PRESERVE_MIN_SCALE default 10-40 Primary key ALTER TABLE statement 2-15 description of 6-61 Primary key
R Index QUERY_CACHE_REQUIRED_PREFIX_KE YS default 10-58 R RADIANS function examples of 9-118 syntax diagram of 9-118 Range partitioning description of 6-82 MODIFY utility 5-43, 5-45 READ COMMITTED 1-6 READ UNCOMMITTED 1-6 READONLY_CURSOR default 10-60 REAL data type 6-35 RECOVER utility 5-76 REFERENCES access privilege 2-141, 2-171 References column constraint, ALTER TABLE statement 2-16, 2-19 References column constraint, description of 6-8 Referential integrity constraint 6-8 Referential integrity, ALT
S Index Row value constructor (continued) comparison predicates use of 6-87 IN predicate use of 6-93 NULL predicate use of 6-98 quantified comparison predicates use of 6-100 ROWS SINCE function examples of 9-123 syntax diagram of 9-122 Rowsets DELETE statement 2-111, 2-112 expressions 6-53 GET DESCRIPTOR items 3-51 INSERT statement 2-150, 2-152 predicates 6-103 search condition 6-107 SELECT statement FROM clause 2-188 HAVING clause 2-192 host variables 2-183 ROWSET FOR clause 2-181 search condition 2-189
S Index Schemas, description of 6-104 SCHEMATA metadata table 10-9 SCHEMA_REPLICAS metadata table 10-9 Scope ALLOCATE CURSOR use of 3-3 ALLOCATE DESCRIPTOR use of 3-6 CLOSE use of 3-11 DEALLOCATE DESCRIPTOR use of 3-16 DEALLOCATE PREPARE use of 3-18 DECLARE CURSOR use of 3-24 DESCRIBE use of 3-34 EXECUTE use of 2-135 FETCH use of 3-41 OPEN use of 3-73 PREPARE use of 2-164 SCRATCH_DISKS default 10-60 SCRATCH_DISKS_EXCLUDED default 10-60 SCRATCH_DISKS_PREFERRED default 10-60 SCRATCH_FREESPACE_THRESHOLD_P ER
S Index Sequence functions (continued) MOVINGAVG 9-87 MOVINGCOUNT 9-89 MOVINGMAX 9-91 MOVINGMIN 9-93 MOVINGSTDDEV 9-95 MOVINGSUM 9-97 MOVINGVARIANCE 9-99 OFFSET 9-102 ROWS SINCE 9-122 RUNNINGAVG 9-126 RUNNINGCOUNT 9-128 RUNNINGMAX 9-130 RUNNINGMIN 9-132 RUNNINGSTDDEV 9-134 RUNNINGSUM 9-136 RUNNINGVARIANCE 9-138 THIS 9-156 SERIALIZABLE 1-6, 1-9 SESSION_USER function examples of 9-141 syntax diagram of 9-141 SET CATALOG statement C examples of 2-213 COBOL examples of 2-213 MXCI examples of 2-213 scope of 2-
S Index SET WARNINGS command examples of 4-55 syntax diagram of 4-55 SH command examples of 4-56 syntax diagram of 4-56 SHARE lock mode 1-10 Shorthand view 6-112 SHOW PARAM command examples of 4-57 syntax diagram of 4-57 SHOW PREPARED command examples of 4-58 syntax diagram of 4-58 SHOW SESSION command attributes displayed by 4-59 examples of 4-60 syntax diagram of 4-59 SHOWCONTROL command examples of 4-62 syntax diagram of 4-61 SHOWDDL command examples of 4-71 syntax diagram of 4-67 SHOWLABEL command exa
S Index SQL/MP aliases ALTER SQLMP ALIAS statement 2-9 catalogs 10-48 CREATE SQLMP ALIAS statement 2-71 description of 6-108 DROP SQLMP ALIAS statement 2-128 OBJECTS table 6-14 schemas 6-104 SQL/MP catalogs 6-2 SQL/MP considerations access options 1-28 catalogs 6-2 collations 1-30 datetime literals data inserting 6-66 selecting 6-26 embedded statements 3-1 INTERVAL data inserting 6-71 selecting 6-32 NCHAR data inserting 6-64, 6-65 selecting 6-23 reserved words 1-24, B-1 stored text 1-29 views 1-28 SQL/MP
S Index Statistics (continued) examples of 2-252 syntax diagram 2-245 STDDEV function DISTINCT clause within 9-147 examples of 9-148 statistical definition of 9-147 syntax diagram of 9-147 STORE BY clause, syntax description 7-22 Stored procedure statements CALL 2-28 CREATE PROCEDURE 2-61 DROP PROCEDURE 2-122 Stored text reserved words B-1 SQL/MP restrictions 1-29 Stream timeout dynamic, SET TABLE TIMEOUT statement setting 2-218 static CONTROL QUERY DEFAULT statement setting 2-35 SYSTEM_DEFAULTS table 10-
T Index SYSTEM_DEFAULTS table (continued) nonaudited tables 10-47 object naming 10-47 partition management 10-50 query optimization and performance 10-53 query plan caching 10-58 referential action 10-59 row maintenance 10-59 scratch disk management 10-60 sequence functions 10-61 statement atomicity 10-62 statement recompilation 10-62 stored procedures in Java 10-64 stream access 10-64 table management 10-65 SYSTEM_SQLJ_SCHEMA schema 10-6 T Table reference description of 2-184 SELECT statement use of 2-1
U Index TRANSPOSE clause (continued) 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-26 considerations 2-98 CREATE TABLE LIKE statement 2-88 CREATE TRIGGER statement 2-96 description 6-111 DROP TRIGGER statement 2-132 DUP utility 5-8 import utility 5-21 privileges 2-143 PURGEDATA utility 5-73 SET statement 2-211 SIGNAL SQLSTATE statement 2-227 TRIGGERS metadata table 10-24 TRIGGERS_CAT_USAGE metadata table 10-25 TRIGGER_USED met
V Index UPD_ORDERED default 10-57 UPD_SAVEPOINT_ON_ERROR default 10-62 UPPER function examples of 9-169 syntax diagram of 9-169 UPSHIFT function examples of 9-170 syntax diagram of 9-170 User aliases, for super IDs executing privileged utilities 5-2 USER function examples of 9-172 syntax diagram of 9-172 Utilities DUP 5-4 FIXUP 5-11 GOAWAY 5-15 import 5-20 INFO 5-36 MIGRATE 5-38 MODIFY 5-43 mxexportddl 5-59 MXGNAMES 5-61 mxtool 5-68 POPULATE INDEX 5-69 privileges required to execute 5-2 PURGEDATA 5-72 REC
Y Index Y YEAR function examples of 9-179 syntax diagram of 9-179 Z ZIG_ZAG_TREES default 10-57 Special Characters =_DEFAULTS define 10-48, 10-50 HP NonStop SQL/MX Reference Manual—523725-004 Index -34