In Touch SQL
In Touch SQL
In Touch SQL
All rights reserved. No part of this documentation shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the Invensys Systems, Inc. No copyright or patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this documentation, the publisher and the author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. The information in this documentation is subject to change without notice and does not represent a commitment on the part of Invensys Systems, Inc. The software described in this documentation is furnished under a license or nondisclosure agreement. This software may be used or copied only in accordance with the terms of these agreements.
2002 Invensys Systems, Inc. All Rights Reserved. Invensys Systems, Inc. 33 Commercial Street Foxboro, MA 02035 (949) 727-3200 http://www.wonderware.com Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Invensys Systems, Inc. cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Alarm Logger, ActiveFactory, ArchestrA, Avantis, DBDump, DBLoad, DTAnalyst, FactoryFocus, FactoryOffice, FactorySuite, hotlinks, InBatch, InControl, IndustrialRAD, IndustrialSQL Server, InTouch, InTrack, MaintenanceSuite, MuniSuite, QI Analyst, SCADAlarm, SCADASuite, SuiteLink, SuiteVoyager, WindowMaker, WindowViewer, Wonderware, and Wonderware Logger are trademarks of Invensys plc, its subsidiaries and affiliates. All other brands may be trademarks of their respective owners.
Contents
Contents
CHAPTER 1: SQL Access Manager ..................5
Introduction ............................................................................................ 5 About this Manual.................................................................................. 6 Technical Support................................................................................... 7 ODBC Compliant................................................................................... 7
CHAPTER 5: Troubleshooting.........................43
Troubleshooting Functions................................................................... 43 Result Code Error Messages............................................................. 43 InTouch SQL Access Manager Users Guide
Contents
Index..................................................................51
C H A P T E R
Wonderware FactorySuite SQL Access Manager allows you to access, modify, create and delete tables in a database. A database stores information in tables that share a common attribute or field. Structured Query Language (SQL) is the language used to access that information.
Introduction
The InTouch SQL Access Manager add-on program is designed to easily transfer data, such as batch recipes from a SQL database to an InTouch application. It also facilitates the transfer of run-time data, alarm status or historical data from InTouch to the SQL database. For example, after a machine cycle is completed, a company may need to save several sets of data, each for a different application. SQL databases provide the ability for information to be transferred between one or more third-party applications easily. SQL Access Manager allows this data to be accessed and displayed in any InTouch application. The InTouch SQL Access product consists of the SQL Access Manager program and the SQL Functions. The SQL Access Manager program is used to create and associate database columns with tagnames in your InTouch tagname dictionary. The process of associating database columns and InTouch database tagnames is called "binding." Binding the InTouch database tagnames to the database columns allows the SQL Access Manager to directly manipulate the data in the database. SQL Access Manager saves the database field names and their associations in a comma-separated variable (.CSV) formatted file named "SQL.DEF." (This file resides in the InTouch application directory and may be viewed or modified using SQL Access Manager or any text editor, such as Notepad.) The SQL Access Manager also creates Table Templates defining database structure and format. For more information on Bind Lists and Table Templates, see Chapter 3, "Configuring SQL Access Manager."
Chapter 1
SQL Functions can be used in any InTouch action script. These functions can be used to automatically execute based on operator input, a tagname value changing or when a particular set of conditions exist. For example, if an alarm condition exists, the application would execute a SQLInsert() or SQLUpdate() command to save all of the applicable data points and the state of the alarm. The SQL Functions can be used to create new tables, insert new records into tables, edit existing table records, clear tables, delete tables, select and scroll through records, etc. Note Database systems not discussed in this user's guide are not supported.
Assumptions
This manual assumes you are:
Familiar with the Windows 2000, Windows XP, and/or Windows NT operating system working environment. Knowledgeable of how to use of a mouse, Windows menus, select options, and accessing online Help. Experienced with a programming or macro language. For best results, you should have an understanding of programming concepts such as variables, statements, functions and methods.
Technical Support
Wonderware Technical Support offers a variety of support options to answer any questions on Wonderware products and their implementation. Prior to contacting technical support, please refer to the relevant chapter(s) in your SQL Access Manager User's Guide for a possible solution to any problem you may have with your system. If you find it necessary to contact technical support for assistance, please have the following information available: 1. 2. 3. 4. 5. 6. 7. 8. Your software serial number. The version of InTouch you are running. The type and version of the operating system you are using. For example, Microsoft Windows NT Version 4.0 workstation. The exact wording of system error messages encountered. Any relevant output listing from the Wonderware Logger, the Microsoft Diagnostic utility (MSD), or any other diagnostic applications. Details of the attempts you made to solve the problem(s) and your results. Details of how to recreate the problem. If known, the Wonderware Technical Support case number assigned to your problem (if this is an on-going problem).
For more information on Technical Support, see your online FactorySuite System Administrator's Guide.
ODBC Compliant
SQL Access Manager is an ODBC compliant application that communicates with any database system, provided the database system has an ODBC driver available for it. Before you can use an ODBC driver, it must be configured via the Microsoft ODBC Administrator program to set up the links between the ODBC compliant application and the database. To configure an ODBC driver 1. Run the Microsoft ODBC Administrator program.
Chapter 1
2.
Select a driver or data source, and then click Add New Name, Set Default or Configure. The ODBC Driver Setup dialog box. Description User-defined name that identifies the data source. User-defined description of this data source. Identify the directory that contains the database files. If none is specified, the current working directory is used.
Tip Enter any other information required to configure the selected driver. 3. Click OK. Tip The driver writes the values of each field to the ODBC.INI file. These values are the default values of a connection to the data source. The default values can be changed by modifying the data source fields. Entries can be inserted manually in the appropriate data source section of the ODBC.INI file for any attribute that is not supported by the ODBC Driver Setup dialog box.
C H A P T E R
SQL Access Manager supports databases developed in Oracle, Microsoft SQL Server, and Microsoft Access. Each database's requirements are unique and particular. This chapter includes separate sections for each database, describing how to configure the particular database for communication with SQL Access Manager.
Contents Using Oracle 8.0 Using Microsoft SQL Server Using Microsoft Access Data Type Values for Supported Databases
2.
SQLConnect() Format
The SQLConnect() function is used to connect to Oracle databases. The connection string used by the SQLConnect() function is formatted as follows:
SQLConnect(ConnectionId,"<attribute>=<value>; <attribute>=<value>;...");
10
Chapter 2
The following describes the attributes used by Oracle: Attribute Provider User ID Password Data Source Example
SQLConnect(ConnectionId,"Provider=MSDAORA; Data Source=OracleServer; User ID=SCOTT; Password=TIGER;");
2. 3. 4.
In the Tagname.FieldName box, type the tagname that you want to use. In the Column Name box, type the DATE_TIME delim() function. In your InTouch application, create a QuickScript to prepare input data from present date and time. For example:
11
The following describes the attributes used by Microsoft SQL Server: Attribute Provider DSN UID PWD SRVR DB Example
SQLConnect(ConnectionId,"DSN=SQL_Data;UID=OPERATOR;PWD=XYZ Z");
Value SQLOLEDB The name of the data source as configured in Microsoft ODBC Administrator. Logon ID, case sensitive. Password, case sensitive. Name of the server computer with the database tables to be accessed. The database name to be accessed.
12
Chapter 2
SQLConnect() Format
The SQLConnect() function is used to connect to Microsoft Access databases. Executing this function logs you on to the database server and opens a connection to allow other SQL functions to be executed. The connection string used by SQLConnect() is formatted as follows:
SQLConnect(ConnectionId,"<attribute>=<value>; <attribute>=<value>;...");
DSN is an attribute used by Microsoft Access and is the name of the data source as configured in the Microsoft ODBC Administrator. Example
SQLConnect(ConnectionId,"DSN=MSACC");
String Length
The valid data types that SQL Access Manager supports depends on the version of the ODBC driver being used. The text data type contains fixed length character strings and are used with InTouch Message tagnames. A length must be specified. Microsoft Access databases support text fields with a maximum length of 255 characters. InTouch Message tagnames are limited to 131 characters. If a message variable contains more characters than the length specified for a database field, the string will be truncated when inserted into the database. The Microsoft Access ODBC driver supports up to 17 characters per column name. The maximum number of columns supported when using SQLSetStatement( Select Col1, Col2, ...) is 40.
13
float
Real
14
Chapter 2
15
C H A P T E R
The SQL Access Manager utility program creates Bind Lists and Table Templates. The Bind List associates database columns with tagnames in the InTouch Tagname Data Dictionary. The Table Template defines the structure and format of a new table in the database.
Contents SQL Access Manager Overview Using Special Delimiters Configuring a Table Template The SQL.DEF File
16
Chapter 3
When a SQLInsert(), SQLSelect() or SQLUpdate() is executed, the Bind List argument defines which InTouch tagnames are used and which database columns to associate.
2.
Click New.
17
3.
Tip If you right click the mouse in any of the text entry boxes, a menu appears displaying the commands that you can apply to the selected text. 4. In the Bind List Name box, type the Bind List Name. Tip A Bind List Name can be up to 32 characters in length. The new Bind List links database columns to InTouch tagnames. For example, if an employee demographic list is being created, you would enter the Bind List Name that associates information on the employees here. Note The SQLInsert(), SQLSelect(), and SQLUpdate() functions use the Bind List parameter. 5. In the Tagname.FieldName box, type an InTouch tagname.field name. Tip The Tagname Dictionary associates this tagname.field with the Column Name in the database. If this tagname is not currently defined in the Tagname Dictionary, double-click it to open the Tagname Dictionary dialog box and define it now. 6. Click Tagname to select an existing tagname. The Tag Browser appears. Tip The Tag Browser will display the tagnames for the currently selected tag source. To select a tagname, double-click it or select it, and then click OK. To select a .field for the tagname click the Dot Field arrow, and select the .field that you want to use, and then click OK.
18
Chapter 3
Note I/O type tagnames that are not used in your application, but are specified in a SQLAccess bind list, will be activated (advised to the I/O Server) as soon as WindowViewer starts up. No connect to a database is necessary to see this behavior. For more information on the Tag Browser, see your online InTouch User's Guide. 7. 8. Click FieldName to append a .field to the tagname. The Choose field name dialog box appears. Click the .field that you want to use. The dialog box will close and the .field will automatically be appended to the tagname in the Tagname.FieldName field. For more information on tagname .fields, see Chapter 4 in your InTouch User's Guide. 9. In the Column Name box, type the name of the column. Tip A Column Name can be up to 30 characters in length. The column name is directly associated with the database column name. If the Column Name has a space, use square brackets around the Column Name in the Bind List and when used in a script. For example:
WHERE EXPR= "[Pipe Flow} = " + text (tagname,"#");
Tip Special Delimiters can also be used to associate your column name with your database. For more information on special delimiters, see "Using Special Delimiters" 10. Click Move Up to move the selected tagname up one level in the list. 11. Click Move Down to move the selected tagname down one level in the list. 12. Click Add Item to add your new Tagname.FieldName and Column Name to the Bind List. 13. Click Delete Item to delete a selected Tagname.FieldName and Column Name from the Bind List. 14. Click Modify Item to modify a selected Tagname.FieldName or Column Name for this Bind List. 15. Click OK to save your new Bind List configuration and close the dialog box. Tip You can click Save to save your settings without closing the dialog box. To modify a Bind List 1. On the Special menu, point to SQL Access Manager, and then click Bind List, or in the Application Explorer under SQL Access Manager, doubleclick Bind List.
19
2.
3. 4.
Select the Bind List name that you want to change, and then click Modify. The Bind List Configuration dialog box appears. Modify the required item(s).
5. Click OK to save your changes and close the dialog box. For more information on configuring a Bind List, see "To create a new Bind List." To delete a Bind List 1. On the Special menu, point to SQL Access Manager, and then click Bind List, or in the Application Explorer under SQL Access Manager, doubleclick Bind List. The Select a Bind List dialog box appears.
2.
3. 4.
Select the Bind List name that you want to delete. Click Delete. A message box appears asking you to confirm your deletion. Click Yes to delete the selected Bind List, or click No to cancel the deletion. The Bind List Configuration dialog box reappears. Click OK to close the dialog box.
5.
20
Chapter 3
Example: datestring delim (,) To use the same delimiter for both left and right, just specify the delimiter in parentheses without the comma. Example: datestring delim ( ) The following example uses different left and right delimiters. Notice where date delim (,) is entered in the Column Name field.
For more information on logging date and time to an Oracle date field, see Chapter 2, "Configuring and Connecting Databases."
21
To create a new Table Template 1. On the Special menu, point to SQL Access Manager, and then click Table Template, or in the Application Explorer under SQL Access Manager, double-click Table Template.
2. 3.
Tip If you right click the mouse in any of the text entry boxes, a menu appears displaying the commands that you can apply to the selected text. 4. In the Table Template Name box, type the name of the Table Template. Note A Table Template Name can be up to 32 characters in length. If you are creating an index, unique or otherwise, the Table Template Name can not exceed 24 characters. The Table Template name is used to identify the structure of a database for the SQLCreateTable() function. 5. In the Column Name box, type the column name for the Table Template. A Column Name can be up to 30 characters in length. InTouch SQL Access Manager Users Guide
22
Chapter 3
6.
In the Column Type box, type the data type for the column. Data type selections vary according to the database being used. For more information on data types for a specific database, see Chapter 2, "Configuring and Connecting Databases."
7.
Select the Index Type as follows: Unique A column requires that each value in that column be unique. Non-Unique A column does not require that each value in that column be unique. None No Index. Tip When you execute a SQLCreateTable(), an index file is automatically created.
8.
Select Allow Null Entry to allow null data to be entered in this column. Note InTouch does not support null data. When inserting data, if a value has not been entered for a tagname, values will be:
When selecting data, null values will be translated according to the data type as shown above. 9. Click Add Item to add your new Column Name, Column Type, Length and Index Type to the Table Template.
10. Click Delete Item to delete a selected Column Name, Column Type, Length and Index Type from the Table Template list. 11. Click Modify Item to modify a selected Column Name, Column Type, Length and Index Type in the Table Template list. 12. Click OK to save your new Table Template configuration and close the dialog box. Tip You can click Save to save your settings without closing the dialog box. To modify a Table Template 1. On the Special menu, point to SQL Access Manager, and then click Table Template, or in the Application Explorer under SQL Access Manager, double-click Table Template.
23
2.
3. 4. 5.
Select the Table Template name that you want to modify, and then click Modify. The Table Template Configuration dialog box appears. Modify the required item(s). Click OK to save your changes and close the dialog box. For more information on configuring a Table Template, see "To create a new Table Template."
To delete a Table Template 1. On the Special menu, point to SQL Access Manager, and then click Table Template, or in the Application Explorer under SQL Access Manager, double-click Table Template. The Select a Table Template dialog box appears.
2.
3. 4.
Select the Table Template name that you want to delete Click Delete. A message box appears asking you to confirm your deletion. Click Yes to delete the selected Bind List, or click No to cancel the deletion. The Table Template Configuration dialog box reappears. Click OK to close the dialog box.
5.
24
Chapter 3
25
C H A P T E R
InTouch uses SQL Functions to interact with information in the database. These functions are an extension of the standard InTouch QuickScript functions and can be used in any script. They allow you to select, modify, insert or delete records in the tables you choose to access.
Contents SQL Functions SQL Parameters Using SQL Functions in InTouch QuickScripts\
SQL Functions
This section lists each SQL Function. Keep in mind that SQL actions are synchronous. Control is not returned to InTouch until the SQL activity is complete (InTouch trending, polling, etc. are suspended). All SQL Functions (with the exception of SQLNumRows()) return a ResultCode. If the ResultCode is non-zero, the function failed and other actions should be taken. The ResultCode can be used by the SQLErrorMsg() function. The general format for SQL Functions is as follows:
SQLFunction(Parameter1, Parameter2,...)
For complete details on each SQL function and examples of how you use each function, see your InTouch Reference Guide.
Function
SQLAppendStatement(ConnectionId, SQLStatement)
Append the statement SQLStatement to the default SQL statement for ConnectionId.
26
Chapter 4
SQLClearParam(StatementId, ParameterNumber)
Set the value of ParameterNumber associated with StatementId to zero or a zero-length string, depending on whether the parameter is of numeric or string type.
SQLClearStatement(ConnectionId, StatementId)
Clean up resources associated with StatementId. However, the default statement associated with ConnectionId remains intact.
SQLClearTable(ConnectionId, TableName)
Delete all rows in the table named TableName.
SQLCommit(ConnectionId)
Commit the transaction that was created by the last SQLTransact.
SQLConnect(ConnectionId, ConnectString)
The ConnectString parameter is the same ConnectionString as explained in most ADO documentations (probably most extensively by Microsoft ADO API Reference). It is a parameter that may need to be modified in any InTouch application to leverage the power of native OLE DB provider for a particular database management system. A general form of the ConnectString parameter consists of different components separated by semicolons. The first component is normally specified as Provider=ProviderName, where ProviderName is the OLE DB provider for the particular database system. The SQLConnect functions in existing InTouch applications do not have the Provider keyword in the ConnectString parameter, thus ADO will use the default provider, Microsoft OLE DB Provider for ODBC, which is MSDASQL.DLL. Although existing InTouch applications will continue to work, it is highly recommended that the ConnectString parameter be changed to use the native OLE DB provider. Examples of ConnectString include the following: Example 1 Microsoft OLE DB Provider for Microsoft Jet (recommended use) "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\DBName.mdb;User ID=UserIDStr;Password=PasswordStr;" Microsoft.Jet.OLEDB.4.0 is the native OLE DB Provider for Microsoft Jet (Microsoft Access Database engine). Example 2 Microsoft OLE DB Provider for ODBC (using the default provider MSDASQL for MS Access): "Provider=MSDASQL;DSN=DSNStr;UID=UserName;PWD=PasswordStr;"
27
Note User ID and uid can be used interchangeably, and Password and pwd can be used interchangeably. However, as stated above, it is recommended that the ConnectString parameter uses Microsoft.Jet.OLEDB.4.0. Example 3 Microsoft OLE DB Provider for SQL Server (recommended use) "provider=sqloledb;Data Source=MyServer;Initial Catalog=MyDB;User Id=sa;Password=;" The OLE DB Provider for SQL Server is sqloledb. Example 4 Microsoft OLE DB Provider for SQL Server (recommended use) "Provider=SQLOLEDB;uid=sa;pwd=;Database=MyDB" Example 5 Microsoft OLE DB Provider for ODBC (using the default provider MSDASQL for SQL Server): "DSN=Pubs;UID=sa;PWD=;" Example 6 Microsoft OLE DB Provider for ODBC (using the default provider MSDASQL for SQL Server): "Data Source=Pubs;User ID=sa;" "Password=;" Note Data Source and Server can be used interchangeably, and Initial Catalog and Database can be used interchangeably. Example 7 Microsoft OLE DB Provider for Oracle (recommended use) "Provider=MSDAORA;Data Source=ServerName;User ID=UserIDStr; Password=PasswordStr;" If SQLTrace=1 is defined under the [InTouch] section of the win.ini file, each successful execution of SQLConnect will log version information for the ADO, the provider and the database system to the Wonderware logger.
28
Chapter 4
SQLDisconnect(ConnectionId)
Disconnect from the database and clean up all resources that were created by SQLPrepareStatement and SQLInsertPrepare that have not yet been released (by executing SQLClearStatement and SQLInsertEnd).
SQLDropTable(ConnectionId, TableName)
Delete the table named TableName from the database.
SQLEnd(ConnectionId)
Clean up resources associated with the logical table associated with ConnectionId.
SQLErrorMsg(ResultCode)
Return a ResultCode of -1 whenever an error is generated by the database provider. The ResultCode returned is always -1, but the message is copied exactly from the provider. For a list of Result Codes and a description of the error messages, see Chapter 5, "Troubleshooting."
SQLFirst(ConnectionId)
Go to the first row of the logical table and fetch values of that row into InTouch tags.
SQLGetRecord(ConnectionId, RecordNumber)
Go to row number RecordNumber of the logical table and fetch values of that row into InTouch tags.
SQLInsertEnd(ConnectionId, StatementId)
Clean up resources associated with StatementId created by SQLInsertPrepare.
29
SQLLast(ConnectionId)
Go to the last row of the logical table and fetch values of that row into InTouch tags.
SQLLoadStatement(ConnectionId, FileName)
Load the statement contained in the file FileName into the default statement for ConnectionId.
SQLManageDSN(ConnectionId)
The ConnectionId is not used. It is retained for backward compatibility of older versions of SQL Access. Therefore, any number can be passed into the function. No database connection needs to be established before this function can be called. Example
SQLManageDSN( 0 )
SQLNext(ConnectionId)
Go to the next row of the logical table and fetch values of that row into InTouch tags.
30
Chapter 4
SQLNumRows(ConnectionId)
Return the number of rows of the logical table. Because this function may return an error code, the recommended use of the function is as follows:
DIM TEMP AS INTEGER; TEMP = SQLNumRows(ConnectionId); IF (TEMP >= 0) THEN RowCount = TEMP; ELSE ResultCode = TEMP; ENDIF;
Definition A default statement is a statement associated with a connection ID. It can be a textual SQL statement (SELECT, INSERT, DELETE, or UPDATE), the name of a query in MS Access (with or without parameters), or the name of a stored procedure in MS SQL Server (with or without parameters). The default statement is modified by SQLLoadStatement, SQLSetStatement and SQLAppendStatement and is used by SQLExecute whenever StatementId = 0 is specified.
SQLPrepareStatement(ConnectionId, StatementId)
Prepare the default statement and return a StatementId (1, 2, 3, and so on). This preparation is useful for statements with parameters that need to be set using the SQLSetParam{Type} functions. SQLHandle is specified as the second parameter to this function in older versions of SQL Access; however, the current version of SQL Access renames SQLHandle into StatementId for all functions. The functional behavior remains the same.
SQLPrev(ConnectionId)
Go to the previous row of the logical table and fetch values of that row into InTouch tags.
SQLRollback(ConnectionId)
Roll back the transaction that was created by the last SQLTransact.
31
If the statement is executed successfully, a temporary record set (referred to as the logical table) is created and the BindList is used to associate InTouch tags with the columns of this table in preparation for SQLFirst, SQLPrev, SQLNext, SQLLast, and SQLNumRows. This logical table remains valid even if it has no row. For example, if WhereExpr is False for all records.
32
Chapter 4
33
GO
SQLSetStatement(ConnectionId, SQLStatement)
Set the statement SQLStatement into the default SQL statement for ConnectionId.
SQLTransact(ConnectionId)
Begin a database transaction. Transactions can be nested as supported by the underlying OLE DB provider for the database system. For example, native OLE DB provider for Microsoft Jet supports transactions nested up to five levels, including the first and last transactions.
SQLUpdateCurrent(ConnectionId)
Update the current row of the logical table using InTouch tags mapped to the table fields via the bind list specified in SQLSelect or SQLExecute. If there are rows that are identical to the current row, all of them will be updated. If there are too many identical rows to be updated in SQL Access, this function may return an error after updating a number of rows. The error message may be similar to, "Microsoft Cursor Engine: Key column information is insufficient or incorrect. Too many rows were affected by update." Up to 54 identical rows may be modified at once.
34
Chapter 4
To avoid this situation, create a unique key field in the table so that no rows are identical. It is strongly recommended that all tables used by SQL Access have a unique key. For a table without a key, it is recommended that a field of type AutoNumber (MS Access) or an integer field used as the row Identity (SQL Server) be used as the primary key so that SQLUpdateCurrent affects only one row. This primary key field does not have to be included in a BindList.
SQL Parameters
The following describes the parameters required for each SQL function. When a parameter is entered in a script surrounded by quotation marks ("Parameter1") that exact string will be used. If no quotation marks are used, Parameter1 is assumed to be a tagname and the system will access the InTouch tagname dictionary for the value of the tagname, Parameter1. Example
"c:\main\file" vs. Location
where: location is an InTouch message tagname "c:\main\file" is a literal string The parameters for most of the SQL functions will be one or more of the following:
BindList
Corresponds to one of the Bind List names in the SQL.DEF file.
ConnectionID
Memory integer tagname created by the user to hold the number (ID) assigned by the SQLConnect function to each database connection.
ConnectString
String that identifies the database and any additional logon information used in SQLConnect().
ErrorMsg
Message variable containing a text description of the error message. For more information on error message descriptions, see Chapter 5, "Troubleshooting."
FileName
The name of the file name in which the information is contained.
35
MaxLen
Maximum size of the column with which this parameter is associated. This setting determines whether the parameter is of varying character or long varying character type. If MaxLen is less than or equal to the largest character string allowed by the database, then the parameter is varying character type. If greater, long varying character type.
OrderByExpression
Defines the columns and direction for sorting. Only column names can be used to sort. The expression must be formatted: ColumnName [ASC|DESC] To sort the selected table by a column name (e.g., manager) in ascending order: "manager ASC" To sort by multi-columns, the expression is formatted: ColumnName [ASC|DESC], ColumnName [ASC|DESC] To sort a selected table by one column name (for example, temperature) in ascending order and another column name (for example, time) in descending order: "temperature ASC, time DESC"
ParameterNumber
Actual parameter number in the statement.
ParameterType
Data type of the specified parameter. Valid values: Type Char Var Char Decimal Integer Small integer Float Double Precision Float DateTime Date Description Blank Padded fixed length string Variable Length String BCD Number 4-byte signed integer 2-byte signed integer 4-byte floating point 8-byte floating point 8-byte date time value 4-byte date time value
36
Chapter 4
ParameterValue
Actual value to set.
Precision
Is the decimal value's precision, the max. size of the character, or the length in bytes of the date-time value.
RecordNumber
Actual record number to retrieve.
ResultCode
Integer variable returned from most SQL functions. ResultCode is returned as zero (0) if the function is successful and a negative integer if it fails. For more information, see Chapter 5, "Troubleshooting."
Scale
Is the decimal value's scale. This value is required only if applicable to the parameter being set to null.
StatementId
When using the advanced functionality statements, SQL returns a StatementId, which it uses internally.
SQLStatement
Actual statement, for example:
ResultCode=SQLSetStatement(ConnectionID,Select LotNo, LotName from LotInfo);
TableName
The database table name you want to access.
TemplateName
The name of the template definition you want to use.
37
WhereExpression
Defines a condition that can be either true or false for any row of the table. The command extracts only those rows from the table for which the condition is true. The expression must be in the following format: ColumnName comparison_operator expression Note If the column is a character data type, the expression must be in single quotes. The following example will select all rows whose name column contains the value EmployeeID:
name='EmployeeID'
The following example will select all rows containing part numbers from 100 to 199:
partno>=100 and partno<200
The following example will select all rows whose temperature column contains a value that is greater than 350:
temperature>350
38
Chapter 4
The statement is now ready for execution. Note Many database column and table names are case sensitive. For the above script to function properly, the column and database names must be typed exactly as used in the database tables.
39
To perform parameter substitution on a SQL statement, put a "?" in the SQL statement where you want to specify a parameter at a later date. The statement is "prepared," parameters are "set" into the statement, and then the statement is executed. SQLPrepareStatement() prepares the statement for execution. It does not execute the statement, it just makes the statement active so you can set parameter values. SQLSetParamType() is a set of functions that allow you to set values into parameters in the SQL statement. Example
ResultCode = SQLSetStatement (ConnectionID, "Select LotNo, LotName, LotDescription, LotQuantity from LotInfo, ProductionInfo"); ResultCode = SQLAppendStatement (ConnectionID, " where LotInfo.LotNo = ?"); ResultCode = SQLAppendStatement (ConnectionID, " order by LotNo,NotName,LotQuantity"); ResultCode = SQLPrepareStatement (ConnectionID, StatementId); {return the statement handle into tag 'StatementId'} ResultCode = SQLSetParamInt (StatementId, 1, tagLotNumber); {put the value of tagLotNumber into param}
Since the statement only has one parameter, it is now ready for execution. Once the statement is executed and you are finished with the prepared statement, SQLClearStatement() can be called to free the resources associated with that statement. Note SQLEnd() is called to free "unnamed" SQL statements (those generated by existing SQL Access functions), and those statements created by SQLSetStatement() and SQLLoadStatement() and not prepared.
40
Chapter 4
Example 2
ResultCode = SQLSetStatement (ConnectionID, "Select LotNo, LotName, LotDescription, LotQuantity from LotInfo, ProductionInfo"); ResultCode = SQLAppendStatement (ConnectionID, " where LotInfo.LotNo = ?"); {question mark means I'll get back to you}
ResultCode = SQLAppendStatement (ConnectionID, " order by LotNo,NotName,LotQuantity"); ResultCode = SQLPrepareStatement (ConnectionID, StatementId); {return the statement handle into tag 'StatementId'} ResultCode = SQLSetParamInt (StatementId, 1, tagLotNumber); {put the value of tagLotNumber into param} ResultCode = SQLExecute (ConnectionID, "BindList", StatementId); {put the results of the Select into the tags specified in BindList prepared statement handle is in StatementId} ResultCode = SQLNext (ConnectionID); {Get results of Select}
Example 3 SQLSetStatement This statement must be used for complex queries and string expressions greater than 131 characters. When the string expression exceeds 131 characters use the SQLAppend
SQLSetStatement(ConnectionID, Select Speed, Ser_No from tablename where Ser_No = + Serial_input + ); SQLExecute(ConnectionID, "BindList", 0);
In the above example the StatementId is set to zero so the statement does not have to call SQLPepare(Connection_Id, StatementId) before the execute statement. Because the StatementId was not created by the SQLPepare to properly end this select use the SQLEnd function instead of the SQLClearStatement().
SQLSetStatement(Connection_Id, Select Speed, Ser_No from tablename where Ser_No = + Serial_input + ); SQLPrepareStatement(Connection_Id, StatementId); SQLExecute(Connection_Id, StatementId);
In the above example the StatementId is created by the SqlPrepareStatement and used in the SQLExecute function. To end this select statement use SQLClearStatement to free up resources and free the StatementId.
41
42
Chapter 4
Troubleshooting
43
C H A P T E R
Troubleshooting
This chapter explains how to troubleshoot SQL applications using the Result Codes returned by SQL functions. The first section describes the SQLErrorMsg() function and includes a table of SQL Result Codes with their corresponding Error Messages. The second section includes tables with specific database Error Messages.
Contents Troubleshooting Functions Specific Database Error Messages Debugging SQL Access
Troubleshooting Functions
All SQL Functions return a Result Code that can be used for troubleshooting. The SQLErrorMsg() function returns the Error Message associated with the Result Code. Example
ErrorMsg=SQLErrorMsg(ResultCode);
where: ErrorMsg is a memory message tag. ResultCode is an integer value obtained from a previous SQL function.
44
Chapter 5
The SQLErrorMsg() function will set the value of the InTouch message tagname ErrorMsg. The following is a listing of some of the possible SQL Result Codes and their corresponding error messages and descriptions: Result Code Error Message 0 -1 -2 No errors occurred <Message from DB Provider> An empty statement cannot be executed Value returned was Null Description The command was successful <A specific error message from the DB provider> SQLExecute(ConnectionId, BindList, 0) is executed without previously calling SQLSetStatement or SQLLoadStatement with a non-empty statement. An integer or real value read from the database is null. This is only a warning sent to Wonderware Logger. The last record in the table has been reached SQLSetParamI{Type} is called with an invalid parameter ID. Example of an invalid parameter list: 1, 2, 3, 5 (Missing 4). SQLSetParamNull is called with an invalid type. SQLSetParam {Type} is called with a different type for an existing parameter. SQLSetParam {Type} is called for a new parameter ID after the statement has been executed successfully. An invalid date time format is encountered, for example, when executing SQLSetParamTime, SQLInsertExecute, or SQLUpdateCurrent. An invalid decimal format is encountered, for example, when executing SQLSetParamDecimal, SQLInsertExecute, or SQLUpdateCurrent. An invalid currency format is encountered, for example, when executing SQLInsertExecute or SQLUpdateCurrent. SQLInsertEnd is called for a statement ID created by SQLPrepareStatement or SQLClearStatement is called for a statement ID created by SQLInsertPrepare. There is insufficient memory to perform this function. The ConnectionId passed to the function is not valid. The specified Bind List name does not exist. The specified Table Template name does not exist. An internal error occurred. Call Technical Support.
-4
-5 -7 -8 -9 -10 -11
No more rows to fetch Invalid parameter ID Invalid parameter list Invalid type for NULL parameter Changing data type of parameter is not allowed Adding parameter after the statement has been executed successfully is not allowed. Invalid date time format
-12
-13
-14
-15
Out of memory Invalid connection No bind list found No template found Internal Error
Troubleshooting
45
Result Code Error Message -1006 -1007 String is null String is truncated
Description Warning - the string read from the database is null. This is only a warning sent to Wonderware Logger. Warning - the string read from the database is longer than 131 characters and is truncated on a select. The warning is sent to Wonderware Logger. There is no Where clause on Delete. Check Wonderware Logger for a more detailed description of the failed connect.
The database specified on the The specified database does not exist. DB= portion of the connect string does not exist No rows were selected A SQLNumRows(), SQLFirst(), SQLNext(), SQLLast, or SQLPrev() command was attempted without executing a SQLSelect() or SQLExecute command first. SQLLoadStatement is called with a filename that cannot be found.
-1011
-1013
There is not enough memory Try rebooting the client workstation. available to process the command Invalid object name table name The table name does not exist in the database you are using. Try DB=database name.
Check you Microsoft SQL Server documentation for specific error messages and solutions.
46
Chapter 5
Reserved Keywords
47
A P P E N D I X
Reserved Keywords
48
Appendix A
DEFERRED ENTF DESC DESCRIBE DESCRIPTOR DIAGNOSTICS DICTIONARY DISCONNECT DISPLACEMENT DISTINCT DOMAIN DOUBLE DROP ELSE ENDEESC EXCEPT EXCEPTION EXEC EXECUTE EXISTS EXTERNAL EXTRACT FALSE FETCH FIRST FLOAT FOR FOREIGN FORTRAN FOUND FROM FULL GET GLOBAL GO GOTO GRANT GROUP HAVING HOUR IDENTITY IGNORE IMMEDIATE IN INCLUDE INDEX INDICATOR INITIALLY INNER INPUT INSENSITIVE EINFGEN INTEGER INTERSECT INTERVALL INTO
IS ISOLATION JOIN KEY LANGUAGE LAST LEFT LEVEL LIKE LOCAL LOWER MATCH MAX MIN MINUTE MODULE MONTH MUMPS NAMES NATIONAL NCHAR NEXT NONE NOT NULL NULLIF NUMERIC OCTET_LENGTH OF OFF ON ONLY OPEN OPRN OPTION OR ORDER OUTER OUTPUT OVERLAPS PARTIAL PASCAL PLI POSITION PRECISION PREPARE PRESERVE PRIMARY PRIOR PRIVILEGES PROCEDURE PUBLIC RESTRICT REVOKE
RIGHT ROLLBACK ROWS SCHEMA SCROLL SECOND SECTION SELECT SEQUENCE SET SIZE SMALLINT SOME SQL SQLCA SQLCODE SQLERROR SQLSTATE SQLWARNING SUBSTRING SUM SYSTEM TABLE TEMPORARY THEN TIME TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINU TO TRANSACTION TRANSLATE TRANSLATION TRUE UNION UNIQUE UNKNOWN UPDATE UPPER USAGE USING WERT VALUES VARCHAR VARING VIEW WHEN WHENEVER WHERE WITH WORK YEAR
Reserved Keywords
49
InTouch
The following are reserved keywords for InTouch: As Call Dim Discrete Integer Message Real Return RetVal
50
Appendix A
51
Index
A
About this Manual 6 SQLGetRecord 28 SQLInsert 28 SQLInsertEnd 28 SQLInsertExecute 29 SQLInsertPrepare 29 SQLLast 29 SQLLoadStatement 29 SQLManageDSN 29 SQLNumRows 30 SQLPrepareStatement 30 SQLPrev 30 SQLRollback 30 SQLSelect 30 SQLSetParamChar 31 SQLSetParamDate 31 SQLSetParamDecimal 31 SQLSetParamFloat 31 SQLSetParamInt 32 SQLSetParamLong 32 SQLSetParamNull 32 SQLSetParamTime 33 SQLSetStatement 33 SQLTransact 33 SQLUpdate 33 SQLUpdateCurrent 33 Using 25
B
Bind List 16 create new 16 delete 19 modify 18 Tag Browser 17 BindListName 23, 34 Building queries dynamically 38
C
Column Name 18 Commands Table Template 22 Configuring a Bind List 16 Configuring a Table Template 20 Configuring SQL Access Manager 15 ConnectionID 34 ConnectString 34 CSV 5, 23
D
Data Types Supported 13 Database 5 Databases Supported 11 Microsoft Access 12 Microsoft SQL Server 11 deleting a Bind List 19 deleting a table template 23 Delim Function 19 Delimiters 19
L
Logging Date and Time to an Oracle Date Field 10
M
MaxLen 35 Microsoft Access Connection Requirements 12 Data Types Supported 12, 13 Microsoft SQL Server Connection Requirements 11 Data Types Supported 12 Mircrosoft SQL Server Data Types Supported 13 modify a Bind List 18 modifying a table template 22 Modifying extended SQL Statements 38
E
ErrorMsg 34 Executing extended SQL Statements 39
F
FileName 34 Functions SQLAppendStatement 25 SQLClearParam 26 SQLClearStatement 26 SQLClearTable 26 SQLCommit 26 SQLConnect 11 SQLCreateTable 27 SQLDelete 27 SQLDisconnect 28 SQLDropTable 28 SQLEnd 28 SQLErrorMsg 28 SQLExecute 28 SQLFirst 28
O
ODBC Administrator Program 7 ODBC Compliant 7 ODBC.INI 8 Online manuals 6 Oracle Data Types Supported 13 OrderByExpression 35
P
Parameter BindListName 34 ConnectionID 34
52
ConnectString 34 ErrorMsg 34 FileName 34 MaxLen 35 OrderByExpression 35 ParameterNumber 35 ParameterType 35 ParameterValue 36 Precision 36 RecordNumber 36 ResultCode 36 Scale 36 SQLStatement 36 StatementId 36 TableName 36 TemplateName 36 WhereExpression 37 ParameterNumber 35 Parameters 34 ParameterType 35 ParameterValue 36 Precision 36
T
Table Template 20 create new 21 delete 23 modify 22 Table Template Command 22 Table Template Name 21, 24 TableName 36 Tag Browser 17 Tagname.FieldName 18 TemplateName 36 Troubleshooting 43 Troubleshooting SQL Functions 43
U
Using Microsoft Access 12 Using Microsoft SQL Server 11 Using Special Delimiters 19 Using SQL Functions 25 Using SQL Functions in InTouch 37
Q
Queries Building Dynamically 38 Complex 38 QuickScripts 37
W
WhereExpression 37 Wonderware Technical Support 7
R
Reading SQL Statements from a File 38 RecordNumber 36 Reserved Keywords 47 Result Code Error Messages 43 ResultCode 36, 43
S
Scale 36 Specific Database Error Messages Microsoft SQL Server 45 Specifying Complex Queries 37 SQL Access Manager Introduction 5 SQL Access Manager Overview 15 SQL Function format 25 SQL Parameters 34 SQL.DEF 5, 23 SQLConnect 11 SQLErrorMsg 43 SQLInsert 19 SQLSelect 30 SQLStatement 36 SQLUpdate 19, 33 StatementId 36 Structured Query Language 5 Supporting Stored Procedures 41