KB_SQL Programmer s Reference Guide
|
|
|
- Milo Stewart
- 10 years ago
- Views:
Transcription
1 KB_SQL Programmer s Reference Guide
2
3 Table of Contents CHAPTER 1: AN OVERVIEW SQL IN PERSPECTIVE...2 EASY TO LEARN...2 PIGGYBACKING SQL...2 DEVELOPING WITH KB_ESQL/KB_SQL API...3 KB SYSTEMS CLIENT/SERVER ARCHITECTURE...4 COMMON ELEMENTS...4 DISTINCTIVE ELEMENTS...5 SUMMARY...6 CHAPTER 2: USING THE KB_ESQL CHOOSING A SOURCE TYPE...8 STRUCTURAL CHARACTERISTICS...8 LANGUAGE ELEMENTS...11 CREATING THE SOURCE...13 CONNECTIONS...13 TRANSACTIONS...16 CURSORS...22 SQLCODE & SQLSTATE VARIABLES...26 COMPILING THE SOURCE...29 SQL0S...29 EPI^SQL...32 EP^SQL...33 ESQL EXAMPLES...37 CHAPTER 3: USING THE KB_SQL API A FRAMEWORK FOR IMPLEMENTATION...49 NETWORK STANDARDS...49 SOFTWARE STANDARDS...50 A CONCEPTUAL VIEW OF THE KB_SQL API...50 FEATURES OF THE KB_SQL API...55 PREPARED AND DIRECT EXECUTION...55 ODBC EXTENSIONS...56 ERROR PROCESSING...65 ON-LINE SUPPORT...69 DEFAULT DATA TYPES...69 KB_SQL API FUNCTION SUMMARY...70 KB_SQL API FUNCTION REFERENCE...72 PUTTING IT TOGETHER CONNECTING TO A DATA SOURCE PROCESSING SQL STATEMENTS...145
4 APPENDIX A: A COMPARISON OF KB_ESQL & KB_SQL API APPENDIX B: USING THE KB_SQL API FOR MSE ii KB_SQL Programmer s Reference Guide
5 Chapter 1 An Overview Welcome to KB_SQL Version 3 s programming development tools, KB_ESQL and KB_SQL API, embedded structured query language and application programming interface, respectively. We think you ll find this development milestone for KB Systems to be arguably the finest accomplishment among many significant new capabilities offered in this release. The culmination of a number of years of intensive research and development, KB_ESQL and KB_SQL API provide the exciting new dimension of programmatic access to information retrieval and analysis. Many of you are already familiar with the power and flexibility of SQL through earlier releases of KB_SQL. Both the EZQ Report Writer and SQL Editor harness SQL in an interactive mode. Now that same dazzling capability can be built into your own applications. Chapter 1: An Overview 1
6 SQL in Perspective Originally developed by IBM Research Laboratories, SQL s strength lies in its data and device independence. You are relieved of the nagging details of how data is physically accessed and can rely on one standard to access data wherever it resides mainframes, minicomputers, or personal computers. In addition, because it has been adopted by ANSI as the de facto standard for relational database access, you are assured of a reasonably long and stable life for your applications. Easy to Learn Approximately 30 commands comprise this elegant and concise query language with a core of four basic commands for data manipulation. The four commands (SELECT, UPDATE, DELETE, and INSERT) are used to form statements that closely resemble the structure of a natural English question or query. Once the basics are understood, a developer can adapt to the specifics of any SQL environment. Piggybacking SQL For all its strength and versatility, SQL is a special purpose database sublanguage; there are no provisions for declaring variables, testing for certain conditions, or constructing loops. Originally geared toward stand-alone, interactive use, the standard has evolved with an eye towards its programmatic implementation. In this way, existing, standardized procedural languages may incorporate the special purpose functionality of SQL to deliver database access on an enterprise-wide scale. 2 KB_SQL Programmer s Reference Guide
7 Developing with KB_ESQL/KB_SQL API Perhaps the most compelling reason for an application programmer to develop with KB_ESQL and KB_SQL API is the need to position your applications, as well as yourself, for the future. Astute developers recognize the rapid rise of client/server architecture as the result of a relentless, industry-wide objective to provide seamless cross-systems intercommunication. Part and parcel of this movement is the ability to access data no matter what it looks like or where it resides. Implementing an SQL interface in your application clearly promotes this objective. To give you some feel for KB Systems blueprint for effecting this concept, see the diagram on the next page which illustrates KB Systems Client/Server Architecture. When fully implemented, it will provide transparent data access and facilitate intercommunication. For purposes of this guide, however, we confine our discussion to Version 3 s two new programming tools, KB_ESQL and KB_SQL API, which use the KB_SQL Engine as a server. Chapter 1: An Overview 3
8 KB Systems Client/Server Architecture Whether you develop with KB_ESQL or KB_SQL API depends largely on the nature of the application. As a general rule, KB_ESQL is well-suited to static applications while KB_SQL API lends itself to ad hoc, dynamic applications. There is much common ground shared by either approach, minimizing exhaustive retraining. Common Elements Both approaches share the key concepts of environments, connections, statements, and cursors. In short, the environment is a distinct M $JOB; a connection establishes communication between the application and the database engine (even when both reside on the same system); a statement requests data; and a cursor is the mechanism by which you retrieve data. The following chapters provide more details on these concepts. 4 KB_SQL Programmer s Reference Guide
9 Distinctive Elements KB_ESQL insulates your static applications from changes in the structure of the database. ESQL supports standard SQL as well as several extensions that are unique to ESQL. A precompiler translates ESQL into one or more M routines. The result is a reusable, executable program that is compiled one time and can be run many times. A typical best-use example for this approach would be the hypothetical development of an account management application for Intuit s Quicken where the procedure is fixed. KB_SQL API provides maximum flexibility to dynamic applications through the use of function calls from within the application. Unlike KB_ESQL, SQL commands are compiled or prepared at runtime. Here a best-use example would be the hypothetical development of an Microsoft Access application that uses a query by form approach (an open-ended procedure) to determine what s out there as the basis for a report. Chapter 1: An Overview 5
10 Summary KB_ESQL and KB_SQL API provide programmatic access to database resources. While each is best-suited to a particular type of application, both bring the power and versatility of SQL to your development efforts, positioning your applications for maximum interoperability. The following two chapters, replete with diagrams and examples, are designed to provide the information you need to develop simple to complex applications using KB_ESQL and KB_SQL API. For a quick comparison of common functions of KB_ESQL and KB_SQL API, see Appendix A. KB Systems wishes you every success in your development efforts using KB_ESQL and KB_SQL API. 6 KB_SQL Programmer s Reference Guide
11 Chapter 2 Using the KB_ESQL When special SQL statements are specified together with a traditional procedural language like M, the technique is generally referred to as embedded SQL (ESQL). The resulting blended source cannot be submitted to its host language compiler, or interpreter in the case of M, without producing an abrupt, if not screeching, halt in the process. A precompiler solves the problem by converting ESQL statements into one or more equivalent M routines. Once ESQL is introduced to the application, the developer realizes two significant advantages: first, the ability to reference data using table and column names, and second, simplified application maintenance. This chapter describes the basic concepts of KB_ESQL to guide you in your application development. The examples that follow demonstrate the structure and capabilities of ESQL and will repay close attention. Chapter 2: Using the KB_ESQL 7
12 Choosing a Source Type The process begins when you create and store the initial source of M code and ESQL statements in one of three available source types: a routine, a global, or a file. All of the source types have the same set of capabilities. Choose the type that is most convenient for your environment. For example, in a stand-alone M system, using the routine or global type avoids having to exit M to view or modify a source. Alternatively, if you are running a layered-windowing environment, using the file type allows you to use any non-m text editor. Structural Characteristics Structurally, the source resembles M routines: it is composed of one or more lines, each having two distinct pieces a tag name, delimited by a tab character ($ASCII(9)), followed by a command string. The usual M tag naming rules apply with one exception: the ampersand character (&) is also allowed under certain situations. The command string may contain any valid M commands and an ESQL statement. An M command string follows a fairly simple structure consisting of one or more command-argument pairs. Each command-argument starts with a command or conditionalized command, followed by a space character, followed by an argument list. Each command-argument within the command string is also separated by a space character. 8 KB_SQL Programmer s Reference Guide
13 M command strings: [command_argument<space>]...command_argument Examples: S X=1 S X=1 D ^XXX An ESQL statement may be defined at any command position within the command string; however, it must be the last command in the line. ESQL takes the format &SQL(statement). Command string with ESQL: [command_argument<space>]...esql_statement Examples: &SQL(CONNECT TO M USER DBA AUTHORIZATION SHARK) S X=1 &SQL(FETCH C1 INTO :A,:B) For readability, we recommend always using the first command position for ESQL statements. If the statement is too long to fit on one line, additional continuation lines may be used by either placing a single ampersand in the tag position or two ampersands at the beginning of the command string. We illustrate below. & &SQL(CONNECT TO M USER DBA AUTHORIZATION SHARK) OR &SQL(CONNECT TO M USER DBA && AUTHORIZATION SHARK) Note: The use of double ampersands is our extension; it is not part of the M-SQL binding. Following is a simple example to demonstrate the preceding remarks. &SQL(connect to DEFAULT user SHARK) Chapter 2: Using the KB_ESQL 9
14 &SQL(update employees set salary = salary * 1.1 & where salary < 18) &SQL(commit) &SQL(disconnect) Q 10 KB_SQL Programmer s Reference Guide
15 Language Elements ESQL supports a full implementation of Data Manipulation Language (DML), Data Definition Language (DDL), and Data Control Language (DCL). In addition, ESQL supports a variety of statements that are valid only in ESQL. The tables below summarize supported SQL statements; ESQL statements are listed in the table on the next page. For more information on the use of all the various statements, refer to the KB_SQL Syntax Guide. SQL Data Manipulation (DML) SELECT Retrieves columns from tables. INSERT Adds new rows to a table. UPDATE Changes columns in a table. DELETE Removes rows from a table. SQL Data Definition (DDL) ALTER Changes a data dictionary object. CREATE Adds a new data dictionary object. DROP Removes data dictionary objects. SQL Data Control (DCL) GRANT Gives privileges to user groups. REVOKE Takes privileges away from user groups. Chapter 2: Using the KB_ESQL 11
16 ESQL Statements CLOSE COMMIT CONNECT DECLARE CURSOR DELETE (positioned) DISCONNECT FETCH GET DIAGNOSTICS OPEN ROLLBACK SELECT INTO SET CONNECTION SET TRANSACTION UPDATE (positioned) Deletes a named result set. Terminates current transaction and applies pending changes to the database. Establishes a link between an application and a database. Creates a positional reference to a result set. Deletes the row specified by a cursor. Terminates a connection between an application and a database. Positions a cursor on a specific result table row and retrieves the result column values from that row. Returns status information on the last SQL statement. Builds a named result set and positions the cursor prior to the first row. Terminates the current transaction and discards pending changes to the database. Selects data values from a particular row in a table producing a single row result set. Sets the active connection. Defines transaction related parameters. Updates the row specified by a cursor. 12 KB_SQL Programmer s Reference Guide
17 Creating the Source We turn now to a discussion of the manner in which the ESQL syntactical and semantic elements are combined within the source to access the database. Some fundamental concepts are connections, transactions, and cursors. We examine key details for each as they pertain to programming with M. To preface our coverage, you should understand that a hierarchical relationship exists between connections, transactions, and cursors. All of these elements are part of the larger logical environment, that is, a distinct M $JOB. Each environment may establish one or more connections. Each connection may perform one or more sequential transactions. Each transaction, in turn, may declare one or more cursors that are unique to the transaction. Keep this hierarchy in mind as you review the following sections. Connections With the programmatic approach of ESQL, you must manually establish a connection between the application and the database engine, from client to server. Such a connection is necessary for intercommunication between the two entities, even when both exist on the same computer. Clients like the SQL Editor and EZQ Editor establish an automatic, albeit transparent, connection to the SQL engine using the sign-on routine ^SQL. The ESQL statements shown on the next page all relate to the connection event. Chapter 2: Using the KB_ESQL 13
18 Connection-Related Statements CONNECT TO {server_name or DEFAULT} [AS connection_name] [USER [user_name [SET] AUTHORIZATION] password] SET CONNECTION connection_name DISCONNECT [ALL or CURRENT or DEFAULT or connection_name] The CONNECT and DISCONNECT statements are required as a functional pair; you create a connection using the CONNECT statement and terminate the connection using the DISCONNECT statement as shown below. In addition, the CONNECT statement confers an active or inactive status to each connection. A Functional Pair CONNECT TO DEFAULT USER SHARK... DISCONNECT DEFAULT Notice in the Connection-Related statements illustration that each CONNECT statement identifies a specific connection name that is unique within the environment. Using DEFAULT consistently for all connection_name references can provide greater portability since the local system name may be changed without affecting the ESQL code. 14 KB_SQL Programmer s Reference Guide
19 If the CONNECT statement contains the AS connection_name clause, the connection takes the specified name; otherwise, the connection name defaults to the server name. If a second connection name is then established by a second CONNECT statement, the first connection name automatically becomes inactive. You may activate or inactivate a connection at any time by using the SET CONNECTION statement. Regardless of the number of established connections, only one connection may be active at a time. Prior to the CONNECT, and after the DISCONNECT, the connection name and status are undefined. The table below outlines the parameters, values, and meanings of the connection name and status. Connection Parameters Parameter Value Meaning Connection name server_name Uses the local system name as the connection name. connection_name Uses the specified name of the AS connection_name clause for the connection name. Connection status active All ESQL statements are sent to the active connection by the SQL engine. inactive A connection is suspended until activated by a SET CONNECTION statement. Chapter 2: Using the KB_ESQL 15
20 Transactions Once a connection is established, the next phase of the process centers on the transaction. A transaction is a discrete unit of work composed of one of more statements that reference and/or modify the database. The atomic execution, all or nothing, of the transaction is a specification of the SQL transaction model. The objective of that model is to maintain a consistent state in the database. Like the transaction, statements are atomic in and of themselves. This means the programmer can accommodate a failure at the statement level without losing the entire transaction. Two other provisions of the SQL transaction model, concurrency control and recovery, are critical in a multi-user transaction environment. Briefly stated, concurrency control provides for multiple access without the loss or corruption of data while recovery ensures that partial transactions never become part of the database. With these comments in mind, we move on to a closer look at the structure of a transaction. 16 KB_SQL Programmer s Reference Guide
21 Transaction-Related Statements Three statements, shown below, are integral to an ESQL transaction. Transaction-Related Statements COMMIT [WORK] ROLLBACK [WORK] SET TRANSACTION [{AUTO COMMIT} or {MANUAL COMMIT}] [ISOLATION LEVEL {READ UNCOMMITTED or READ COMMITTED}] [{READ ONLY} or {READ WRITE}] Commit/Rollback For each transaction, all database changes (work) associated with the transaction are either applied (COMMIT) or not applied (ROLLBACK). The COMMIT statement makes any modifications to the database permanent, and deletes all transaction-related structures. Conversely, the ROLLBACK statement discards all database modifications and deletes all transaction-related structures. Other conditions may also terminate a transaction causing an implicit ROLLBACK including an unrecoverable system error, a data definition statement (CREATE, ALTER or DROP), or a data control statement (GRANT or REVOKE). Chapter 2: Using the KB_ESQL 17
22 Setting Transaction Attributes Default transaction parameters are established by the CONNECT statement. To use a different set of parameter values, the SET TRANSACTION statement should immediately follow the CONNECT statement to ensure consistency. Once assigned, transaction parameters should not be changed again until a COMMIT or ROLLBACK statement is executed, completing the current transaction. Transaction Commit Modes Each transaction has a commit mode of either AUTO COMMIT or MANUAL COMMIT. The default commit mode for ESQL is MANUAL COMMIT. The commit mode attribute that may be changed by the SET TRANSACTION statement. In the default MANUAL COMMIT mode, a transaction is initiated implicitly by the first SQL statement that causes a database reference or modification. Therefore, every subsequent reference to the database is considered part of that same transaction until the transaction is explicitly terminated by a COMMIT or ROLLBACK statement. An attempt to execute a DISCONNECT statement without completing a database update transaction returns an error (SQLSTATE=25000, invalid transaction state). When the commit mode is set to AUTO COMMIT, each statement that completes is immediately committed, effectively starting and ending with statement execution. If the statement encounters an error, a rollback occurs automatically, thus ending the transaction. 18 KB_SQL Programmer s Reference Guide
23 Isolation Level Another optional element of the SET TRANSACTION syntax is the isolation level of the transaction. The isolation level determines the degree to which separate simultaneous transactions are insulated from affecting each other, thus controlling their interaction. Version 3 provides two isolation levels: READ UNCOMMITTED or READ COMMITTED. The default is READ UNCOMMITTED. Your DBA may change this level using the Default transaction isolation level prompt of the CONFIGURATION/SITE EDIT/ANSI INFO option. READ COMMITTED permits reads and modifications of committed rows only. It ensures your transaction does not read or modify a row another concurrent transaction has changed but not yet committed. The READ UNCOMMITTED isolation level allows reads of pending transactions that have not been committed. However, it ensures your transaction does not modify a row that another concurrent transaction has changed but not yet committed. The isolation level may be changed by a SET TRANSACTION statement. Note: ANSI SQL2 also supports REPEATABLE READ and SERIALIZABLE levels, but these are not implemented in Version 3. Internally, the isolation level is implemented through means of automatic READ or WRITE locks that are transparent to the user. Their purpose is to ensure the consistency of the data for the duration of the transaction, through the final COMMIT or ROLLBACK. For more information on the subject of READ and WRITE locks, refer to the KB_SQL Data Dictionary Guide. Chapter 2: Using the KB_ESQL 19
24 Access Mode The last option you may choose to set for the transaction is the access mode. Each transaction may be set to either READ ONLY or READ WRITE. The default is READ WRITE. Of course, the programmer compiling the embedded program (EP) must have the appropriate table privileges to successfully compile any INSERT, UPDATE, or DELETE statements. The access mode may be changed by using the SET TRANSACTION statement with the READ ONLY clause. When the mode is READ ONLY, all database updates are rejected. The table on the next page summarizes the parameters for transaction processing. 20 KB_SQL Programmer s Reference Guide
25 Transaction Parameters Parameter Value Meaning Commit Mode MANUAL COMMIT All transactions must be explicitly terminated by either a COMMIT or ROLLBACK statement. AUTO COMMIT Each successful SQL statement is immediately committed; each statement that encounters an error is immediately rolled back. Isolation Level READ COMMITTED The transaction returns a concurrency error if it attempts an action that would cause a READ or WRITE lock on a table row that has already been updated by another concurrent transaction. (An update transaction causes a WRITE lock which is exclusive.) READ UNCOMMITTED The transaction allows reads on rows that are WRITE locked by another concurrent transaction. Access Mode READ WRITE The transaction may read and update table READ ONLY rows. The transaction may read table rows, but cannot update table rows. Chapter 2: Using the KB_ESQL 21
26 Cursors While the set-at-a-time processing of SQL is ideal for certain operations, procedural programming languages like M are designed for row-at-a-time processing. To integrate SQL with M it is necessary to use cursors to provide access to a particular row. Cursors are positioned references to a result set of a SELECT statement. Cursors allow the programmer to step through a result set one row at a time. Cursor-Related Statements Below is the ESQL statement sequence used to retrieve data for a multiple-row result set. You may refer to this figure as we highlight syntactical elements in the following section. Cursor-Related Statements DECLARE cursor_name[insensitive] [SCROLL] CURSOR FOR[SET ROWSET integer] SELECT statement[order BY order_item_commalist] [{FOR READ ONLY} or {FOR UPDATE}] OPEN cursor_name FETCH [{NEXT or PRIOR or FIRST or LAST or ABSOLUTE integer_value}[from]] cursor_name INTO variable [,variable]... integer_value or RELATIVE CLOSE cursor_name For purposes of this discussion, we confine our comments to the most typical query result set, a multiple-row result set. 22 KB_SQL Programmer s Reference Guide
27 Defining a Cursor Cursors are defined by the DECLARE CURSOR statement. For example: DECLARE C1 CURSOR FOR SELECT NAME, SALARY FROM EMPLOYEES Here we define a cursor named C1. You use C1 to step through the result rows of the query SELECT NAME, SALARY FROM EMPLOYEES one row at a time. After the DECLARE statement, the cursor_name is defined, and the cursor state is inactive or CLOSED. Building the Result Set The result set is theoretically built when the OPEN cursor statement is executed. However, in practice the result is often built as needed, providing blocks of the result set at a time, even as the query continues to process. The net effect is a faster response time and greater concurrence. If the SELECT statement contains references to M variables, the values of these variables are bound at the time when the OPEN statement is executed. A typical OPEN statement appear as: Retrieving Data OPEN C1 After the OPEN statement is executed, the cursor state is activated or OPEN, and it is positioned before the first row in the result set. The FETCH statement is the mechanism by which the cursor is advanced, one row at a time, in the following manner: FETCH C1 INTO :X1, :X2 The FETCH statement moves the column values from the result row to the INTO clause variables X1 and X2. Building on our example, the first row NAME value moves to variable X1, and the first row SALARY value moves to X2. Note that variables referenced in an ESQL statement are known as host variables and are preceded by a colon to distinguish them for the precompiler. Checking for Errors Each successive FETCH statement advances the cursor by one row, retrieving data into the variables. Two obvious potential glitches could derail this process: first, the cursor may be unable to successfully retrieve the data, and second, at some point we can assume the cursor reaches the last row of the result set. As good programming practice would suggest, you should implement a mechanism to monitor cursor activities. Two variables designed especially for the error-checking process are SQLCODE and SQLSTATE. A value of 0 for SQLCODE indicates successful execution, negative values indicate error conditions, and a value of 100 indicates no more rows in the result set. Refer to the section in this chapter titled SQLCODE & SQLSTATE for more information. Closing the Cursor The cursor and the result set may be explicitly deleted by the close statement, or implicitly deleted by a COMMIT or ROLLBACK statement when the transaction is in MANUAL COMMIT mode. The following statement explicitly deletes C1 and its query result set: CLOSE C1 Note: In MANUAL COMMIT mode, any READ or WRITE locks that occur during cursor operations remain in effect until a COMMIT or ROLLBACK statement is executed. Chapter 2: Using the KB_ESQL 23
28 24 KB_SQL Programmer s Reference Guide
29 The table below reflects the parameters, values, and meanings related to cursor states, access modes, and cursor types. Cursor Parameters Parameter Value Meaning Cursor State CLOSED The cursor_name is defined. A result set does not exist. OPEN Access Mode FOR READ ONLY A result set exists for the cursor_name. The cursor CANNOT BE USED IN CONJUNCTION WITH The WHERE CURRENT OF cursor_name clause for positioned DELETE and UPDATE statements. FOR UPDATE If the cursor s SELECT statement is updatable, the cursor may be used for positioned DELETE and UPDATE statements. Fetch Type NEXT The cursor is not scrollable. The only allowable SCROLL [ROWSET] INSENSITIVE [SCROLL] fetch type is NEXT. The cursor is scrollable, allowing all fetch types (FIRST, LAST, NEXT, PRIOR, RELATIVE and ABSOLUTE). The ROWSET value may be used to tune response time. The cursor has an implicit access mode of FOR READ ONLY, and a fetch type of SCROLL. Chapter 2: Using the KB_ESQL 25
30 SQLCODE & SQLSTATE Variables Each executed SQL statement returns basic status information in the variables SQLCODE and SQLSTATE. Although these two variables seem to return redundant information, we believe the best approach is to use both. SQLCODE should always be implemented for basic status checking. (The exception is the DECLARE CURSOR statement which does not set values for the SQLCODE and SQLSTATE variables.) In the event of an error, you may then check SQLSTATE for specific conditions that could require special handling. SQLCODE returns one of three values {-1, 0, 100}; SQLSTATE may return a value called an exception from a set of more than 100 possibilities. Each SQLSTATE exception is five characters long, composed of a two-character class code and three-character subclass code. The subclass code is often 000. While each statement returns only one value for SQLCODE and SQLSTATE, it is possible that additional SQLSTATE exceptions may be recorded. Two statements may be used to provide information on the status of statement execution, shown below. The first GET DIAGNOSTICS statement allows the programmer to determine the number of exceptions recorded; the second statement retrieves individual values on each exception. Diagnostic Statements GET DIAGNOSTICS variable={number or COMMAND_FUNCTION or ROW_COUNT} [,variable={number or COMMAND_FUNCTION or ROW_COUNT}]... GET DIAGNOSTICS EXCEPTION integer variable={returned_sqlstate or MESSAGE_TEXT} [,variable={returned_sqlstate or MESSAGE_TEXT}]... Your application should check the SQLCODE or SQLSTATE variables after each SQL statement to determine if the statement was successful. 26 KB_SQL Programmer s Reference Guide
31 The table below (which continues on the following page) lists the most common SQLCODE and SQLSTATE values for various SQL statements. (All possible SQLSTATE values are contained in the DATA_DICTIONARY table SQL_API_SQLSTATE.) Statement Type SELECT INSERT...SELECT FETCH # Rows Processed SQLCODE SQLSTATE Meaning Data not found. n> Success. SELECT...INTO Data not found Success. n> Cardinality violation. Attempting to use more than one row. positioned DELETE or UPDATE Invalid cursor state Success. DISCONNECT Invalid transaction DECLARE CURSOR all other statements not applicable not applicable not applicable not applicable state. not applicable Success. Chapter 2: Using the KB_ESQL 27
32 # Rows Statement Type Processed any error on any statement not applicable SQLCODE SQLSTATE Meaning -1 -variety- See the SQL_API_SQLSTA TE table for the specific SQLSTATE value Serialization failure. Attempting to access a row in use by other transactions. 28 KB_SQL Programmer s Reference Guide
33 Compiling the Source SQL0S Several utility routines are available to you for compiling the source. They are: SQL0S, EPI^SQL, and EP^SQL. Let s take a closer look at each of these interfaces. Prior to execution, the ESQL source may be compiled into one or more M routines using the SQL0S utility routine. Note: If you intend to modify rows in a table using the INSERT, UPDATE, or DELETE verbs, you must first write or compile a table filer for the table that you want to modify. Refer to the KB_SQL Data Dictionary Guide for more information on table filers. The following input variables are required to successfully compile the source. Input Variables Variable Meaning SQLSRC Source name (routine name, global prefix, or file) SQLRTN Object code routine name SQLTYPE Source type (routine, global, or file) SQLUSER User password (not encrypted) On the next page are examples of the statement structure and sequence for compiling three different types of source files: routine, global, and file. Chapter 2: Using the KB_ESQL 29
34 To compile the routine-type source DESQL into the M routines XESQL*, the following sequence may be executed: Compiling a Routine S SQLSRC="DESQL",SQLRTN="XESQL",SQLUSER="SHARK",SQLTYPE="ROUTINE" D ^SQL0S I SQLCODE<0 F I=1:1:SQLDIAG W!,SQLDIAG(I) To compile the global-type source ^EP("XXX",sequence)=text into the M routines XXX*, execute the following sequence: Compiling a Global S SQLSRC="^EP(""XXX"")",SQLRTN="XXX",SQLUSER="SHARK",SQLTYPE="GLOBAL D ^SQL0S I SQLCODE<0 F I=1:1:SQLDIAG W!,SQLDIAG(I) And finally, to compile the file-type source \TEMP\RTN.EP into the M routines Z*, you would execute the following sequence: Compiling a File S SQLSRC="\TEMP\RTN.EP",SQLRTN="Z",SQLUSER="SHARK",SQLTYPE="FILE" D ^SQL0S I SQLCODE<0 F I=1:1:SQLDIAG W!,SQLDIAG(I) 30 KB_SQL Programmer s Reference Guide
35 Obtaining Compile Status The compiler returns status information in the variable SQLDIAG which takes the following general format. SQLDIAG=number_of_messages SQLDIAG(number)=message_text The table below shows the possible compiler output variables with their values and meanings. Output Variables Variable Value Meaning SQLCODE 0 The compile was successful. -1 The compile encountered an error. SQLDIAG integer The number of compile messages. SQLDIAG(integer) text A compile message. Chapter 2: Using the KB_ESQL 31
36 EPI^SQL This utility routine provides a higher level interface than the SQL0S routine described on the previous pages. Using this approach to compile your source offers the advantages of resource tracking as well as compatibility with the EP ^SQL interactive option which follows. The EPI^SQL routine saves both the project and program definition. In addition, the routine tracks changes to resources for automatic recompilation. To implement this routine, you must first define the variable array SQLX as described below. SQLX("FUNCTION")=operation(COMPILE, DELETE, or SAVE) SQLX("PROJECT")=project name SQLX("PROJECT_DESCRIPTION")=project description SQLX("PROJECT_ROUTINE")=base routine name SQLX("PROGRAM")=program name SQLX("PROGRAM_DESCRIPTION")=program description SQLX("TYPE")=source type (FILE, GLOBAL, or ROUTINE) SQLX("SOURCE")=source location (the format depends on the TYPE) SQLX("OBJECT")=M routine name for compiled ESQL The FUNCTION, PROJECT, and PROGRAM entries are always required. Remaining entries may be defined for COMPILE and SAVE operations. Compile status may be obtained as described previously in Obtaining Compile Status ; SQLCODE should be checked after returning from EPI^SQL. The SQLDIAG variable may be defined after a COMPILE operation. After the SQLX variable array is defined, the entry point to the routine is: D EPI^SQL 32 KB_SQL Programmer s Reference Guide
37 EP^SQL This menu-driven routine provides facilities to compile a new source and recompile and manage existing embedded programs, (EPs). The high-level cataloging capability, illustrated below, helps you establish an organizational framework for your embedded programs. EP^SQL cataloging structure EPs are grouped by projects. Each project has a name, description, and base routine. EPs, in turn, are identified by name, description, source, source location, and optional M routine (object code). Chapter 2: Using the KB_ESQL 33
38 Starting EP^SQL The entry point to this routine is: D EP^SQL The EMBEDDED PROGRAM OPTIONS window appears, with a choice of three different options. For purposes of discussion, we assume this is the initial use of EP^SQL. Therefore, as suggested by the cataloging structure illustration, you typically establish a project definition first through the second option, PROJECT EDIT. In subsequent sessions, you are more likely to make frequent use of the first option, EMBEDDED PROGRAM EDIT. For this reason, it is highlighted as the default. Project Edit Option Add Select the PROJECT EDIT option from the Select Embedded Program Options window and provide the required information. Note that during this procedure you may make modifications and deletions. However, keep in mind the following points as you make any changes. Project definitions must be added before you enter associated EPs. Once a project definition has been added, you may link EPs to that project. You may make project-related additions and insertions at your discretion without implication. 34 KB_SQL Programmer s Reference Guide
39 Edit Edits to project definitions do not impact associated programs. Delete Deleting a project causes associated EPs to be deleted from the organizational framework. Source and object files remain intact. EMBEDDED PROGRAM EDIT Option Add Edit Delete Once the project definition is created, EPs may be linked to a given project. In addition, you may make modifications and deletions to EPs according to the following guidelines. You may make additions to program definitions without implication. You may edit program-related information freely. Although changes may be committed, they do not take effect until the program is actually compiled. You may delete program-related information or delete programs themselves. This last action only removes a program from the organizational framework and does not delete source or object file. Now, select the EMBEDDED PROGRAM EDIT option from the Select Embedded Program Options window. Supply the required values to the series of program-related windows to establish an EP definition. Because we are following a sequence, the Search for Project window appears again as we have seen it when we defined the initial project group name. In this cycle, the project name is derived from the previous PROJECT EDIT option. In subsequent sessions, you will likely use this option as the starting point, in which case you provide an existing project name manually or you may use [list]. RECOMPILE PROGRAMS Option The third and final option from the Select Embedded Program Options window is a RECOMPILE PROGRAMS option that brings up the Recompile Embedded Programs window. This option allows you to recompile one or many previously compiled EPs from one or more projects. You can select all EPs or specific EPs either manually or using wildcards. Taking the second approach allows you to narrow the scope to EPs that reference data dictionary objects that have changed since the original compile. Objects subject to change include tables, view, functions, and domains. Obtaining Procedure Status Chapter 2: Using the KB_ESQL 35
40 At any point in the EP^SQL menu-driven process, you may encounter various error messages if you attempt an illegal action or enter erroneous information. These messages are built into the process to provide general feedback to you regarding the operational status of each procedure you attempt to execute. 36 KB_SQL Programmer s Reference Guide
41 ESQL Examples The following examples illustrate the use of ESQL within M code. These examples were created in a non-m text editor (Microsoft Windows Notepad ) and as a file source-type. Using M routines or globals for the source is equivalent. The relative placement and position of SQL statements depends on both parsing consideration at compile time, and program flow at run time. For example, during the compile time parse, DECLARE statements must precede any references by OPEN, FETCH, or CLOSE statements. During runtime, the program flow must execute a CONNECT statement to establish a connection prior to executing any other SQL statement. The DECLARE statement may precede a CONNECT without consequence because it is nonexecutable. The DISCONNECT must be the last statement executed. Example 1 This example demonstrates the basic structure of an ESQL source. To work with two query result sets, notice that we establish two unique cursors through two separate DECLARE statements. Remember that each transaction may declare one or more cursors that are unique to the transaction. For readability and support purposes, we strongly recommend that all DECLARE statements be at, or near the top of, the embedded source. Returning to the example, we then establish a connection with the CONNECT statement. Chapter 2: Using the KB_ESQL 37
42 Two separate loops, tag L1 and tag L2, comprise the body of the file. Prior to starting each loop, an OPEN statement initializes each cursor. Each loop contains a FETCH statement to retrieve the next result row into the specified M variables. The SQLCODE variable returns one of the following values: -1=failure, 0=success, or 100=no data found. After each loop completes, a CLOSE statement executes to clear the result set and a DISCONNECT statement terminates the connection. ; example1.ep ; &SQL(DECLARE C1 CURSOR FOR SELECT PROJ_NO, PROJECT && FROM PROJECTS) &SQL(DECLARE C2 CURSOR FOR SELECT TASK_NO, TASK, STATUS && FROM TASKS WHERE PROJ_NO=:PNO) ; &SQL(CONNECT TO DEFAULT USER DBA AUTHORIZATION SHARK) I SQLCODE<0 Q ; O1 &SQL(OPEN C1) I SQLCODE<0 G 99 L1 &SQL(FETCH C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G L1 &SQL(CLOSE C1) ; R!,"Select project #: ",PNO I 'PNO G 99 ; L2 &SQL(OPEN C2) &SQL(FETCH C2 INTO :X1, :X2, :X3) I SQLCODE=0 W!,X1,?20,X2,?30,X3 G L2 &SQL(CLOSE C2) W!! G O1 ; 99 &SQL(DISCONNECT DEFAULT) Q 38 KB_SQL Programmer s Reference Guide
43 Note: Example 1 uses the standard ampersand in the first tab piece as a line continuation indicator. However, if the source type is a routine, using this syntax may cause an error, effectively preventing saving the source under certain M implementations. If you encounter this problem, use a different source type or the nonstandard double ampersand in the first command position continuation indicator. Example 2 This example builds on the previous example, adding INSERT, UPDATE, and DELETE statements to change the database as well as COMMIT and ROLLBACK statements. In manual commit mode, this source includes explicit COMMIT statements to commit all previously executed statement or ROLLBACK statements to rollback any pending changes. If a statement fails to execute successfully, any database changes performed by the statement prior to the failure will be rolled back and the SQLCODE variable will be set to -1. Subroutines perform the insert, update, and delete functions. While these statements are positioned after the DISCONNECT statement, the run time program flow executes the subroutines prior to the DISCONNECT statement. The insert and delete sections are relatively straightforward. The insert performs an INSERT...VALUES to add a new row. The delete subroutine utilizes a searched DELETE using the row s primary key in the WHERE clause to delete the specific row. The update section performs a singleton SELECT...INTO to load the old values and a searched UPDATE to save the new values. The singleton SELECT...INTO is the key characteristic of the less-common single-row query. Notice the structural difference from the multiplerow query. Chapter 2: Using the KB_ESQL 39
44 ; example2.ep ; &SQL(CONNECT TO DEFAULT USER SHARK) I SQLCODE<0 Q ; &SQL(declare C1 cursor for select EMP_SSN, NAME && from SQL_TEST.EMPLOYEES) ; 0 &SQL(open C1) 1 &SQL(fetch C1 into :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G 1 &SQL(CLOSE C1) ; 2 R!,"Option (I, U#, D#): ",OPT I OPT="I" G I I OPT?1"U"1.E G U I OPT?1"D"1.E G D I OPT'="" W "???" G 2 R!,"Commit? ",A I $F("Yy",A)>1 G CT &SQL(ROLLBACK WORK) G DC CT DC I &SQL(COMMIT WORK) &SQL(DISCONNECT) Q ; R!,"SSN: ",SSN R!,"Name: ",NAME R!,"Salary: ",SAL R!,"Manager: ",MGR &SQL(INSERT INTO EMPLOYEES && (EMP_SSN, NAME, SALARY, MANAGER) && VALUES (:SSN, :NAME, :SAL, :MGR)) I SQLCODE<0 W!,SQLERR G 0 ; 40 KB_SQL Programmer s Reference Guide
45 U D S ID=$E(OPT,2,999) &SQL(SELECT NAME, SALARY, MANAGER && INTO :NAME, :SAL, :MGR && FROM EMPLOYEES && WHERE EMP_SSN = :ID) I SQLCODE'=0 G 1 W!,"Name: ",NAME R "/",A I A'="" S NAME=A W!,"Salary: ",SAL R "/",A I A'="" S SAL=A W!,"Manager: ",MGR R "/",A I A'="" S MGR=A &SQL(UPDATE EMPLOYEES SET NAME=:NAME, && SALARY=:SAL, MANAGER=:MGR && WHERE EMP_SSN = :ID) I SQLCODE<0 W!,SQLERR G 0 ; S ID=$E(OPT,2,999) &SQL(DELETE EMPLOYEES WHERE EMP_SSN=:ID) I SQLCODE<0 W!,SQLERR G 0 Note: The nonstandard double ampersand is used in the first command position as a line continuation indicator. Example 3 This example utilizes two connections to demonstrate several features. First, notice that the DECLARE statement is not linked to a connection. Also, the source establishes two connections, A and B, that each open a distinct copy of one cursor, C1. The SET CONNECTION statement switches context between the two concurrent connections. Two points to remember are that cursor names must be unique with a connection at run time and cursor names must be unique within the source at compile time. The DISCONNECT ALL statement disconnects both connections. Chapter 2: Using the KB_ESQL 41
46 ; example3.ep ; &SQL(DECLARE C1 CURSOR FOR SELECT PROJECT FROM PROJECTS) ; &SQL(CONNECT TO DEFAULT AS A USER SHARK) &SQL(OPEN C1) ; &SQL(CONNECT to DEFAULT AS B USER SHARK) &SQL(OPEN C1) ; &SQL(SET CONNECTION A) &SQL(FETCH C1 INTO :X1) W!,X1 &SQL(SET CONNECTION B) &SQL(FETCH C1 INTO :X1) W!,X1 &SQL(SET CONNECTION A) &SQL(FETCH C1 INTO :X1) W!,X1 &SQL(SET CONNECTION B) &SQL(FETCH C1 INTO :X1) W!,X1 &SQL(DISCONNECT ALL) Q It is important to remember that using multiple connections has concurrency implications. In this example, both connections perform only READS, so the FETCH statements do not receive any concurrency violations. However, if one of the connections performs an update on a table row, the other connections would be unable to access the updated row. 42 KB_SQL Programmer s Reference Guide
47 Example 4 Here we demonstrate a searched DELETE. If a failure occurs during a searched DELETE, no employee rows are deleted, even if the failure occurs after some of the result rows have been processed. ; example4.ep ; &SQL(connect to DEFAULT user SHARK) &SQL(delete from employees) &SQL(commit work ) &SQL(disconnect) Q Since this example updates the database, it is necessary to execute either a COMMIT or ROLLBACK statement. Example 5 Unlike Example 4, this example illustrates a positioned DELETE, deleting some rows and displaying any rows it is unable to delete. ; example5.ep ; &SQL(connect to DEFAULT user SHARK) &SQL(declare C1 cursor for select name & from employees where salary > 15 for update) ; &SQL(open C1) 1 &SQL(fetch C1 into :X1) I SQLCODE=100 G 2 I SQLCODE<0 W!,"Unable to delete ",X1," due to ",SQLSTATE E &SQL(delete from employees where current of C1) G 1 2 &SQL(commit) &SQL(disconnect) Q Chapter 2: Using the KB_ESQL 43
48 Example 6 This example demonstrates a searched UPDATE. ; example6.ep ; &SQL(connect to DEFAULT user SHARK) &SQL(update employees set salary = salary * 1.1 & where salary < 18) &SQL(commit) &SQL(disconnect) Q Example 7 Following is a positioned UPDATE example. & ; example7.ep ; &SQL(connect to DEFAULT user SHARK) &SQL(declare C1 cursor for select name, salary from employees where salary > 15 for update) &SQL(open C1) 1 &SQL(fetch C1 into :X1, :X2) I SQLCODE'=0 G 2 &SQL(update employees set salary = salary * 1.1 & where current of C1) G 1 2 &SQL(close C1) &SQL(commit) &SQL(disconnect) Q 44 KB_SQL Programmer s Reference Guide
49 Example 8 Here you see a demonstration of most of the FETCH options for a scrollable cursor. To use these options, the DECLARE statement must specify the SCROLL option. ; example8.ep ; &SQL(CONNECT TO DEFAULT USER SHARK) &SQL(DECLARE C1 SCROLL CURSOR FOR && SELECT PROJ_NO, PROJECT && FROM PROJECTS) ; O1 &SQL(OPEN C1) W!,"next" L1 &SQL(FETCH NEXT C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G L1 R!,Z W!,"prior" L2 &SQL(FETCH PRIOR C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G L2 R!,Z W!,"first" &SQL(FETCH FIRST C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 R!,Z W!,"relative 1" L4 &SQL(FETCH RELATIVE 1 FROM C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G L4 R!,Z W!,"last" &SQL(FETCH LAST C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 R!,Z W!,"relative -1" L6 &SQL(FETCH RELATIVE -1 FROM C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 G L6 R!,Z W!,"absolute +1" S I=1 L7 &SQL(FETCH ABSOLUTE :I C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 S I=I+1 G L7 R!,Z W!,"absolute -1" S I=-1 Chapter 2: Using the KB_ESQL 45
50 L8 &SQL(FETCH ABSOLUTE :I C1 INTO :X1, :X2) I SQLCODE=0 W!,X1,?20,X2 S I=I-1 G L8 ; &SQL(CLOSE C1) &SQL(DISCONNECT DEFAULT) Q 46 KB_SQL Programmer s Reference Guide
51 Chapter 3 Using the KB_SQL API KB Systems application programming interface, KB_SQL API, supports the development of applications, custom servers, gateways, and other modules that interface with database systems defined in the KB_SQL data dictionary. From a programming point of view, an API is an SQL-software interface comprised of functions that provide intercommunication between a data source and an application. This approach is highly suited to ad hoc, interactive processing. The KB_SQL API has two versions: one for the client, which we refer to as the KB_SQL Client API, and one for the server, the KB_SQL Server API. The function names are identical regardless of whether they are used by the Client API or the Server API. The difference between the two is the relationship that each one has with the KB_SQL Engine. The Client API connects to the Server API over the network. The Server API speaks directly to the KB_SQL Engine. In this chapter, we examine several general implementation scenarios. They show you how the Client and Server APIs come to play depending on how you are accessing the KB_SQL Engine. Then we focus on the information you need to develop M applications using the KB_SQL API. Chapter 3: Using the KB_SQL API 47
52 Highlights of this chapter include: a framework for implementation, including typical usage scenarios; the KB_SQL API Function Summary Table; a reference section containing an alphabetic listing of each KB_SQL API function complete with descriptions and illustrations. Note: When installing KB_SQL, you can choose to load API sample routines. Each routine demonstrates the usage of an API function. Because the KB_SQL API is modeled on Microsoft s Open Database Connectivity application programming interface (ODBC API), we strongly recommend ODBC 2.0 Programmer s Reference and SDK Guide from Microsoft. This guide provides excellent detailed coverage of the ODBC interface as an emerging industry standard. Attention MSE programmers: You should also refer to Appendix B which discusses the MSE syntax of the API functions. 48 KB_SQL Programmer s Reference Guide
53 A Framework for Implementation In order to use the KB_SQL API, you need to be aware of some fundamental network and SQL conformance standards that form the framework for implementing our product. The authoritative standard adhered to in development of the API is Microsoft s ODBC interface. The strategy is simple: Using standard SQL, applications access data in database management systems no matter what the data looks like or where it resides. The payoff is maximum interoperability. Network Standards The KB_SQL API supports a multiple-tier driver as defined by ODBC. A driver is a dynamic-link library (DLL) that implements API function calls and interacts with a data source. The data source typically resides on a server in another system. There are many multiple-tier configurations (including a gateway process through which SQL requests may be passed) and any number of these may appear in a single network. However, all are transparent from the application s point of view. The strength of the ODBC is its interoperability. When you develop an ODBC-compliant application, you need not target a specific data source because you can add drivers to the application later for accessing specific data sources. To deploy the KB_SQL API in a network, you will need TCP/IP access as a requirement for both the client and server processes. For more information on tested configurations, see Appendix A in KB Systems KB_SQL ODBC Driver Install Guide. Chapter 3: Using the KB_SQL API 49
54 Software Standards The KB_SQL API is based on the framework provided by the SQL Access Group (SAG) and the Open Database Connectivity (ODBC) specification by Microsoft. Specifically, the API conforms to Core and Level 1 ODBC specifications for API performance and meets the Minimum and Core levels defined for SQL grammar. A Conceptual View of the KB_SQL API The KB_SQL API is extremely versatile and can accommodate a variety of situations; you might develop in C or M, and you may or may not require network access. Ultimately, you can design your application to access any data source using the API and appropriate drivers. Let s take a look at some typical scenarios beginning on the next page. 50 KB_SQL Programmer s Reference Guide
55 Accessing the KB_SQL Engine from M programs M Reporting Tools M MSE Server API shell (SQLOS) KB_SQL Server API KB_SQL Engine Relational Data Dictionary M Data In this example, M programs call KB_SQL Server API functions to access the KB_SQL Engine. These functions perform the same operations as their ODBC versions. The distinction in the structure of each function is a result of the inherent differences between the C and M languages. The SQLOS program serves as an interface to the Server API. Note that this configuration is host-based as opposed to client/server. Providing application development for this configuration significantly extends existing capabilities. Guidelines M programming experience Experience developing host-based applications accessed via terminals Chapter 3: Using the KB_SQL API 51
56 Accessing the KB_SQL Engine from C programs Non-Windows environment M Reporting Tools C KB_SQL Client API Network API TCP/IP Network API KB_SQL Server API KB_SQL Engine Relational Data Dictionary M Data In UNIX and other non-windows environment, the programmer can access the KB_SQL Client API by including an object library with the application. By linking this library with your application, you can access the Server API. For example, the object library can be used to develop a gateway from a non-m database system. This method requires C programming expertise. Note that this method communicates with the Server API over TCP/IP. As a side note, the sendside of the Network API is written in C; the receive side is written in M. Guidelines C programming experience Experience developing applications to access data from UNIX workstations or gateways 52 KB_SQL Programmer s Reference Guide
57 Accessing the KB_SQL Engine from Windows via Dynamic Link Library (DLL) M Reporting Tools C Visual Basic KB_SQL Client API Network API TCP/IP Network API KB_SQL Server API KB_SQL Engine Relational Data Dictionary M Data With this approach, the KB_SQL Client API is accessed as a dynamic link library (DLL) from Windows via C or Visual Basic. A Windows programming paradigm, the DLL allows one copy of a set of functions to be accessed by multiple applications. In Visual Basic, the Server API is accessed directly through the KB_SQL ODBC Driver. The ODBC Driver Manager is not involved. Again, TCP/IP provides your connection to the Server API. Guidelines Experience with Windows programming, DLLs, Windows applications, and gateways Chapter 3: Using the KB_SQL API 53
58 Accessing the KB_SQL Engine or other data sources from Windows via ODBC Manager M Data C Visual Basic ODBC Manager KB_SQL Client API ODBC Driver Network API TCP/IP Network API KB_SQL Server API M Reporting Tools KB_SQL Engine Relational Data Dictionary M Data Unlike the previous approach that provides access only to the KB_SQL Engine, this method furnishes access to virtually any data source for which you have ODBC drivers. (As you may have guessed, this scenario represents the ultimate goal of ODBC.) The KB_SQL Engine may also still be accessed via the ODBC Manager from C or Visual Basic. Guidelines Experience with Windows programming, DLLs, Windows applications, and gateways 54 KB_SQL Programmer s Reference Guide
59 Features of the KB_SQL API Prepared and Direct Execution The KB_SQL API supports two methods of statement execution: the direct method (using the SQLExecDirect function) and the prepare/execute method (using the SQLPrepare and SQLExecute functions). When an SQL statement is prepared it is sent to the server, parsed, and optimized. This is the ideal method for statements that are executed repeatedly, each time with different parameter values. An application should prepare a statement for execution if any of the following are true: The application will repeatedly execute the statement. The application needs information about the result set before executing the statement. An application can execute a statement directly if both are true: The application will execute the statement only once. The application does not need information about the result set before executing the statement. Chapter 3: Using the KB_SQL API 55
60 Parameter Markers Parameter markers in a prepared SQL statement are placeholders for parameter values that are supplied by an application. Parameter markers are delimited by question marks. Using parameter markers in an SQL statement lets you execute the statement repeatedly with different values. This is a more efficient alternative to coding literal values in an application, and changing the application each time the parameters change. To use parameter markers, the application must first call the SQLBindParameter function to bind a storage area to a parameter marker. Then the application must place the parameter s value in the storage location. Examples of using parameter markers are found in the Stored Procedures section of this chapter. ODBC Extensions Catalog Functions Catalog functions return information about a data source s data dictionary, such as the names of the tables and the columns and the privileges associated with them. The information is returned as a result set. The application retrieves the result set by calling SQLBindCol and SQLFetch. Descriptions for the following catalog functions can be found in the KB_SQL API Function Summary section of this chapter. 56 KB_SQL Programmer s Reference Guide
61 SQLTables SQL TablePrivileges SQLColumns SQLColumnPrivileges SQLPrimaryKeys SQLForeignKeys SQLSpecialColumns SQLStatistics SQLProcedures SQLProcedureColumns Parameter Data Functions An application can send parameters at statement execution time by calling the following functions: SQLBindParameter specifies the SQL data type of the parameters and reserves storage location for each parameter. SQLPutData sends data value for the parameter to the driver. Using data-at-execution parameters is useful for applications handling long data. SQL Extensions KB_SQL API supports several ODBC SQL extensions: the representation of date and time literals the syntax for scalar functions LIKE predicate escape characters stored procedures Chapter 3: Using the KB_SQL API 57
62 These extensions provide essential functionality that is shared by most DBMSs. However, because the syntax required by the DBMSs varies, ODBC uses a syntactical notation called the escape clause. The escape clause consists of a pair of curly braces {} which surround the standard SQL syntax form and a one- or two-character token which specifies the type of clause. Date, Time, and Timestamp Data KB_SQL API supports the DATE, TIME, and TIMESTAMP (a combined form of DATE and TIME) data types. The shorthand escape clause syntax for these data types is: {d 'value'} {t 'value'} {ts 'value'} Scalar Functions Scalar (or row) functions operate on a single value. They include functions that compute absolute value or length, format a date or time, or return a substring. The on-line query SQL_FUNCTION_LIST provides a complete list of the KB_SQL API scalar functions and their syntax. 58 KB_SQL Programmer s Reference Guide
63 Wildcards (Search Pattern Escape Characters) ODBC supports wildcards using the underscore character (_) for single-character replacement and the percent sign (%) for multiple-character replacement. A word of caution is in order with respect to the use of wildcards, particularly in relation to the various catalog functions where the SQL_IDENTIFIER can include the underscore character. When you want to use a metacharacter as a literal and not as a wildcard, you must precede the metacharacter with the search pattern escape character (the default is the backward slash). For example, to obtain all columns for the LAB_PATIENT table where the underscore is a literal in the SQL_IDENTIFIER, you send the table name parameter as: LAB\_PATIENT Using the escape character prevents the engine from interpreting the underscore as a wildcard, thus avoiding retrieving columns for tables that could be named LABaTABLE, LABbTABLE, and so forth. Chapter 3: Using the KB_SQL API 59
64 LIKE Predicate Escape Characters The support of the LIKE predicate escape clause allows for searches to include metacharacters. In a LIKE predicate, the underscore character (_) is used for single-character replacement and the percent sign (%) is used for multiple-character replacement. The percent and underscore characters can be used as literals in a LIKE predicate by preceding them with an escape character. The escape clause for ODBC queries looks like: {escape escape-character } Example {escape \ } Example Items aab aad aa_123 abc aac aazz aa_245 ade SQL without escape character select code from item_master where code like aa_% Returns aab aad aa_123 aac aazz aa_ KB_SQL Programmer s Reference Guide
65 SQL with escape character select code from item_master where code like aa\_% Returns aa_123 aa_245 Notes The default LIKE escape character is '\'. The escape character can be specified using the escape clause syntax: {escape '\'}. The SQL Editor supports the feature, but does not use the {} syntax. ODBC Example select code from item_master where code like aa\_% {escape \ } SQL Editor Example select code from item_master where code like aa\_% escape \ Chapter 3: Using the KB_SQL API 61
66 Stored Procedures The KB_SQL Server API supports the use of stored procedures as a collection of precompiled SQL statements residing on the server. An application can call a procedure in place of an SQL statement. Stored procedures help to increase performance and consistency when performing repetitive tasks because they are compiled the first time they are executed. When executed again, subsequent run time is much shorter than for the equivalent set of stand-alone statements. Stored procedures simplify application development because you can repeatedly change them without modifying and compiling the application. Stored procedures can be created for permanent or temporary use. Temporary Stored Procedures KB_SQL creates a stored procedure for every set of SQL statements that are submitted from client applications. These procedures are available for use by all server queries for as long as the procedure is in the buffer of stored queries on the server. The query text is stored under a name where nnn represents the number of the query relative to the number of stored queries allowed. IMPORTANT: DBA users can copy the definition of a server query into a new query, but server queries should not be modified in any way. 62 KB_SQL Programmer s Reference Guide
67 Permanent Stored Procedures KB_SQL can make any stored procedure permanent so that it will always be available regardless of the size of the stored query buffer. This type of procedure is desirable for use within custom applications. It allows the application to be developed independently of the server-side SQL statements. Only the calling parameters and result set must stay constant. Otherwise, the stored procedure can be modified as needed without affecting the client application. Steps to create a permanent stored procedure 1. Create a query that returns a result set in the ODBC format. SET CLIENT=ODBC This parameter is automatically inserted into SQL statement buffers sent from client applications. Setting STORED_PROCEDURE implicitly sets the CLIENT type. 2. Indicate that the procedure is permanent. SET STORED_PROCEDURE=YES This makes the query take on the characteristics of a stored procedure until you remove the setting. This query will appear in the result set for the SQLProcedures function. 3. Give names to input parameters (optional). SET PARAMETERS='name,city,state' You can choose to specify names for parameter markers in any query. This acts as documentation, and is accessible in the result of the SQLProcedureColumns function. Note that setting PARAMETERS implicitly sets the CLIENT type and STORED_PROCEDURE indicators. Chapter 3: Using the KB_SQL API 63
68 Running a stored procedure Replace the SQL statements in your application with the ODBC escape clause syntax for calling a stored procedure. Syntax {call procedure-name[(parameter[,parameter...])]} Example Replace: Select Name, Position, Salary, Comments From Employees Where EmpDept =? With: {call DeptEmps(?)} The? represents a parameter marker, in this case used to receive the department identifier. Rules Users must have SELECT privileges on the stored procedure query. The stored procedure query must be compiled in order to show in SQLProcedures, SQLProcedureColumns, or to be executed. The server will require that the number of parameters in the reference must match the number in the procedure definition. 64 KB_SQL Programmer s Reference Guide
69 Parameter values can be specified as all literals, or all parameter markers, but not a mix. For example: Legal Illegal {call xyzproc(?,?)} {call xyzproc('abc','123') {call xyzproc(?)} -- 2 parameters required {call xyzproc('abc',?)} -- Cannot mix types If the parameters or the result set changes, you would have to respecify your application. Otherwise, changes can be made to the logic on the server side by editing and recompiling the query. Testing stored procedures You may test stored procedures by using the sample routine APIM13. This program will let you enter the ODBC syntax for calling the procedure. Example >{call xyzproc(?,?)} >go Use the Execute SQL option in MSQuery to invoke a stored procedure. Note that this interface does not have a mechanism for collecting input parameters, so you must supply the values as string literals. Example Error Processing {call xyzproc('abc','123')} Implementation of error processing is the responsibility of the application developer. Each and every function should invoke a fundamental error process whereby return codes are checked for success or failure of the function call. The following example depicts the generic error processing module. SQLCODE = $$APIfunction(parm1, parm2,..., parmn) If SQLCODE <> 0 Do ErrorProcessing If SQLCODE < 0 Exit Error processing typically handles the following values for SQLCODE. SQLCODE ODBC Value Description 0 SQL_SUCCESS Function completed successfully. Chapter 3: Using the KB_SQL API 65
70 -1 SQL_ERROR Function failed. -2 SQL_INVALID_ Network failure. HANDLE 1 SQL_SUCCESS_ WITH_INFO Function completed successfully with a nonfatal error. 99 SQL_NEED_DATA The application needs to send parameter data values. 100 SQL_NO_DATA_ FOUND No data found (or End-of-Data) Not all functions return all codes. But all API functions return some value for SQLCODE. This value will be non-zero if an error occurred. In the case of a non-zero return code, error information is stored and can be retrieved using the SQLError function. Most queries are processed by following a successful SQLPrepare and SQLExecute function with a set of functions to process the set of rows returned by the query; the result set. Certain classes of queries do not return a result set. These are typically DDL, DCL, and DML (insert, update, delete) queries. These queries require special handling. For example, a DELETE command does not produce a set of result rows; it simply deletes zero or more rows. There may be informational messages stored that can be retrieved using SQLError. These messages might look like '12 rows deleted'. Note that the number of rows affected can be determined by using the SQLRowCount function. It is preferable to check for a non-zero SQLCODE on the SQLExecute function than to base any logic on how many rows were affected. A perfectly valid query may not affect any rows, while a flawed query could affect some rows, but in the wrong way. The diagram on the next page reflects a specific instance of the error-processing module as it relates to the execution of a parameterized query. Note: Generally speaking, a parameter is a value or option that refines the output of a process. In this process, SQLPrepare sends an SQL statement to a data source for preparation. Depending on the statement, the application may embed parameter markers that are delimited by a question mark (?) into the SQL string in corresponding positions. SQLBindParameter specifies the language-specific ODBC data type as well as the SQL data type of the parameter and reserves storage location and length in memory for each parameter in the SQL statement. The application assigns data values to each parameter and calls SQLExecute to execute the statement. SQLExecute processes the prepared statement using the values of the parameter marker variables. 66 KB_SQL Programmer s Reference Guide
71 Error Processing in Parameterized Query Chapter 3: Using the KB_SQL API 67
72 In our example, if the error condition 99 - need data occurs, the SQL statement immediately enters a loop construct in which SQLPutData permits the application to send data for a parameter at statement execution time. Only when a one-toone correspondence exists between data and parameter markers will continuation of normal processing be possible. Again, as a practical matter the illustration depicts a single instance of the error process, checking for a single return code. In reality, error processing occurs after each and every function call for a variety of return codes that are specific to the nature of the function. 68 KB_SQL Programmer s Reference Guide
73 On-line Support A number of on-line sample source routines are available to you to supplement this guide. You can choose to load them when installing KB_SQL. The table below lists some of the on-line queries and the functions they demonstrate. Query Name Associated Functions SQL_API_DATATYPE SQLBindParameter; SQLGetTypeInfo SQL_API_SQLSTATE SQLError SQL_API_CONNECT_OPTION SQLGetConnectOption; SQLSetConnectOption SQL_API_INFO_OPTION SQLGetInfo SQL_API_STMT_OPTION SQLGetStmtOption; SQLSetStmtOption Default Data Types The KB_SQL API supports the following default data types: Date Type API Format Example SQL Editor Format Date yyyy-mm-dd Mar. 18, 1995 Time hh:mm:ss 20:15:00 8:15 PM Timestamp yyyy-mm-dd :15:00: :15:00:00 hh:mm:ss:ff * Flag 0 or 1 0=No/Off/False 1=Yes/On/True 0=No/Off/False 1=Yes/On/True * FF stands for fractional seconds which are not supported by M. Chapter 3: Using the KB_SQL API 69
74 KB_SQL API Function Summary Below are the KB_SQL API functions, grouped by type of task, including a brief description of the purpose of each function. For more information about the syntax and semantics of each function, consult the alphabetical reference section of this chapter. Task Function Name Purpose SQLAllocEnv Connecting to a data source Obtaining information about a driver and data source Setting and retrieving driver options SQLAllocConnect SQLConnect SQLDriverConnect * SQLGetInfo SQLGetTypeInfo SQLGetFunctions SQLSetConnectOption Obtains an environment handle. An environment handle can be used for one or more connections. Obtains a connection handle. A connection handle can be used for one or more statements. Connects to a specific driver by data source name, user ID, and password. Connects to a specific driver by connection string or invokes driver display connection dialog boxes. Returns information about a specific driver and data source. Returns information about supported data types. Returns supported driver functions. Sets a connection option. SQLGetConnectOption Returns the value of a connection option. SQLSetStmtOption Sets a statement option. SQLGetStmtOption Returns the value of a statement option. * Supported by Windows ODBC driver only. Preparing SQL requests KBSStatement SQLAllocStmt SQLPrepare SQLBindParameter SQLGetCursorName Inserts partial SQL statements. Allocates a statement handle. Prepares an SQL statement for later execution. Assigns storage for a parameter in an SQL statement. Returns the cursor name associated with a statement handle. Specifies a cursor name. Specifies cursor behavior. SQLSetCursorName SQLSetScrollOptions * Submitting requests SQLDescribeParam Returns the description of a parameter marker associated with a prepared SQL statement. SQLExecute SQLExecDirect SQLNativeSql Executes a prepared statement. Executes a statement. Returns the SQL command text as 70 KB_SQL Programmer s Reference Guide
75 Task Function Name Purpose translated by the server. SQLNumParams Returns the number of parameters in an SQL statement. SQLParamData * Used in conjunction with SQLPutData to supply parameter data at execution time. SQLPutData Send part or all of a data value for a parameter. * Supported by Windows ODBC driver only. Retrieving Results and information about results Retrieving Results and information about results (continued) Obtaining information about the data source s system tables (catalog functions) Terminating a statement SQLRowCount SQLNumResultCols SQLDescribeCol SQLColAttributes SQLBindCol SQLFetch SQLGetData SQLError SQLColumnPrivileges SQLColumns SQLForeignKeys SQLPrimaryKeys SQLProcedures SQLSpecialColumns SQLStatistics SQLTablePrivileges SQLTables SQLFreeStmt Returns the number of rows affected by an insert, update, or delete request. Returns the number of columns in the result set. Describes a column in the result set. Describes attributes of a column in the result set. Assigns storage for a result column and specifies the data type. Returns a result row. Returns a specific column value from a statement cursor. Returns additional error or status information. Returns a list of columns and associated privileges for the specified table. Returns a list of column names in specified tables. Returns information about the foreign keys for a table. Returns the list of column name(s) that comprise the primary key for a table. Returns the list of procedure names stored in a specific data source. Returns information about the optimal set of columns that uniquely identifies a row in a specified table, or the columns that are automatically updated when any value in the row is updated by a transaction. Returns statistics about a single table and the list of indexes associated with the table. Returns a list of tables and the privileges associated with each table. Returns the list of table names stored in a specific data source. Ends statement processing and closes any associated cursors, discarding pending Chapter 3: Using the KB_SQL API 71
76 Terminating a connection Task Function Name Purpose results, and optionally, frees all resources associated with the statement handle. SQLCancel Cancels an SQL statement. SQLTransact SQLDisconnect SQLFreeConnect SQLFreeEnv Commits or rolls back a transaction. Closes the connection. Releases the connection handle. Releases the environment handle. KB_SQL API Function Reference The following pages describe each KB_ SQL API function in alphabetic order. Each function is defined as an M programming language function. Descriptions may include some or all of the following items: Arguments Returns Syntax Examples Notes Options Result set Related functions 72 KB_SQL Programmer s Reference Guide
77 A Word about Variable Names Variable names shown in the following functions are used for illustrative purposes only. KB_SQL reserves the letters SQL for use as the first three letters of our variable names. We suggest you use variable name conventions suitable to your operation. Chapter 3: Using the KB_SQL API 73
78 KBSStatement Inserts part of an SQL command into the SQL input buffer. Arguments Statement handle SQL command [SQLHSTMT] [SQLTEXT] Returns Return code [SQLCODE] Syntax Example Notes SQLCODE=$$KS^SQLOS(SQLHSTMT,SQLTEXT) S SQLCODE=$$KS^SQLOS(SQLHSTMT, SQLTEXT) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function can be used to insert partial SQL commands to the SQL server. Its purpose is to support SQLPrepare. Splits should occur on a space or punctuation character. A special subroutine, SPLIT^SQLK1, may be invoked to automate this process 74 KB_SQL Programmer s Reference Guide
79 For example, suppose X contains a long line (375 characters), thus exceeding the limitation of 255 bytes M imposes on strings. X SELECT COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15, COL16, COL17, COL18, COL19, COL20, COL21, COL22, COL23, COL24, COL25, COL26, COL27, COL28, COL29, COL30, COL31, COL32, COL33, COL34, COL35, COL36, COL37, COL38, COL39, COL40 FROM TABLE WHERE COL1 = 100 AND (COL2 = 200) ORDER BY COL3 You can invoke the SPLIT^SQLK1 subroutine to decompose the line into smaller segments. It attempts to split first on a space boundary, followed by one of several punctuation characters. >D SPLIT^SQLK1 X(0) 7 X(1) SELECT COL1, COL2, COL3, COL4, COL5, COL6, COL7, X(2) COL8, COL9, COL10, COL11, COL12, COL13, COL14, X(3) COL15, COL16, COL17, COL18, COL19, COL20, COL21, X(4) COL22, COL23, COL24, COL25, COL26, COL27, COL28, X(5) COL29, COL30, COL31, COL32, COL33, COL34, COL35, X(6) COL36, COL37, COL38, COL39, COL40 FROM TABLE WHERE X(7) COL1 = 100 AND (COL2 = 200) ORDER BY COL3 Now, you simply call KBSStatement for each entry in X(n). Chapter 3: Using the KB_SQL API 75
80 When using this function, you must still invoke the SQLPrepare function. Typically, this invocation occurs in the last segment of the SQL command text. For example, assume X is very long. Below you see a sequence of point of entry through the call to SQLPrepare. typical statements from the subroutine s >D SPLIT^SQLK1 >S N=X(0) Note: X(0) contains the count of elements. >F I=1:1:N-1 DO >. SQLCODE=$$KS^SQLOS(SQLHSTMT,X(I)) I SQLCODE'=0 G Error >S SQLCODE=$$P^SQLOS(SQLHSTMT,X(N)) Note: If you perform your own split logic, make sure you adhere to subroutine. all of the rules observed by the SPLIT^SQLKI 76 KB_SQL Programmer s Reference Guide
81 SQLAllocConnect Allocates a connection handle. Arguments Environment handle [SQLHENV] Returns Syntax Example Notes Return code [SQLCODE] Connection handle [SQLHDBC] SQLCODE=$$AC^SQLOS(SQLHENV,.SQLHDBC) S SQLCODE=$$AC^SQLOS(SQLHENV,.SQLHDBC) I SQLCODE'=0 D Error Q This function requires a valid environment handle (SQLHENV). A valid connection handle (SQLHDBC) is returned by the function. You need a connection handle to store information about the connection. A connection can contain multiple statement handles. Chapter 3: Using the KB_SQL API 77
82 SQLAllocEnv Arguments Returns Syntax Allocates an environment handle. None Example Notes Return code [SQLCODE] Environment handle [SQLHENV] SQLCODE=$$AE^SQLOS(.SQLHENV) S SQLCODE=$$AE^SQLOS(.SQLHENV) I SQLCODE'=0 D Error Q A valid environment handle (SQLHENV) is returned by the function. You need an environment handle to store information about the environment. An environment can contain multiple connection handles. 78 KB_SQL Programmer s Reference Guide
83 SQLAllocStmt Allocates a statement handle. Arguments Connection handle [SQLHDBC] Returns Return code [SQLCODE] Statement handle [SQLHSTMT] Syntax Example Notes SQLCODE=$$AS^SQLOS(SQLHDBC,.SQLHSTMT) S SQLCODE=$$AS^SQLOS(SQLHDBC,.SQLHSTMT) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function requires a valid connection handle (SQLHDBC). A valid statement handle (SQLHSTMT) is returned by the function. You need a statement handle to prepare and execute an SQL command. Chapter 3: Using the KB_SQL API 79
84 SQLBindCol Binds a select expression to a host variable. Arguments Statement handle [SQLHSTMT] Column sequence [SQLCOL] Column name [NAME] Returns Return code [SQLCODE] Syntax Example SQLCODE=$$BC^SQLOS(SQLHSTMT,SQLCOL,NAME) S SQLCODE=$$BC^SQLOS(SQLHSTMT,2,"CNAME") I SQLCODE'=0 D Error G:SQLCODE<0 Discon 80 KB_SQL Programmer s Reference Guide
85 Notes This function cannot occur prior to statement preparation. The SQLFetch function places data into the host variable. If a column sequence is 0, all columns in the array are bound by the name parameter and sequenced by the actual column number. Consider $$BC^SQLOS(SQLHSTMT, 0, "XYZ"). Each fetch operation returns the local array XYZ populated with all columns from the result set. For example, SELECT NAME, SEX, DOB FROM PATIENT yields: XYZ(1) = name XYZ(2) = sex XYZ(3) = dob Chapter 3: Using the KB_SQL API 81
86 SQLBindParameter Declares the data type for a parameter. Arguments Statement handle Parameter sequence ODBC data type Returns Return code [SQLHSTMT] [SEQ] [TYPE] [SQLCODE] Syntax Example Notes SQLCODE=$$BP^SQLOS(SQLHSTMT,SEQ,TYPE) S SQLCODE=$$BP^SQLOS(SQLHSTMT,1,1) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function is equivalent to the SQLSetParam function from ODBC V1.0. The data type is the numeric value of the ODBC data type. Run the on-line query SQL_API_DATATYPE to generate a list of supported data types. 82 KB_SQL Programmer s Reference Guide
87 SQLCancel Cancels a statement. Arguments Statement handle Returns Return code [SQLHSTMT] [SQLCODE] Syntax Example Notes SQLCODE=$$CS^SQLOS(SQLHSTMT) S SQLCODE=$$CS^SQLOS(SQLHSTMT) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function is primarily useful when asynchronous processing is enabled. Chapter 3: Using the KB_SQL API 83
88 SQLColAttributes Arguments Returns Syntax Example Notes Returns information on a particular feature of a column. Statement handle [SQLHSTMT] Column sequence [SQLCOL] Descriptor type [SQLDESC] Return code [SQLCODE] Descriptor value [VALUE] SQLCODE=$$CA^SQLOS(SQLHSTMT,SQLCOL,SQLDESC,.VALUE) S SQLCODE=$$CA^SQLOS(SQLHSTMT,3,1,.NAME) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function provides more information than SQLDescribeCol. 84 KB_SQL Programmer s Reference Guide
89 See SQLColAttributes Descriptor Code SQL_COLUMN_COUNT 0 SQL_COLUMN_NAME 1 SQL_COLUMN_TYPE 2 SQL_COLUMN_LENGTH 3 SQL_COLUMN_PRECISION 4 SQL_COLUMN_SCALE 5 SQL_COLUMN_DISPLAY_SIZE 6 SQL_COLUMN_UNSIGNED 8 SQL_COLUMN_MONEY 9 SQL_COLUMN_UPDATABLE 10 SQL_COLUMN_AUTO_INCREMENT 11 SQL_COLUMN_CASE_SENSITIVE 12 SQL_COLUMN_SEARCHABLE 13 SQL_COLUMN_TYPE_NAME 14 SQL_COLUMN_TABLE_NAME 15 SQL_COLUMN_OWNER_NAME 16 SQL_COLUMN_QUALIFIER_NAME 17 SQL_COLUMN_COLUMN_LABEL 18 Chapter 3: Using the KB_SQL API 85
90 SQLColumnPrivileges SQLColumnPrivileges returns a list of columns and associated privileges for the specified table. Note: This function is implemented but not yet supported. Arguments Statement handle [SQLHSTMT] TableQualifier [QUAL] TableOwner [OWNER] TableName [TABLE] ColumnName [COLUMN] Returns Return code [SQLCODE] Syntax S SQLCODE=$$CM^SQLOS(SQLHSTMT,QUAL,OWNER,TABLE,COLUMN) Notes The ColumnName argument accepts a search pattern. This function will return an empty result set until the product supports column-level privileges within the KB_SQL Engine. 86 KB_SQL Programmer s Reference Guide
91 Result Set SQLColumnPrivileges returns the results as a standard result set, ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE. The following table lists the columns in the result set. Column Name TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME GRANTOR GRANTEE PRIVILEGE SELECT INSERT UPDATE REFERENCES IS_GRANTABLE Description Table qualifier identifier. Table owner identifier. Table identifier. Column identifier. User who granted the privilege. User to whom the privilege was granted. Identifies the column privilege. The grantee is permitted to retrieve data for the column. The grantee is permitted to provide data for the column in new rows that are inserted into the associated table. The grantee is permitted to update data in the column. The grantee is permitted to refer to the column within a constraint (for example, a unique, referential, or table check constraint). Indicates whether the grantee is permitted to grant the privilege to other users; YES, NO, or NULL if unknown. Chapter 3: Using the KB_SQL API 87
92 SQLColumns Returns the list of column names in specified tables. Arguments Statement handle [SQLHSTMT] Table qualifier [QUAL] Table owner [OWNER] Table name [TABLE] Column name [COLUMN] Returns Return code [SQLCODE] Syntax Example SQLCODE=$$CM^SQLOS(SQLHSTMT,QUAL,OWNER,TABLE,COLUMN) S SQLCODE=$$CM^SQLOS(SQLHSTMT,"","SQL_TEST","EMPLOYEES","%") I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes SQLColumns does not return columns for an index table. Use the SQLStatistics function to return the columns of an index table. This function returns a result set (see the next page) that can be processed like any other query result. 88 KB_SQL Programmer s Reference Guide
93 Result Set SQLColumns Column Code TABLE_QUALIFIER 1 TABLE_OWNER 2 TABLE_NAME 3 COLUMN_NAME 4 DATA_TYPE 5 TYPE_NAME 6 PRECISION 7 LENGTH 8 SCALE 9 RADIX 10 NULLABLE 11 REMARKS 12 Chapter 3: Using the KB_SQL API 89
94 SQLConnect Connects to KB_SQL server. Arguments Data source name User name Authorization Returns Return code Connection handle [SQLDATAS] [SQLUNAME] [SQLUAUTH] [SQLCODE] [SQLHDBC] Syntax Example Notes SQLCODE=$$C^SQLOS(SQLDATAS,SQLUNAME,SQLUAUTH,.SQLHDBC) S SQLCODE=$$C^SQLOS("M","DBA","SHARK",.SQLHDBC) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The data source name parameter is not currently validated by the Server API. If you are using the API for M, set the data source name parameter to "M". If you are using the API for C, the data source name parameter takes the value of the entry in the ODBC.INI configuration file. 90 KB_SQL Programmer s Reference Guide
95 SQLDescribeCol Gets basic metadata on a column. Arguments Statement handle Column sequence Returns Return code Column name ODBC data type Precision Scale Nullable [SQLHSTMT] [SQLCOL] [SQLCODE] [NAME] [TYPE] [PRECISION] [SCALE] [NULLABLE] Syntax SQLCODE=$$DC^SQLOS(SQLHSTMT,SQLCOL,.NAME,.TYPE,.PREC,.SCALE,.NULLABLE) Example S COL=3 S SQLCODE=$$DCSQLOS(SQLHSTMT,COL,.NAME,.TYPE,.PREC,.SCALE,.NULLABLE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes The example uses the variable COL to get column data dictionary information for the third column in the result set. Note that COL is a number where 1 <= COL <= NumResultCols. This function is an easier form of the more complete SQLColAttributes function. SQLDescribeParam Arguments SQLDescribeParam returns the description of a parameter marker associated with a prepared SQL statement. Statement handle [SQLHSTMT] Parameter sequence [PARSEQ] SqlType [TYPE] Precision [PREC] Scale [SCALE] Nullable [NULLABLE] SQL_NO_NULLS(0) The parameter does not allow NULL values. (This is the default value). Chapter 3: Using the KB_SQL API 91
96 SQL_NULLABLE(1) The parameter allows NULL values. SQL_NULLABLE_UNKNOWN(2) The driver cannot determine if the parameter allows NULL values. Syntax S SQLCODE=$$DP^SQLOS(SQLHSTMT,PARSEQ,.TYPE,.PREC,.SCALE,.NULLABLE) 92 KB_SQL Programmer s Reference Guide
97 Example SQL>SELECT * FROM EMPLOYEES WHERE NAME =? OR SALARY >? Parameter Type Precision Scale Nullable Notes Parameter markers are numbered from left to right in the order they appear in the SQL statement. The Precision and Scale values are the default maximums for the data type specified. The context in which the parameter is used may require the Precision and/or Scale values to be smaller. SQLDescribeParam does not return the type (input, input/output, or output) of a parameter in an SQL statement. Except in calls to procedures, all parameters in SQL statements are input parameters. To determine the type of each parameter in a call to a procedure, an application calls SQLProcedureColumns. Related Functions Sample routine APIM22. Chapter 3: Using the KB_SQL API 93
98 SQLDisconnect Disconnects from KB_SQL Server. Arguments Connection handle Returns Return code [SQLHDBC] [SQLCODE] Syntax Example Notes SQLCODE=$$D^SQLOS(SQLHDBC) DISCON S SQLCODE=$$D^SQLOS(SQLHDBC) I SQLCODE'=0 D Error All connection statement handles are dropped. In the KB_SQL API for C, this function causes a network disconnect. 94 KB_SQL Programmer s Reference Guide
99 SQLError Returns error information. Arguments Connection handle Statement handle Returns Return code Sqlstate Native code Native error text [SQLHDBC] [SQLHSTMT] [SQLCODE] [SQLSTATE] [SQLNC] [SQLNT] Syntax SQLCODE=$$ER^SQLOS(SQLHDBC,SQLHSTMT,.SQLSTATE,.SQLNC,.SQLNT) Example ER ; SQLError 3 I SQLCODE=99!(SQLCODE=100) Q W!,"SQLCODE= ",SQLCODE,! N SQLCODE,K65,ERS,ERC,ERT I '$G(SQLHDBC) S SQLHDBC=0 I '$G(SQLHSTMT) S SQLHSTMT=0 4 S SQLCODE=$$ER^SQLOS(SQLHDBC,SQLHSTMT,.ERS,.ERC,.ERT) I SQLCODE<0 Q I SQLCODE=100 Q W "SQLSTATE= ",ERS I ERS="" G 5 S K65=$O(^SQL(65,-1,ERS,0)) W " ",^SQL(65,K65,2) 5 W!,"Error Code= ",ERC,!,"Error Text= ",ERT,! G 4 6 Q Chapter 3: Using the KB_SQL API 95
100 Notes SQLSTATE is a 5-character code with descriptions provided by the SAG and Microsoft. To generate a list of the codes and descriptions, run the query SQL_API_SQLSTATE. 96 KB_SQL Programmer s Reference Guide
101 SQLExecDirect Prepares and executes an SQL command. Arguments Statement handle SQL command [SQLHSTMT] [SQLTEXT] Returns Return code [SQLCODE] Syntax Example SQLCODE=$$ED^SQLOS(SQLHSTMT,SQLTEXT) S SQLCODE=$$ED^SQLOS(SQLHSTMT,"SELECT * FROM SQL_TEST.EMPLOYEES") I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes This function can be used in place of SQLPrepare and SQLExecute. Chapter 3: Using the KB_SQL API 97
102 SQLExecute Executes a previously prepared SQL command. Arguments Statement handle [SQLHSTMT] Returns Return code [SQLCODE] Syntax Example Notes SQLCODE=$$E^SQLOS(SQLHSTMT) S SQLCODE=$$E^SQLOS(SQLHSTMT) I SQLCODE'=0 D Error G:SQLCODE<0 Discon If your query includes parameters, the SQLExecute function can return "SQLCODE=99," which indicates that data needs to be provided for parameters. At this point, you would invoke SQLPutData until SQLCODE is not equal to 99. Refer to the illustration in the Error Processing section earlier in this chapter. 98 KB_SQL Programmer s Reference Guide
103 SQLFetch Advances the cursor position for a statement. Arguments Statement handle [SQLHSTMT] Returns Return code [SQLCODE] Syntax Example Notes SQLCODE=$$F^SQLOS(SQLHSTMT) 1 S SQLCODE=$$F^SQLOS(SQLHSTMT) I SQLCODE'=0 D Error G:SQLCODE<0 Discon I SQLCODE=100 G 2... G 1 2. This function automatically populates all bound columns for each row. Chapter 3: Using the KB_SQL API 99
104 SQLForeignKeys SQLForeignKeys can return: A list of foreign keys in the specified table (columns in the specified table that refer to primary keys in other tables). A list of foreign keys in other tables that refer to the primary key in the specified table. Arguments Syntax Notes Statement handle [SQLHSTMT] PkTableQualifier [PKQUAL] PkTableOwner [PKOWNER] PkTableName [PKTABLE] FkTableQualifier [FKQUAL] FkTableOwner [FKOWNER] FkTableName [FKTABLE] S SQLCODE=$$FK^SQLOS(SQLHSTMT,PKQUAL,PKOWNER,PKTABLE, FKQUAL,FKOWNER,FKTABLE) If PkTableName contains a table name, SQLForeignKeys returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it. The result set is ordered by PKTABLE_QUALIFIER, PKTABLE_OWNER, PKTABLE_NAME, and KEY_SEQ. Example: To obtain a list of foreign keys that refer to the PATIENT table. S SQLCODE=$$FK^SQLOS(SQLHSTMT,,, PATIENT,,, ) 100 KB_SQL Programmer s Reference Guide
105 If FkTableName contains a table name, SQLForeignKeys returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer. The result set is ordered by FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, and KEY_SEQ. Example: To obtain a list of foreign keys stored in the PATIENT table. S SQLCODE=$$FK^SQLOS(SQLHSTMT,,,,,, PATIENT ) If both PkTableName and FkTableName contain table names, SQLForeignKeys returns the foreign keys in the table specified in FkTableName that refer to the primary key of the table specified in PkTableName. Example: To obtain a list of the one foreign key that joins the PATIENT and VISIT tables. S SQLCODE=$$FK^SQLOS(SQLHSTMT,,, PATIENT,,, VISIT ) Chapter 3: Using the KB_SQL API 101
106 Result Set Column Name Description PKTABLE_QUALIFIER Primary key table qualifier identifier. PKTABLE_OWNER Primary key table owner identifier. PKTABLE_NAME Primary key table identifier. PKCOLUMN_NAME Primary key column identifier. FKTABLE_QUALIFIER Foreign key table qualifier identifier. FKTABLE_OWNER Foreign key table owner identifier. FKTABLE_NAME Foreign key table identifier. FKCOLUMN_NAME Foreign key column identifier. KEY_SEQ Column sequence number in key (starting with 1). UPDATE_RULE Action to be applied to the foreign key on UPDATE. SQL_CASCADE SQL_RESTRICT SQL_SET_NULL NULL DELETE_RULE Action to be applied to the foreign key on DELETE. SQL_CASCADE SQL_RESTRICT SQL_SET_NULL NULL if not applicable FK_NAME Foreign key identifier. PK_NAME Primary key identifier. Related Functions Sample routine APIM KB_SQL Programmer s Reference Guide
107 SQLFreeConnect Frees the connection handle and all associated statement handles. Arguments Connection handle Returns Return code [SQLHDBC] [SQLCODE] Syntax Example SQLCODE=$$FC^SQLOS(SQLHDBC) S SQLCODE=$$FC^SQLOS(SQLHDBC) I SQLCODE'=0 D Error Q Note This function effectively closes all active statements and drops the connection. Chapter 3: Using the KB_SQL API 103
108 SQLFreeEnv Frees the environment handle and all associated connection and statement handles. Arguments Environment handle Returns Return code [SQLHENV] [SQLCODE] Syntax Example Notes SQLCODE=$$FE^SQLOS(SQLHENV) S SQLCODE=$$FE^SQLOS(SQLHENV) I SQLCODE'=0 D Error Q This function effectively closes all active statements and active connections and drops the environment. 104 KB_SQL Programmer s Reference Guide
109 SQLFreeStmt Stops processing of a statement, closes any open cursors associated with that statement, and discards results. Arguments Statement handle Option Returns Return code [SQLHSTMT] [SQLTYPE] [SQLCODE] Syntax Example Options SQLCODE=$$FS^SQLOS(SQLHSTMT,SQLTYPE) S SQLCODE=$$FS^SQLOS(SQLHSTMT,1) I SQLCODE'=0 D Error G:SQLCODE<0 Discon SQLFreeStmt Option Code SQL_CLOSE 0 SQL_DROP 1 SQL_UNBIND 2 SQL_RESET_PARAMS 3 Chapter 3: Using the KB_SQL API 105
110 SQLGetConnectOption Returns the current setting of a connection option. Arguments Connection handle [SQLHDBC] Option type [TYPE] Returns Return code Option value [SQLCODE] [VALUE] Syntax Example Notes SQLCODE=$$GCO^SQLOS(SQLHDBC,TYPE,.VALUE) S OPTION=101 S SQLCODE=$$GCO^SQLOS(SQLHDBC,OPTION,.VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example uses the variable OPTION to get information about the SQL_ACCESS_MODE state for the connection referenced by the variable SQLHDBC. See SQLSetConnectOption for a list of statement options for this function. Run SQL_API_CONNECT_OPTION to generate a list of connection options. 106 KB_SQL Programmer s Reference Guide
111 SQLGetCursorName Returns the name of a cursor associated with a statement. Arguments Statement handle Returns Return code Cursor name [SQLHSTMT] [SQLCODE] [NAME] Syntax Example Notes SQLCODE=$$GCN^SQLOS(SQLHSTMT,.NAME) S SQLCODE=$$GCN^SQLOS(SQLHSTMT,.NAME) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The only statements that use a cursor name are the positioned UPDATE and DELETE (for example, UPDATE tablename...where CURRENT OF cursor-name). If the application does not call SQLSetCursorName, the SQL engine allocates a default cursor name. This function returns the name of a cursor regardless of whether it was created explicitly or implicitly. Chapter 3: Using the KB_SQL API 107
112 SQLGetData Returns a specific column value from a statement cursor. Arguments Statement handle Column sequence Returns Return code Column value [SQLHSTMT] [SQLCOL] [SQLCODE] [VALUE] Syntax Example Notes SQLCODE=$$GD^SQLOS(SQLHSTMT,SQLCOL,.VALUE) S SEQ=3 S SQLCODE=$$GD^SQLOS(SQLHSTMT,SEQ,.VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example gets the value of the result set s third column, (SEQ), for the statement referenced by the variable SQLHSTMT. Note that SEQ is a number where 1<= SEQ <= NumResultCols. See also SQLBindCol. We recommend SQLFetch for better performance. 108 KB_SQL Programmer s Reference Guide
113 SQLGetInfo Returns general information about the driver and data source. Arguments Connection handle [SQLHDBC] Info type [TYPE] Returns Return code Info value [SQLCODE] [VALUE] Syntax Example Notes SQLCODE=$$GI^SQLOS(SQLHDBC,TYPE,.VALUE) S SQLCODE=$$GI^SQLOS(SQLHDBC,TYPE,.VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon Run the on-line query, SQL_API_INFO_OPTION, to generate a list of the SQLGetInfo options and their respective codes. See sample routine APIM10 for an illustration of how to use SQLGetInfo. The ODBC specification reserves the range of for information types. KB Systems reserves values greater than 1000 for data source specific information. A returned value is always a simple string of numbers or characters. A bitmask requires special handling. Two subroutines, UNMASK ^SQLK1 and MASK^SQLK1, are provided to assist in this process. For example, suppose you receive a BitMask value of The following code demonstrates the effect of the two subroutines: ; Convert Number to BitString S X=65535 D MASK^SQLK1 W X ; Returns " " ; Convert BitString to Number S X=" " D UNMASK^SQLK1 W X ; Returns Chapter 3: Using the KB_SQL API 109
114 110 KB_SQL Programmer s Reference Guide
115 SQLGetStmtOption Returns the current settings of a statement option. Arguments Statement handle Statement option [SQLHSTMT] [OPTION] Returns Return code Option value [SQLCODE] [VALUE] Syntax Example Notes SQLCODE=$$GSO^SQLOS(SQLHSTMT,OPTION,.VALUE) S TYPE=0 S SQLCODE=$$GSO^SQLOS(SQLHSTMT,TYPE,.VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example uses the variable TYPE to get information about the statement option for the statement referenced by the variable SQLHSTMT. For a list of valid statement options, run the on-line query SQL_API_STATEMENT_OPTION or see the SQLSetStmtOption function. Chapter 3: Using the KB_SQL API 111
116 SQLGetTypeInfo Returns information on supported data types. Arguments Statement handle ODBC data type Returns Return code [SQLHSTMT] [TYPE] [SQLCODE] Syntax Example SQLCODE=$$GTI^SQLOS(SQLHSTMT,TYPE) S TYPE=-7 S SQLCODE=$$GTI^SQLOS(SQLHSTMT,TYPE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes The example produces a result set of information about the SQL_BIT(FLAG) data type. If the TYPE variable is zero (0), the result set contains information about all supported types. Otherwise, the result set is specific to the one type referenced by the TYPE variable. Run the on-line query, SQL_API_DATATYPE, to generate a list of supported data types. See sample routine APIM6 for a demonstration of SQLGetTypeInfo. 112 KB_SQL Programmer s Reference Guide
117 SQLMoreResults SQLMoreResults determines whether there are more results available on an hstmt containing SELECT, UPDATE, INSERT, or DELETE statements and, if so, initializes processing for those results. Arguments Statement handle [SQLHSTMT] Syntax Notes S SQLCODE=$$MR^SQLOS(SQLHSTMT) UPDATE, INSERT, and DELETE statements return a count of affected rows. If any of these statements are batched, submitted with arrays of parameters, or in procedures, they can return multiple result sets or counts. If another result set or count is available, SQLMoreResults returns SQL_SUCCESS and initializes the result set or count for additional processing. After calling SQLMoreResults for SELECT statements, an application can call functions to determine the characteristics of the result set and to retrieve data from the result set. After calling SQLMoreResults for UPDATE, INSERT, or DELETE statements, an application can call SQLRowCount. If all results have been processed, SQLMoreResults returns SQL_NO_DATA_FOUND. Chapter 3: Using the KB_SQL API 113
118 Note that if there is a current result set with unfetched rows, SQLMoreResults discards that result set and makes the next result set or count available. If a batch of statements or a procedure mixes other SQL statements with SELECT, UPDATE, INSERT, and DELETE statements, these other statements do not affect SQLMoreResults. 114 KB_SQL Programmer s Reference Guide
119 SQLNativeSql SQLNativeSql returns the SQL command text as translated by the server. Arguments Connection handle LinesIn ArrayIn LinesOut ArrayOut [SQLHDBC] [IN] [XIN] [OUT] [XOUT] Syntax Notes S SQLCODE=$$NS^SQLOS(SQLHDBC,IN,XIN,.OUT,XOUT) The SQLNativeSql function returns the SQL command text after it has been processed to handle ODBC escape clauses and string literal quoting. A summary of the conversions is listed below. {fn function(parmlist)} SQL_function(parmlist) {fn lower(name)} => SQL_lower(Name) {d date-literal} date-literal {d ' '} => ' ' Chapter 3: Using the KB_SQL API 115
120 {t time-literal} time-literal {t '22:30:15'} => '22:30:15' {ts timestamp-literal} timestamp-literal {ts ' :30:15'} => ' :30:15' {call procedure(parmlist)} call procedure(parmlist) {call DeptEmps(?)} => call DeptEmps(?) DoubleQuote in SingleQuoted Literal 'hello "there" world' => 'hello ""there"" world' SingleQuote in DoubleQuoted Literal "hello 'there' world" => "hello ''there'' world" SoftTag in Literal 'hello {*there} world' => ('hello ' chr(123,42) 'there} world') Related Functions Sample routine APIM KB_SQL Programmer s Reference Guide
121 Example Enter SQL Command (or 'GO' to execute) -->Select {fn lcase(name)}, {fn soundex(name)} -->From Employees -->Where {fn floor(salary)} > 10 -->go SQL Statement converted to native syntax Select SQL_fn_lcase(name), SQL_fn_soundex(name) From Employees Where SQL_fn_floor(salary) > 10 Chapter 3: Using the KB_SQL API 117
122 SQLNumParams SQLNumParams returns the number of parameters in an SQL statement. Arguments Statement handle numparams [NPM] [SQLHSTMT] Syntax S SQLCODE=$$NP^SQLOS(SQLHSTMT,.NPM) Notes SQLNumParams can be called only after SQLPrepare has been called. If the statement associated with hstmt does not contain parameters, SQLNumParams sets numparams to 0. Related Functions Sample routine APIM21. SQLDescribeParam API function. 118 KB_SQL Programmer s Reference Guide
123 SQLNumResultCols Returns the number of columns in a table. Arguments Statement handle [SQLHSTMT] Returns Syntax Example Notes Return code [SQLCODE] Number of columns [COLS] SQLCODE=$$NRC^SQLOS(SQLHSTMT,.COLS) S SQLCODE=$$NRC^SQLOS(SQLHSTMT,.NRC) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example uses the NRC variable to return the number of result columns in the statement referenced by the SQLHSTMT variable. Note that the statement must be prepared prior to execution of this function, otherwise an error results. Chapter 3: Using the KB_SQL API 119
124 SQLPrepare Prepares an SQL command for execution. Arguments Statement handle SQL command Returns Return code [SQLHSTMT] [SQLTEXT] [SQLCODE] Syntax Example Notes SQLCODE=$$P^SQLOS(SQLHSTMT,SQLTEXT) S SQLCODE=$$P^SQLOS(SQLHSTMT,"SELECT * FROM SQL_TEST.EMPLOYEES") I SQLCODE'=0 D Error G:SQLCODE<0 Discon If the SQL command is too long (greater than 255 bytes) to be prepared all at once, use KBSStatement. 120 KB_SQL Programmer s Reference Guide
125 SQLPrimaryKeys SQLPrimaryKeys returns the column names that comprise the primary key for a table. Arguments Statement handle TableQualifier TableOwner TableName [SQLHSTMT] [QUAL] [OWNER] [TABLE] Syntax Notes S SQLCODE=$$PK^SQLOS(SQLHSTMT,QUAL,OWNER,TABLE) SQLPrimaryKeys returns the results as a standard result set, ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and KEY_SEQ. Chapter 3: Using the KB_SQL API 121
126 Result Set Column Name Description TABLE_QUALIFIER Primary key table qualifier identifier. TABLE_OWNER Primary key table owner identifier. TABLE_NAME Primary key table identifier. COLUMN_NAME Primary key column identifier. KEY_SEQ Column sequence number in key (starting with 1). PK_NAME Primary key identifier. Related Functions Sample routine APIM KB_SQL Programmer s Reference Guide
127 SQLProcedureColumns Arguments Syntax Notes SQLProcedureColumns returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Statement handle [SQLHSTMT] ProcQualifier [QUAL] ProcOwner [OWNER] ProcName [PROC] ColumnName [COLUMN] S SQLCODE=$$PC^SQLOS(SQLHSTMT,QUAL,OWNER,PROC,COLUMN) This function is typically used before statement execution to retrieve information about procedure parameters and columns from the system catalog. The procedure query must be compiled in order for the procedure to be recognized. The ProcOwner, ProcName, and ColumnName arguments accept search patterns. Chapter 3: Using the KB_SQL API 123
128 Result Set Column Name Description PROCEDURE_QUALIFIER Procedure qualifier identifier. PROCEDURE_OWNER Procedure owner identifier. PROCEDURE_NAME Procedure identifier. COLUMN_NAME Procedure column identifier. COLUMN_TYPE Defines the type of procedure column. SQL_PARAM_TYPE_UNKNOWN (0) The procedure column is a parameter whose type is unknown. SQL_PARAM_INPUT(1) The procedure column is an input parameter. SQL_PARAM_INPUT_OUTPUT(2) The procedure column is an input/output parameter. SQL_RESULT_COL(3) The procedure column is a result set column. SQL_PARAM_OUTPUT(4) The procedure column is an output parameter. SQL_RETURN_VALUE(5) The procedure column is the return value of the procedure. DATA_TYPE SQL data type. TYPE_NAME Data type name. PRECISION The precision of the procedure column. LENGTH The length (in bytes) of data. SCALE The scale of the procedure column. RADIX For numeric data types, either 10 or 2. NULLABLE Whether the procedure column accepts a NULL value. SQL_NO_NULLS(0) The procedure column does not accept NULL values. SQL_NULLABLE(1) The procedure column accepts NULL values. SQL_NULLABLE_UNKNOWN (2) It is not known if the procedure column accepts NULL values. REMARKS A description of the procedure column. Related Functions Sample routine APIM22. SQLProcedures API function. 124 KB_SQL Programmer s Reference Guide
129 SQLProcedures Arguments Syntax Notes SQLProcedures returns the list of procedure names stored in a specific data source. Procedure is a generic term used to describe an executable object, or a named entity that can be invoked using input and output parameters, and which can return result sets similar to the results returned by SQL SELECT expressions. Statement handle [SQLHSTMT] ProcQualifier [QUAL] ProcOwner [OWNER] ProcName [PROC] S SQLCODE=$$PR^SQLOS(SQLHSTMT,QUAL,OWNER,PROC) SQLProcedures lists all procedures in the requested range. A user may or may not have permission to execute any of these procedures. To check accessibility, an application can call SQLGetInfo and check the SQL_ACCESSIBLE_PROCEDURES information value. Otherwise, the application must be able to handle a situation where the user selects a procedure which it cannot execute. The procedure query must be compiled in order for the procedure to be recognized. The ProcOwner and ProcName arguments accept search patterns. Chapter 3: Using the KB_SQL API 125
130 Result Set Column Name PROCEDURE_QUALIFIER PROCEDURE_OWNER PROCEDURE_NAME NUM_INPUT_PARAMS NUM_OUTPUT_PARAMS NUM_RESULT_SETS REMARKS PROCEDURE_TYPE SQL_PT_UNKNOWN(0) SQL_PT_PROCEDURE(1) SQL_PT_FUNCTION(2) Description Procedure qualifier identifier. Procedure owner identifier. Procedure identifier. Number of input parameters. Number of output parameters. Number of result sets. A description of the procedure. Defines the procedure type. It cannot be determined whether the procedure returns a value. The returned object is a procedure; that is, it does not have a return value. The returned object is a function; that is, it has a return value. Related Functions Sample routine APIM KB_SQL Programmer s Reference Guide
131 SQLPutData Arguments Specifies the execution time value for a parameter. Statement handle [SQLHSTMT] Parameter value [VALUE] Parameter sequence [SEQ] Returns Return code [SQLCODE] Syntax Example Notes SQLCODE=$$PD^SQLOS(SQLHSTMT,VALUE,SEQ) S SQLCODE=$$PD^SQLOS(SQLHSTMT,"9.00",2) I SQLCODE'=0 D Error G:SQLCODE<0 Discon In the case of date, time, timestamp, and bit, the value parameter is in the external format used by ODBC. For example, a date parameter is specified as " " as opposed to the internal format for M dates. Note that the SQL_BIT type is mapped to the KB Systems FLAG data type. Chapter 3: Using the KB_SQL API 127
132 SQLRowCount Returns the number of rows from a result set. Arguments Statement handle [SQLHSTMT] Returns Syntax Example Notes Return code [SQLCODE] Number of rows [ROWS] SQLCODE=$$RC^SQLOS(SQLHSTMT,.ROWS) S SQLCODE=$$RC^SQLOS(SQLHSTMT,.ROWS) I SQLCODE'=0 D Error G:SQLCODE<0 Discon This function is designed for use with INSERT, UPDATE, and DELETE queries. It returns the number of rows affected by the query. For a SELECT query, this function returns the current row number. 128 KB_SQL Programmer s Reference Guide
133 SQLSetConnectOption Sets options that govern aspects of connections. Arguments Connection handle [SQLHDBC] Option type [TYPE] Option value [VALUE] Returns Return code [SQLCODE] Syntax Example Notes SQLCODE=$$SCO^SQLOS(SQLHDBC,TYPE,VALUE) S TYPE=101,VALUE=1 S SQLCODE=$$SCO^SQLOS(SQLHDBC,TYPE,VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example uses the variable TYPE to set the value SQL_ACCESS_MODE option to read only for the connection referenced by the variable SQLHDBC. Run the on-line query SQL_API_CONNECT_OPTION to generate a list of connection options. See the accompanying table on the next page for a list of this function s statement options and their respective codes. Chapter 3: Using the KB_SQL API 129
134 Options SQLSetConnectOption Option Code SQL_ACCESS_MODE 101 SQL_AUTOCOMMIT 102 SQL_LOGIN_TIMEOUT 103 SQL_OPT_TRACE 104 SQL_OPT_TRACEFILE 105 SQL_TRANSLATE_DLL 106 SQL_TRANSLATE_OPTION 107 SQL_TXN_ISOLATION 108 SQL_CURRENT_QUALIFIER 109 SQL_ODBC_CURSORS 110 SQL_QUIET_MODE 111 SQL_PACKET_SIZE 112 SQL_CONNECT_OPT_DRVR_START KB_SQL Programmer s Reference Guide
135 SQLSetCursorName Specifies the name of a cursor for a statement. Arguments Statement handle Cursor name Returns Return code [SQLHSTMT] [NAME] [SQLCODE] Syntax Example Notes SQLCODE=$$SCN^SQLOS(SQLHSTMT,NAME) S SQLCODE=$$SCN^SQLOS(SQLHSTMT,NAME) I SQLCODE'=0 D Error G:SQLCODE<0 Discon All cursor names within the connection must be unique. The only statements that use a cursor name are the positioned UPDATE and DELETE (for example, UPDATE tablename...where CURRENT OF cursor-name). If the application does not call SQLSetCursorName, the SQL engine allocates a default cursor name. This function returns the name of a cursor regardless of whether it was created explicitly or implicitly. SQLSetStmtOption Sets options related to statement handle. Arguments Statement handle Statement option Option value [SQLHSTMT] [OPTION] [VALUE] Returns Return code [SQLCODE] Syntax SQLCODE=$$SSO^SQLOS(SQLHSTMT,OPTION,VALUE) Chapter 3: Using the KB_SQL API 131
136 Example Notes S OPTION=0,VALUE=60 S SQLCODE=$$SSO^SQLOS(SQLHSTMT,OPTION,VALUE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example uses the variable OPTION to set the SQL_QUERY_TIMEOUT value for the statement referenced by the variable SQLHSTMT. For a list of valid statement options, run the on-line query SQL_API_STATEMENT_OPTION or see the table on the next page. 132 KB_SQL Programmer s Reference Guide
137 Options SQLSetStmtOption Option Code SQL_QUERY_TIMEOUT 0 SQL_MAX_ROWS 1 SQL_NOSCAN 2 SQL_MAX_LENGTH 3 SQL_ASYNC_ENABLE 4 SQL_BIND_TYPE 5 SQL_CURSOR_TYPE 6 SQL_CONCURRENCY 7 SQL_KEYSET_SIZE 8 SQL_ROWSET_SIZE 9 SQL_SIMULATE_CURSOR 10 SQL_RETRIEVE_DATA 11 SQL_USE_BOOKMARKS 12 SQL_GET_BOOKMARK 13 SQL_ROW_NUMBER 14 Chapter 3: Using the KB_SQL API 133
138 SQLSpecialColumns Returns row identity and auto-updates columns. Arguments Statement handle Column type Table qualifier Table owner Table name Scope Nullable Returns Return code [SQLHSTMT] [COLTYPE] [QUAL] [OWNER] [TABLE] [SCOPE] [NULLABLE] [SQLCODE] Syntax SQLCODE=$$SC^SQLOS(SQLHSTMT,COLTYPE,QUAL,OWNER,TABLE,SCOPE,NULLABLE) Example S SQLCODE=$$SC^SQLOS(SQLHSTMT,1,"","SQL_TEST","CHARGES",0,0) I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes This function returns the primary keys for the table. See the accompanying table on the next page for the result set. 134 KB_SQL Programmer s Reference Guide
139 Result Set SQLSpecialColumns Column Col Seq SCOPE 1 COLUMN_NAME 2 DATA_TYPE 3 TYPE_NAME 4 PRECISION 5 LENGTH 6 SCALE 7 PSEUDO_COLUMN 8 Chapter 3: Using the KB_SQL API 135
140 SQLStatistics Returns the primary key for a base table and for an index table. Because the primary key is all the columns for an index table, you can use this function to get all the columns in an index table, but not all the columns in a base table. Arguments Statement handle [SQLHSTMT] Table qualifier [QUAL] Table owner [OWNER] Table name [TABLE] Unique [UNIQUE] Accuracy [ACCURACY] Returns Return code [SQLCODE] Syntax SQLCODE=$$SM^SQLOS(SQLHSTMT,QUAL,OWNER,TABLE,UNIQUE,ACCURACY) Example S SQLCODE=$$SM^SQLOS(SQLHSTMT,"","SQL_TEST","EMPLOYEES",1,1) I SQLCODE'=0 D Error G:SQLCODE<0 Discon Notes See the accompanying table on the next page for the result set. 136 KB_SQL Programmer s Reference Guide
141 Result Set SQLStatistics Column Col Seq TABLE_QUALIFIER 1 TABLE_OWNER 2 TABLE_NAME 3 NON_UNIQUE 4 INDEX_QUALIFIER 5 INDEX_NAME 6 TYPE 7 SEQ_IN_INDEX 8 COLUMN_NAME 9 COLLATION 10 CARDINALITY 11 PAGES 12 FILTER_CONDITION 13 Chapter 3: Using the KB_SQL API 137
142 SQLTablePrivileges SQLTablePrivileges returns a list of tables and the privileges associated with each table. Arguments Statement handle TableQualifier TableOwner TableName [SQLHSTMT] [QUAL] [OWNER] [TABLE] Notes The TableOwner and TableName arguments accept search patterns. For the DBA, privileges will appear for all grantees. For non-dba users, privileges will appear for your user group only. 138 KB_SQL Programmer s Reference Guide
143 Result Set Column Name TABLE_QUALIFIER TABLE_OWNER TABLE_NAME GRANTOR GRANTEE PRIVILEGE SELECT INSERT UPDATE DELETE REFERENCES IS_GRANTABLE Description Table qualifier identifier. Table owner identifier. Table identifier. User who granted the privilege. User to whom the privilege was granted. Identifies the table privilege. The grantee is permitted to retrieve data for one or more The grantee is permitted to insert new rows containing The grantee is permitted to update the data in one or The grantee is permitted to delete rows of data from the The grantee is permitted to refer to one or more columns of the table within a constraint (for example, a unique, referential, or table check constraint). The scope of action permitted the grantee by a given table privilege is data source-dependent. For example, the UPDATE privilege might permit the grantee to update all columns in a table on one data source and only those columns for which the grantor has the UPDATE privilege on another data source. Indicates whether the grantee is permitted to grant the privilege to other users: YES, NO, or NULL if unknown. Related Functions Sample routine APIM20. Chapter 3: Using the KB_SQL API 139
144 SQLTables Returns list of table names stored in a specific data source. The list includes only those tables accessible by the user who is currently logged in via the SQLConnect function. To get the complete list of tables you must log in as the DBA. Arguments Statement handle Table Qualifier Table Owner Table Name Table Type Returns Return code [SQLHSTMT] [QUAL] [OWNER] [TABLE] [TYPE] [SQLCODE] Syntax Example SQLCODE=$$TM^SQLOS(SQLHSTMT,QUAL,OWNER,TABLE,TYPE) ;List all Owners (schemas) S SQLCODE=$$TM^SQLOS(HSTMT,"","%","","") ;List Types S SQLCODE=$$TM^SQLOS(HSTMT,"","","","%") ;List Views S SQLCODE=$$TM^SQLOS(HSTMT,"","","%","VIEW") ;List Tables S SQLCODE=$$TM^SQLOS(HSTMT,"","","%","TABLE") ;List System Tables S SQLCODE=$$TM^SQLOS(HSTMT,"","","%","SYSTEM TABLE") Notes The table qualifier (QUAL) argument is supported, but its value must be null. You may use the subroutine WCPD^SQLK1 to pad or insert wildcards into an SQL_IDENTIFIER. >w X For example, assume the following SQL_IDENTIFIER is a valid table name. THIS_IS_MY_VALID_TABLENAME The WCPD subroutine may be called to insert the wildcard escape character as illustrated below. 140 KB_SQL Programmer s Reference Guide
145 X THIS_IS_MY_VALID_TABLENAME >D WCPD^SQLK1 /* After conversion */ >W X THIS\_IS\_MY\_VALID\_TABLENAME The result set of the function appears below. Result Set SQLTables Column Col Seq TABLE_QUALIFIER 1 TABLE_OWNER 2 TABLE_NAME 3 TABLE_TYPE 4 REMARKS 5 Chapter 3: Using the KB_SQL API 141
146 SQLTransact Commits or rolls back pending transactions. Arguments Connection handle Commit or rollback Returns Return code [SQLHDBC] [SQLTTYPE] [SQLCODE] Syntax Example Notes SQLCODE=$$T^SQLOS(SQLHDBC,SQLTTYPE) S TTYPE=1 SQLCODE=$$T^SQLOS(SQLHDBC,TTYPE) I SQLCODE'=0 D Error G:SQLCODE<0 Discon The example attempts to rollback the transaction for the connection. TTYPE can be zero (0) for commit, or one (1) for rollback. Users are encouraged to use this API call instead of the SQL COMMIT and ROLLBACK commands to commit or rollback pending transactions. Options SQLTransact Option Code COMMIT 0 ROLLBACK KB_SQL Programmer s Reference Guide
147 Putting It Together This section s objective is to provide you with a visual road map of how to put the tools of this chapter together to develop your application using the KB_ SQL API. The figures on the following pages illustrate the basic tasks a successful application must accomplish. They are: connecting to the data source; processing one or more SQL statements; committing or rolling back each concluded transaction; and, disconnecting from the data source. Chapter 3: Using the KB_SQL API 143
148 Connecting to a Data Source Basic operation overview Obtain environment handle (SQLAllocEnv) Obtain connection handle (SQLAllocConnect) Connect to a driver (SQLConnect) Obtain a statement handle (SQLAllocStmt) Process SQL Statements Receive Results End statement processing (SQLFreeStmt) Close the connection (SQLDisconnect) Release the connection handle (SQLFreeConnect) Release the environment handle (SQLFreeEnv) 144 KB_SQL Programmer s Reference Guide
149 Processing SQL Statements Initialize Execute a statement (SQLExecDirect) Prepare a statement (SQLPrepare) Execute a prepared statement (SQLExecute) SELECT Statement Type? INSERT, UPDATE, or DELETE Return number of columns in result set (SQLNumResultCols) Describe a column in the result set (SQLDescribeCol) Return the number of rows affected by the statement (SQLRowCount) Assign storage for a result column and specify data type (SQLBindCol) Return a result row (SQLFetch) YES More rows? NO End statement processing (SQLFreeStmt) Commit or roll back a transaction (SQLTransact) Terminate Chapter 3: Using the KB_SQL API 145
150 Appendix A A Comparison of KB_ESQL & KB_SQL API For those of you wondering how our programming tools line up, we offer the at-a-glance comparison below. In addition, we draw some broad conclusions on the next page for your consideration as you determine the manner of implementation most suitable for your application. KB_ESQL CONNECT DISCONNECT GET DIAGNOSTICS DECLARE CURSOR and OPEN CURSOR FETCH precompiler operation GET DIAGNOSTICS COMMIT or ROLLBACK KB_SQL API SQLConnect SQLDisconnect SQLError SQLExecDirect/ SQLExecute SQLFetch SQLPrepare/ KBSStatement SQLRowCount SQLTransact 146 KB_SQL Programmer s Reference Guide
151 The line-up suggests, and rightly so, that both KB_ESQL and KB_SQL API share a structured process flow a specific order of statements. Both must establish connections, request information, retrieve data, and terminate the connection, in that order. Both have provisions for applying or not applying changes to the database as well as a mechanism for error checking. Some differences exist that may not be so obvious at a glance. Both conform to the ANSI SQL standard; however, KB_ESQL must also comply to ANSI M for the M binding and KB_SQL API is subject to Microsoft s ODBC specification. A precompile process in KB_ESQL affords performance efficiencies at runtime over KB_SQL API. KB_SQL API, though, delivers a greater degree of direct hands-on control over KB_ESQL because the input is the actual executable. Other distinctions include: KB_ESQL begins in manual commit as opposed to the auto commit mode of KB_SQL API. With regard to statements, KB_ESQL is implicitly functional while KB_SQL API is explicitly functional. KB_ESQL offers an omnidirectional scroll for its cursor while KB_SQL API s cursor is unidirectional forward only. Wherever a host variable occurs in KB_ESQL, KB_SQL API uses a parameter marker. Perhaps our best advice to you in assessing implementation pros and cons is very appropriately conveyed in the maxim of the preeminent architect, Frank Lloyd Wright: let form follow function. Appendix A: A Comparison of KB_ESQL & KB_SQL API 147
152 Appendix B Using the KB_SQL API for MSE This appendix applies specifically to the KB_SQL Server API as it relates to MSE. It is intended for the MSE programmer. Because the KB_SQL API is designed using the ODBC API as a model, the function names and parameters correspond to the ODBC definition. The default language of ODBC is C. The default language of KB_SQL API is MUMPS (M). Just as the ODBC API can be used by other languages (e.g., Visual Basic), the KB_SQL API can be used by different languages (e.g., MSE). 148 KB_SQL Programmer s Reference Guide
153 Example SQLDescribeCol ANSI S SQLCODE=$$DC^SQLOS (SQLHSTMT,ICOL,.NAME,.TYPE,.PREC,.SCALE,.NULLABLE) The function calls use the $$tag^routine syntax. Output parameters are passed as.varname. SQLCODE is set equal to the result of the function call. MSE ZP DC^SQLOS:"SQLCODE":SQLHSTMT:ICOL:"NAME":"TYPE": "PREC":"SCALE":"NULLABLE" The function calls use the Zproc tag^routine syntax. Output parameters are passed inside double quotes varname". SQLCODE is always the first return parameter. Once these basic differences are understood, the documentation of the functions can be used for either MUMPS or MSE. Regardless of the environment, the KB_SQL Server API offers a clean interface to the KB_SQL Engine. For an illustration of how to use the KB_SQL API syntax, refer to Chapter 3 in this manual and to the on-line samples (which you can choose to load when installing KB_SQL). Appendix B: A Comparison of KB_ESQL & KB_SQL API 149
KB_SQL SQL Reference Guide Version 4
KB_SQL SQL Reference Guide Version 4 1995, 1999 by KB Systems, Inc. All rights reserved. KB Systems, Inc., Herndon, Virginia, USA. Printed in the United States of America. No part of this manual may be
Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB
Mimer SQL Version 8.2 Copyright 2000 Mimer Information Technology AB Second revised edition December, 2000 Copyright 2000 Mimer Information Technology AB. Published by Mimer Information Technology AB,
Database Programming with PL/SQL: Learning Objectives
Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-97 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals
Choosing a Data Model for Your Database
In This Chapter This chapter describes several issues that a database administrator (DBA) must understand to effectively plan for a database. It discusses the following topics: Choosing a data model for
1 File Processing Systems
COMP 378 Database Systems Notes for Chapter 1 of Database System Concepts Introduction A database management system (DBMS) is a collection of data and an integrated set of programs that access that data.
Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff
D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to
Micro Focus Database Connectors
data sheet Database Connectors Executive Overview Database Connectors are designed to bridge the worlds of COBOL and Structured Query Language (SQL). There are three Database Connector interfaces: Database
DATABASE SYSTEM CONCEPTS AND ARCHITECTURE CHAPTER 2
1 DATABASE SYSTEM CONCEPTS AND ARCHITECTURE CHAPTER 2 2 LECTURE OUTLINE Data Models Three-Schema Architecture and Data Independence Database Languages and Interfaces The Database System Environment DBMS
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY 2.1 Introduction In this chapter, I am going to introduce Database Management Systems (DBMS) and the Structured Query Language (SQL), its syntax and usage.
Chapter 2 Database System Concepts and Architecture
Chapter 2 Database System Concepts and Architecture Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Outline Data Models, Schemas, and Instances Three-Schema Architecture
2 SQL in iseries Navigator
2 SQL in iseries Navigator In V4R4, IBM added an SQL scripting tool to the standard features included within iseries Navigator and has continued enhancing it in subsequent releases. Because standard features
Chapter 9, More SQL: Assertions, Views, and Programming Techniques
Chapter 9, More SQL: Assertions, Views, and Programming Techniques 9.2 Embedded SQL SQL statements can be embedded in a general purpose programming language, such as C, C++, COBOL,... 9.2.1 Retrieving
Embedded SQL programming
Embedded SQL programming http://www-136.ibm.com/developerworks/db2 Table of contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Before
OBJECTSTUDIO. Database User's Guide P40-3203-03
OBJECTSTUDIO Database User's Guide P40-3203-03 Release information for this manual ObjectStudio Database User's Guide, P40-3203-03, is dated vember 1, 2003. This document supports Release 6.9 of ObjectStudio.
Oracle SQL. Course Summary. Duration. Objectives
Oracle SQL Course Summary Identify the major structural components of the Oracle Database 11g Create reports of aggregated data Write SELECT statements that include queries Retrieve row and column data
KB_SQL Database Administrator s Guide Version 4
KB_SQL Database Administrator s Guide Version 4 1995, 1999 by KB Systems, Inc. All rights reserved. KB Systems, Inc., Herndon, Virginia, USA. Printed in the United States of America. No part of this manual
Oracle Database 10g: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database technology.
Using SQL in RPG Programs: An Introduction
Using SQL in RPG Programs: An Introduction OCEAN Technical Conference Catch the Wave Susan M. Gantner susan.gantner @ partner400.com www.partner400.com Your partner in AS/400 and iseries Education Copyright
Oracle Database: Program with PL/SQL
Oracle Database: Program with PL/SQL Duration: 5 Days What you will learn This Oracle Database: Program with PL/SQL training starts with an introduction to PL/SQL and then explores the benefits of this
C H A P T E R Condition Handling
ch05.fm Page 75 Wednesday, November 13, 2002 7:16 AM 5 C H A P T E R Condition Handling In this chapter, you will learn: what SQLCODE and SQLSTATE are, and the difference between them. what a condition
1. INTRODUCTION TO RDBMS
Oracle For Beginners Page: 1 1. INTRODUCTION TO RDBMS What is DBMS? Data Models Relational database management system (RDBMS) Relational Algebra Structured query language (SQL) What Is DBMS? Data is one
ODBC Client Driver Help. 2015 Kepware, Inc.
2015 Kepware, Inc. 2 Table of Contents Table of Contents 2 4 Overview 4 External Dependencies 4 Driver Setup 5 Data Source Settings 5 Data Source Setup 6 Data Source Access Methods 13 Fixed Table 14 Table
ODBC Chapter,First Edition
1 CHAPTER 1 ODBC Chapter,First Edition Introduction 1 Overview of ODBC 2 SAS/ACCESS LIBNAME Statement 3 Data Set Options: ODBC Specifics 15 DBLOAD Procedure: ODBC Specifics 25 DBLOAD Procedure Statements
Oracle Database 10g: Program with PL/SQL
Oracle University Contact Us: Local: 1800 425 8877 Intl: +91 80 4108 4700 Oracle Database 10g: Program with PL/SQL Duration: 5 Days What you will learn This course introduces students to PL/SQL and helps
Oracle Database: Program with PL/SQL
Oracle University Contact Us: +33 15 7602 081 Oracle Database: Program with PL/SQL Duration: 5 Days What you will learn This course is available in Training On Demand format This Oracle Database: Program
Oracle Database: Develop PL/SQL Program Units
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Develop PL/SQL Program Units Duration: 3 Days What you will learn This Oracle Database: Develop PL/SQL Program Units course is designed for
Chapter 1: Introduction
Chapter 1: Introduction Database System Concepts, 5th Ed. See www.db book.com for conditions on re use Chapter 1: Introduction Purpose of Database Systems View of Data Database Languages Relational Databases
Oracle Database: Program with PL/SQL
Oracle University Contact Us: 0845 777 7711 Oracle Database: Program with PL/SQL Duration: 5 Days What you will learn This course starts with an introduction to PL/SQL and proceeds to list the benefits
Oracle Database: Program with PL/SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Program with PL/SQL Duration: 5 Days What you will learn View a newer version of this course /a/b/p/p/b/pulli/lili/lili/lili/lili/lili/lili/lili/lili/lili/lili/lili/li/ul/b/p/p/b/p/a/a/p/
Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts
D80186GC10 Oracle Database: Program with Summary Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts Level Professional Technology Oracle
SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches
SQL and Programming Languages SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8.4 of Garcia-Molina The user does not want to execute SQL
Firebird. Embedded SQL Guide for RM/Cobol
Firebird Embedded SQL Guide for RM/Cobol Embedded SQL Guide for RM/Cobol 3 Table of Contents 1. Program Structure...6 1.1. General...6 1.2. Reading this Guide...6 1.3. Definition of Terms...6 1.4. Declaring
CA IDMS SQL. Programming Guide. Release 18.5.00
CA IDMS SQL Programming Guide Release 18500 This Documentation, which includes embedded help systems and electronically distributed materials, (hereinafter referred to as the Documentation ) is for your
A Brief Introduction to MySQL
A Brief Introduction to MySQL by Derek Schuurman Introduction to Databases A database is a structured collection of logically related data. One common type of database is the relational database, a term
Oracle Database 11g SQL
AO3 - Version: 2 19 June 2016 Oracle Database 11g SQL Oracle Database 11g SQL AO3 - Version: 2 3 days Course Description: This course provides the essential SQL skills that allow developers to write queries
Microsoft SQL Server for Oracle DBAs Course 40045; 4 Days, Instructor-led
Microsoft SQL Server for Oracle DBAs Course 40045; 4 Days, Instructor-led Course Description This four-day instructor-led course provides students with the knowledge and skills to capitalize on their skills
Oracle Database: Introduction to SQL
Oracle University Contact Us: +381 11 2016811 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn Understanding the basic concepts of relational databases ensure refined code by developers.
What is a database? COSC 304 Introduction to Database Systems. Database Introduction. Example Problem. Databases in the Real-World
COSC 304 Introduction to Systems Introduction Dr. Ramon Lawrence University of British Columbia Okanagan [email protected] What is a database? A database is a collection of logically related data for
SQL Server Database Coding Standards and Guidelines
SQL Server Database Coding Standards and Guidelines http://www.sqlauthority.com Naming Tables: Stored Procs: Triggers: Indexes: Primary Keys: Foreign Keys: Defaults: Columns: General Rules: Rules: Pascal
D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:
D61830GC30 for Developers Summary Duration Vendor Audience 5 Days Oracle Database Administrators, Developers, Web Administrators Level Technology Professional Oracle 5.6 Delivery Method Instructor-led
Oracle Database: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn View a newer version of this course This Oracle Database: Introduction to SQL training
Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications
Chapter 13 SQL Programming Introduction to SQL Programming Techniques Database applications Host language Java, C/C++/C#, COBOL, or some other programming language Data sublanguage SQL SQL standards Continually
FileMaker 11. ODBC and JDBC Guide
FileMaker 11 ODBC and JDBC Guide 2004 2010 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker is a trademark of FileMaker, Inc. registered
Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia
Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia 1. SQL Review Single Row Functions Character Functions Date Functions Numeric Function Conversion Functions General Functions
Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components
Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals 1 Properties of a Database 1 The Database Management System (DBMS) 2 Layers of Data Abstraction 3 Physical Data Independence 5 Logical
Oracle 10g PL/SQL Training
Oracle 10g PL/SQL Training Course Number: ORCL PS01 Length: 3 Day(s) Certification Exam This course will help you prepare for the following exams: 1Z0 042 1Z0 043 Course Overview PL/SQL is Oracle's Procedural
Setting Up ALERE with Client/Server Data
Setting Up ALERE with Client/Server Data TIW Technology, Inc. November 2014 ALERE is a registered trademark of TIW Technology, Inc. The following are registered trademarks or trademarks: FoxPro, SQL Server,
SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach
TRAINING & REFERENCE murach's SQL Server 2012 for developers Bryan Syverson Joel Murach Mike Murach & Associates, Inc. 4340 N. Knoll Ave. Fresno, CA 93722 www.murach.com [email protected] Expanded
Oracle Database: Program with PL/SQL
Oracle University Contact Us: +52 1 55 8525 3225 Oracle Database: Program with PL/SQL Duration: 5 Days What you will learn View a newer version of this course This Oracle Database: Program with PL/SQL
Database System Architecture & System Catalog Instructor: Mourad Benchikh Text Books: Elmasri & Navathe Chap. 17 Silberschatz & Korth Chap.
Database System Architecture & System Catalog Instructor: Mourad Benchikh Text Books: Elmasri & Navathe Chap. 17 Silberschatz & Korth Chap. 1 Oracle9i Documentation First-Semester 1427-1428 Definitions
Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1
Handling Exceptions Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1 Objectives After completing this lesson, you should be able to do the following: Define PL/SQL
Darshan Institute of Engineering & Technology PL_SQL
Explain the advantages of PL/SQL. Advantages of PL/SQL Block structure: PL/SQL consist of block of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL
Database 10g Edition: All possible 10g features, either bundled or available at additional cost.
Concepts Oracle Corporation offers a wide variety of products. The Oracle Database 10g, the product this exam focuses on, is the centerpiece of the Oracle product set. The "g" in "10g" stands for the Grid
5. CHANGING STRUCTURE AND DATA
Oracle For Beginners Page : 1 5. CHANGING STRUCTURE AND DATA Altering the structure of a table Dropping a table Manipulating data Transaction Locking Read Consistency Summary Exercises Altering the structure
SQL Server An Overview
SQL Server An Overview SQL Server Microsoft SQL Server is designed to work effectively in a number of environments: As a two-tier or multi-tier client/server database system As a desktop database system
Working with the Geodatabase Using SQL
An ESRI Technical Paper February 2004 This technical paper is aimed primarily at GIS managers and data administrators who are responsible for the installation, design, and day-to-day management of a geodatabase.
Eventia Log Parsing Editor 1.0 Administration Guide
Eventia Log Parsing Editor 1.0 Administration Guide Revised: November 28, 2007 In This Document Overview page 2 Installation and Supported Platforms page 4 Menus and Main Window page 5 Creating Parsing
Embedding SQL in High Level Language Programs
Embedding SQL in High Level Language Programs Alison Butterill IBM i Product Manager Power Systems Agenda Introduction Basic SQL within a HLL program Processing multiple records Error detection Dynamic
AV-004: Administering and Programming with ORACLE
AV-004: Administering and Programming with ORACLE Oracle 11g Duration: 140 hours Introduction: An Oracle database is a collection of data treated as a unit. The purpose of a database is to store and retrieve
Database Management. Chapter Objectives
3 Database Management Chapter Objectives When actually using a database, administrative processes maintaining data integrity and security, recovery from failures, etc. are required. A database management
Database SQL messages and codes
System i Database SQL messages and codes Version 5 Release 4 System i Database SQL messages and codes Version 5 Release 4 Note Before using this information and the product it supports, read the information
SEER Enterprise Shared Database Administrator s Guide
SEER Enterprise Shared Database Administrator s Guide SEER for Software Release 8.2 SEER for IT Release 2.2 SEER for Hardware Release 7.3 March 2016 Galorath Incorporated Proprietary 1. INTRODUCTION...
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 A feature of Oracle Rdb By Ian Smith Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal SQL:1999 and Oracle Rdb V7.1 The
MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC
MyOra 3.0 SQL Tool for Oracle User Guide Jayam Systems, LLC Contents Features... 4 Connecting to the Database... 5 Login... 5 Login History... 6 Connection Indicator... 6 Closing the Connection... 7 SQL
The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala 2.5.30, as well as the version history.
Cloudera ODBC Driver for Impala 2.5.30 The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala 2.5.30, as well as the version history. The following are highlights
Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement
Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement List the capabilities of SQL SELECT statements Execute a basic SELECT statement
Oracle Database: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training teaches you how to write subqueries,
CA IDMS Server r17. Product Overview. Business Value. Delivery Approach
PRODUCT sheet: CA IDMS SERVER r17 CA IDMS Server r17 CA IDMS Server helps enable secure, open access to CA IDMS mainframe data and applications from the Web, Web services, PCs and other distributed platforms.
Performance Implications of Various Cursor Types in Microsoft SQL Server. By: Edward Whalen Performance Tuning Corporation
Performance Implications of Various Cursor Types in Microsoft SQL Server By: Edward Whalen Performance Tuning Corporation INTRODUCTION There are a number of different types of cursors that can be created
Oracle Database 12c: Introduction to SQL Ed 1.1
Oracle University Contact Us: 1.800.529.0165 Oracle Database 12c: Introduction to SQL Ed 1.1 Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training helps you write subqueries,
IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules
IBM Operational Decision Manager Version 8 Release 5 Getting Started with Business Rules Note Before using this information and the product it supports, read the information in Notices on page 43. This
Teradata Database. SQL Reference. Stored Procedures and Embedded SQL
Teradata Database SQL Reference Stored Procedures and Embedded SQL Release 12.0 B035-1148-067A October 2007 The product or products described in this book are licensed products of Teradata Corporation
TRANSACÇÕES. PARTE I (Extraído de SQL Server Books Online )
Transactions Architecture TRANSACÇÕES PARTE I (Extraído de SQL Server Books Online ) Microsoft SQL Server 2000 maintains the consistency and integrity of each database despite errors that occur in the
Instant SQL Programming
Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions
Data Access Guide. BusinessObjects 11. Windows and UNIX
Data Access Guide BusinessObjects 11 Windows and UNIX 1 Copyright Trademarks Use restrictions Patents Copyright 2004 Business Objects. All rights reserved. If you find any problems with this documentation,
Accessing Your Database with JMP 10 JMP Discovery Conference 2012 Brian Corcoran SAS Institute
Accessing Your Database with JMP 10 JMP Discovery Conference 2012 Brian Corcoran SAS Institute JMP provides a variety of mechanisms for interfacing to other products and getting data into JMP. The connection
Tips and Tricks SAGE ACCPAC INTELLIGENCE
Tips and Tricks SAGE ACCPAC INTELLIGENCE 1 Table of Contents Auto e-mailing reports... 4 Automatically Running Macros... 7 Creating new Macros from Excel... 8 Compact Metadata Functionality... 9 Copying,
BCA. Database Management System
BCA IV Sem Database Management System Multiple choice questions 1. A Database Management System (DBMS) is A. Collection of interrelated data B. Collection of programs to access data C. Collection of data
1 Introduction FrontBase is a high performance, scalable, SQL 92 compliant relational database server created in the for universal deployment.
FrontBase 7 for ios and Mac OS X 1 Introduction FrontBase is a high performance, scalable, SQL 92 compliant relational database server created in the for universal deployment. On Mac OS X FrontBase can
1.264 Lecture 15. SQL transactions, security, indexes
1.264 Lecture 15 SQL transactions, security, indexes Download BeefData.csv and Lecture15Download.sql Next class: Read Beginning ASP.NET chapter 1. Exercise due after class (5:00) 1 SQL Server diagrams
ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5
ERserver iseries DB2 Universal Database for iseries SQL Programming with Host Languages Version 5 ERserver iseries DB2 Universal Database for iseries SQL Programming with Host Languages Version 5 Copyright
Using the Query Analyzer
Using the Query Analyzer Using the Query Analyzer Objectives Explore the Query Analyzer user interface. Learn how to use the menu items and toolbars to work with SQL Server data and objects. Use object
PostgreSQL Audit Extension User Guide Version 1.0beta. Open Source PostgreSQL Audit Logging
Version 1.0beta Open Source PostgreSQL Audit Logging TABLE OF CONTENTS Table of Contents 1 Introduction 2 2 Why pgaudit? 3 3 Usage Considerations 4 4 Installation 5 5 Settings 6 5.1 pgaudit.log............................................
4D and SQL Server: Powerful Flexibility
4D and SQL Server: Powerful Flexibility OVERVIEW MS SQL Server has become a standard in many parts of corporate America. It can manage large volumes of data and integrates well with other products from
æ A collection of interrelated and persistent data èusually referred to as the database èdbèè.
CMPT-354-Han-95.3 Lecture Notes September 10, 1995 Chapter 1 Introduction 1.0 Database Management Systems 1. A database management system èdbmsè, or simply a database system èdbsè, consists of æ A collection
Programming Database lectures for mathema
Programming Database lectures for mathematics students April 25, 2015 Functions Functions are defined in Postgres with CREATE FUNCTION name(parameter type,...) RETURNS result-type AS $$ function-body $$
"SQL Database Professional " module PRINTED MANUAL
"SQL Database Professional " module PRINTED MANUAL "SQL Database Professional " module All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
More SQL: Assertions, Views, and Programming Techniques
9 More SQL: Assertions, Views, and Programming Techniques In the previous chapter, we described several aspects of the SQL language, the standard for relational databases. We described the SQL statements
The Import & Export of Data from a Database
The Import & Export of Data from a Database Introduction The aim of these notes is to investigate a conceptually simple model for importing and exporting data into and out of an object-relational database,
ODBC Sample Application for Tandem NonStop SQL/MX
NonStop Software SDK Application TechNote ODBC Sample Application for Tandem NonStop SQL/MX NonStop Software Developers Page The Windows NT Server program discussed in this NonStop Software Application
Modifier with Visual Basic with Applications (VBA) in Microsoft Dynamics GP 9.0
Modifier with Visual Basic with Applications (VBA) in Microsoft Dynamics GP 9.0 8520: Modifier with VBA in Microsoft Dynamics GP 9.0 (3 Days) About this Course The three-day Microsoft DynamicsT GP Modifier
Chapter 1: Introduction. Database Management System (DBMS) University Database Example
This image cannot currently be displayed. Chapter 1: Introduction Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Database Management System (DBMS) DBMS contains information
SQL Server. 1. What is RDBMS?
SQL Server 1. What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained
DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?
DBMS Questions 1.) Which type of file is part of the Oracle database? A.) B.) C.) D.) Control file Password file Parameter files Archived log files 2.) Which statements are use to UNLOCK the user? A.)
DATABASE MANAGEMENT SYSTEMS
Database Management Systems 2 DATABASE MANAGEMENT SYSTEMS J.KEERTHIKA M.Sc., B.Ed., M.Phil., Assistant Professor Dept. of Computer applications St. Joseph s college of Arts and Science Kovoor, Chennai-600
