Caché Transact-SQL (TSQL) Migration Guide - InterSystems ...

intersystems.com

Caché Transact-SQL (TSQL) Migration Guide - InterSystems ...

Caché Transact-SQL(TSQL) Migration GuideVersion 5.201 September 2006InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com


3.5 Assignment Statements .......................................................................................... 183.5.1 DECLARE .................................................................................................... 183.5.2 SET ............................................................................................................... 183.6 Transaction Statements .......................................................................................... 193.6.1 SET TRANSACTION ISOLATION LEVEL .............................................. 193.6.2 BEGIN TRANSACTION ............................................................................. 193.6.3 COMMIT TRANSACTION ......................................................................... 193.6.4 ROLLBACK TRANSACTION .................................................................... 193.6.5 CHECKPOINT ............................................................................................. 203.7 Other Statements .................................................................................................... 203.7.1 CREATE PROCEDURE / CREATE FUNCTION ....................................... 203.7.2 DROP PROCEDURE ................................................................................... 203.7.3 EXECUTE .................................................................................................... 203.7.4 GRANT ........................................................................................................ 213.7.5 PRINT .......................................................................................................... 213.7.6 USE database ................................................................................................ 213.8 InterSystems Extensions ........................................................................................ 213.8.1 CACHE ......................................................................................................... 213.8.2 IMPORTASQUERY ..................................................................................... 223.8.3 SETTINGS ................................................................................................... 224 TSQL Functions ............................................................................................................. 274.1 Supported Functions .............................................................................................. 274.1.1 ABS .............................................................................................................. 274.1.2 ASCII ............................................................................................................ 274.1.3 CAST ............................................................................................................ 274.1.4 CEILING ...................................................................................................... 284.1.5 CHAR ........................................................................................................... 284.1.6 CHARINDEX .............................................................................................. 284.1.7 CONVERT ................................................................................................... 284.1.8 CURRENT_TIMESTAMP ........................................................................... 294.1.9 CURRENT_USER ....................................................................................... 294.1.10 DATALENGTH .......................................................................................... 294.1.11 DATEADD ................................................................................................. 304.1.12 DATEDIFF ................................................................................................. 304.1.13 DATENAME .............................................................................................. 314.1.14 DAY ............................................................................................................ 32ivCaché Transact-SQL (TSQL) Migration Guide


4.1.15 DB_NAME ................................................................................................. 334.1.16 FLOOR ....................................................................................................... 334.1.17 GETDATE .................................................................................................. 334.1.18 HOST_NAME ............................................................................................ 334.1.19 ISNULL ...................................................................................................... 334.1.20 ISNUMERIC .............................................................................................. 344.1.21 LEFT .......................................................................................................... 344.1.22 LEN ............................................................................................................ 344.1.23 LOG ............................................................................................................ 344.1.24 LOWER ...................................................................................................... 344.1.25 LTRIM ........................................................................................................ 344.1.26 MONTH ..................................................................................................... 354.1.27 NULLIF ...................................................................................................... 354.1.28 OBJECT_ID ............................................................................................... 354.1.29 PATINDEX ................................................................................................. 354.1.30 POWER ...................................................................................................... 364.1.31 RAND ......................................................................................................... 364.1.32 RAISERROR .............................................................................................. 364.1.33 REPLACE .................................................................................................. 364.1.34 REPLICATE ............................................................................................... 364.1.35 REVERSE .................................................................................................. 364.1.36 RIGHT ........................................................................................................ 374.1.37 ROUND ...................................................................................................... 374.1.38 RTRIM ........................................................................................................ 374.1.39 SCOPE_IDENTITY ................................................................................... 374.1.40 SIGN ........................................................................................................... 374.1.41 SPACE ........................................................................................................ 384.1.42 STR ............................................................................................................. 384.1.43 STUFF ........................................................................................................ 384.1.44 SUBSTRING .............................................................................................. 394.1.45 SUSER_NAME .......................................................................................... 394.1.46 UPPER ........................................................................................................ 394.1.47 USER .......................................................................................................... 394.1.48 USER_ID .................................................................................................... 394.1.49 USER_NAME ............................................................................................ 394.1.50 YEAR ......................................................................................................... 404.2 Unsupported Functions .......................................................................................... 40Caché Transact-SQL (TSQL) Migration Guidev


5 TSQL Variables .............................................................................................................. 415.1 Host Variables and Literals .................................................................................... 415.2 Special Variables .................................................................................................... 425.2.1 @@DATEFIRST .......................................................................................... 425.2.2 @@ERROR ................................................................................................. 425.2.3 @@FETCH_STATUS .................................................................................. 425.2.4 @@IDENTITY ............................................................................................ 425.2.5 @@ROWCOUNT ........................................................................................ 435.2.6 @@SPID ...................................................................................................... 435.2.7 @@SQLSTATUS ......................................................................................... 435.2.8 @@TRANSCOUNT .................................................................................... 435.2.9 @@VERSION ............................................................................................. 436 Using the TSQL Shell .................................................................................................... 456.1 Getting Started ....................................................................................................... 456.1.1 Caché Commands in the TSQL Shell ........................................................... 466.1.2 Compiling a Table Definition ....................................................................... 466.1.3 Using the GENRAW Setting ........................................................................ 476.1.4 TSQL Shell Help .......................................................................................... 486.1.5 Exiting the TSQL Shell ................................................................................ 486.2 Qualifiers ................................................................................................................ 486.3 Settings ................................................................................................................... 49viCaché Transact-SQL (TSQL) Migration Guide


1OverviewCaché TSQL is an implementation of Transact-SQL which supports many of the features ofboth the Microsoft and Sybase implementations. Transact-SQL is used with Microsoft SQLServer and Sybase Adaptive Server.Caché TSQL also contains a few proprietary extensions not found in either of these implementations.These are described in the Commands chapter.This document will help you to quickly migrate schemas and stored procedures from Microsoftor Sybase databases and it will provide you with an understanding of the TSQL (Transact-SQL) implementation in Caché.1.1 Getting StartedBefore you begin, go into the Caché System Management Portal, select Configuration, thenselect SQL Settings to set the SQL configuration setting Support Delimited Identifiers to “Yes”.In the System Management Portal, select Configuration, then select Advanced Settings, selectthe category SQL to map any needed UserDataTypes.The initial application migration is simple:1. Migrate the DDL Schema: Table and view definitions can be moved using the CachéSQL Link Table Wizard. Go to the System Management Portal, select SQL, then selectLink Table Wizard. When you are done, be sure to compile the package(s).Alternatively, you can invoke DO $System.SQL.DDLImport(), DO$System.SQL.Sybase() or DO $System.SQL.MSSQLServer() to import the schema.For further details, see the Caché Class Reference.Caché Transact-SQL (TSQL) Migration Guide 1


Overview2. Create a tsql.ini: This file should be in the same directory that contains the stored procedurefiles (.sql). This file is used during the import. If it is anywhere other than thedirectory containing the *.sql files, it won’t have any effect. An example TSQL.INI file isshown below:SET QUOTED_IDENTIFIER OFFSETTINGS UNDERLINE=zSET TRANSACTION ISOLATION LEVEL READ COMMITTEDSET ANSI_NULLS ONSET ROWCOUNT 0SET TEXTSIZE 200SET NOCOUNT ON3. Migrate the Stored Procedures: These are generally in *.sql files and can be loaded usingone of the following commands:For a directory with the .sql extension:DO CompileDirectory^%apiTSQL3(,,"dbo.")For a fully-qualified file name:DO CompileBatchFile^%apiTSQL3(,,"dbo.")4. Inspect the log file for errors: Search by Error #. A summary count of errors and successfulimports will appear at the end of the log. In most cases, errors can be worked around oraddressed by using information found in this document.5. Compile: It is best to use the command as follows:DO $SYSTEM.OBJ.CompileAll("-l")This command can also be invoked as:DO CompileAll^%apiOBJ("-l")The lowercase “L” qualifier flag specifies that locking is not applied for the duration ofthe compile. For a full list of flag qualifiers, call DO $SYSTEM.OBJ.ShowFlags().6. Migrate the Data: In the System Management Portal select SQL, then select the DataMigration Wizard.1.2 TSQL Language ImplementationTSQL procedures are converted to Caché methods or queries with a Language type equal toTSQL. Use the following command:2 Caché Transact-SQL (TSQL) Migration Guide


TSQL Language ImplementationCompileBatchFile^%apiTSQL3(,,).When compiling TSQL methods, Caché ObjectScript code is generated. There is no systemlevelsupport for native TSQL. It is best to maintain the methods in TSQL to retain thefamiliar look of the original stored procedures.• Using TSQL in StudioYou can write and maintain TSQL stored procedures (SPs) in Caché Studio. A TSQLSP can be either a class method or a query. A class method takes parameters and returnsa single scalar result, a query takes parameters and returns rows. If you put plain SELECTstatements into a class method they will be executed but you won't be able to get therows.• Writing a TSQL class methodCreate a class method stored procedure and enter the language as tsql. You can use thefollowing template as a starting point:ClassMethod Example() [ Language = tsql, SqlProc ]{}• Writing a TSQL queryEither write an SQL query and change the type from %SQLQuery to %TSQL.Query, orpaste this and start editing:Query Example() As %TSQL.Query [ SqlProc ]{}• Using the TSQL ShellA TSQL interpreter shell is useful for debugging and experimentation. See “Using theTSQL Shell” for more information.• TSQL Language ReferenceMicrosoft has good TSQL reference material at:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_tsqlcon_6lyk.aspCaché Transact-SQL (TSQL) Migration Guide 3


2Caché TSQL Constructs2.1 Current LimitationsCaché does not provide a full implementation of Transact-SQL at this time. There are majorlimitations which are not likely to be addressed soon, as follows:• TriggersStatement triggers, which are typically used in RDBMS to enforce referential integrity,are not supported and must be reviewed and migrated by hand.• Named TransactionsRDBMS supports identifiable transactions to selectively commit or to define rollbackpoints. For example, ROLLBACK SUBTOTAL. This is not supported in Caché.• SYSOBJECT ReferencesCommonly, an application will have setup procedures that create tables, views, and themetadata for the application environment. Such procedures will have expressions like:IF EXISTS (SELECT * FROM SYSOBJECTSWHERE ID = OBJECT_ID('People')This determines if a table exists, in this example. It’s usually followed by a DROP andCREATE statement to reestablish the table metadata.Caché Transact-SQL (TSQL) Migration Guide 5


Caché TSQL Constructs2.2 Commonly Used Constructs2.2.1 Local Temporary TablesTemporary tables local in visibility to the enclosing procedure are supported. They are createdeither by using CREATE TABLE with a table name starting with "#", or by using DECLARE @TTABLE. Either way, the storage will be deleted on exit from the stored procedure.The temporary table is created when the stored procedure is compiled. The table definitionremains in existence as long as the stored procedure definition refers to the temporary table.The temporary tables are not visible to other processes, so there is no problem if differentprocesses run the same stored procedure at the same time.This is not a security lockout though: unless the default configuration is changed, the temporarytable data of any process can be seen by anyone using a simple ObjectScript routine.Temporary tables are only supported inside stored procedures. The DYNAMICTEMPTABLE/DTTsetting can be used to make local temporary tables visible to called stored procedures too.For further details on settings, see the InterSystems Extensions section of the TSQL Commandschapter.Temporary tables visible to all stored procedures in all processes can be created in the sameway as for a local temporary table, but two "#"s appear at the start of the name instead of justone.2.2.2 SQL Expressions in ObjectScript ContextMost TSQL single-result expressions like EXISTS(subquery) work well. Try this in theSAMPLES directory in the TSQL shell. For example,IF EXISTS(SELECT * FROM Cinema.Film) PRINT 'yes'/xFor further details, refer to the chapter on Using the TSQL Shell.2.2.3 Error HandlingYou can tailor the error-handling in a stored procedure using the QUITONERROR andCONTEXTFORMAL settings:• Set QUITONERROR to 0 to suppress the code which quits the procedure/routine if SQL-CODE


• Setting CONTEXTFORMAL to a name makes the batch loader compile in an extra formalparameter of that name (type %SQLProcContext) which is also passed automatically toother stored procedures.CONTEXTFORMAL defaults to %sqlcontext. In this case it is not passed as an extra formalparameter. Queries automatically behave as if CONTEXTFORMAL is empty because it doesn'tmake sense to use anything but %sqlcontext in this case.For further details on settings, see the InterSystems Extensions section of the TSQL Commandschapter.2.2.4 TransactionsCode generated for BEGIN TRAN, COMMIT and ROLLBACK uses explicit transactionmode, but following a transaction TSQL always restores the mode which was active beforethe BEGIN TRAN statement. TSQL restores this mode when the procedure is exited from,or when a COMMIT or ROLLBACK is issued, whichever comes first.Caché TSQL does not support named transactions.2.2.5 Cursor Name ManagementIf the same cursor is declared more than once in a stored procedure, all but the first declarationare associated with renamed cursors. OPEN, FETCH, CLOSE, and DEALLOCATEstatements are assumed to refer to the most recent DECLARE for the given cursor. Note thatthe lexical position of a statement within a stored procedure is all that is used to match up acursor name with its DECLARE — no account is taken of runtime paths through the code.Cursors inside queries are named using an extension of the scheme used in Caché SQL queries.For example:DECLARE C CURSOR FOR SELECT A FROM B…OPEN CFETCH CCLOSE CDEALLOCATE C…DECLARE C CURSOR FOR SELECT D FROM E…OPEN CFETCH CCLOSE CDEALLOCATE CWould be effectively translated to:Commonly Used ConstructsCaché Transact-SQL (TSQL) Migration Guide 7


Caché TSQL ConstructsDECLARE C CURSOR FOR SELECT A FROM B…OPEN CFETCH CCLOSE CDEALLOCATE C…DECLARE Cv2 CURSOR FOR SELECT D FROM E…OPEN Cv2FETCH Cv2CLOSE Cv2DEALLOCATE Cv22.2.6 Table ReferencesFor the purposes of name translation, a field name has the field suffix removed while translationis performed and then replaced afterwards.Here is how a table name is processed:• The dbo. prefix is removed if present.• If the name now contains no dots and a default database has been specified with the USEstatement, the database is prefixed to the name.• The TABLENAMETEMPLATE/TNT setting (if not empty) will be used to further processthe name. For further details on TNT and other settings, see the InterSystems Extensionssection of the TSQL Commands chapter.2.2.7 Generalized QueriesGeneralized TSQL queries consist of a mixture of query and non-query code. To create aTSQL query in a class in Studio:• Create an SQL query.• Change the return-type from %SQLQuery to %TSQL.Query.• Use TSQL syntax instead of Caché SQL syntax.In a TSQL class query you can mix SELECT statements with INSERT, DELETE and justabout any other TSQL statement.A stored procedure is considered to be a query if it contains at least one SELECT statement.Subqueries, SELECT @X=… and SELECT … INTO … are not considered to be query statements.The query has columns from all the SELECT statements. Columns are taken from SELECTstatements in the order in which they appear in the source code.8 Caché Transact-SQL (TSQL) Migration Guide


Commonly Used ConstructsFor example:SELECT A,B FROM CSELECT X,Y FROM Zwill have columns A, B, X, Y.While the first query is active, X and Y will be returned as NULL. Once the second querybecomes active, A and B will be returned as NULL.Care is needed with columns that appear in more than one SELECT. Accessing them bynumber (GetData) is fine, but accessing them by name (Data) will always fetch the valuebound to the version of the column which appears latest in the list, which will be NULL exceptwhen its own query is active.You can get around duplicate columns using aliases. For example, instead of this:SELECT Category,Description FROM Cinema.FilmSELECT Category,Description FROM Cinema.Filmuse this:SELECT Category,Description FROM Cinema.FilmSELECT Category AS C2,Description AS D2 FROM Cinema.Film2.2.8 EXEC StatementThe EXEC (EXECUTE) statement can be used to invoke a stored procedure which is aquery. You can pass parameters as normal when calling a query stored procedure, but youcannot assign the result of a call to a query stored procedure to a variable.If the caller is itself a query the called query is incorporated into the calling query, both atcompile time and at execution time:• The called query's metadata is incorporated into the calling query.• The called query returns rows one at a time and the calling query returns those rows oneat a time to its own caller.For example, if the caller looks like this:SELECT Description FROM Cinema.FilmEXEC CalledQuery()SELECT Title FROM Cinema.Filmand the called query looks like this:SELECT Name,Age FROM PersonCaché Transact-SQL (TSQL) Migration Guide 9


Caché TSQL Constructs• The columns returned by the caller would be: "Description, Name, Age, Title"• The rows are returned in the order: Description, Name+Age, TitleIf the caller is itself not a query, the called query is invoked to completion but the results arediscarded.In a query, the CONTEXTFORMAL setting is ignored and the compiler behaves as if it wereempty or not given. That is, it uses %sqlcontext to store the context information and doesn'tadd it as an extra formal parameter to the generated query code. For further details onCONTEXTFORMAL and other settings, see the InterSystems Extensions section of the TSQLCommands chapter.Arrays cannot be passed as parameters to the query by reference and a missing parameter isset to "".2.2.8.1 System Stored Proceduressp_addtypeSupported, with the following limitations:• No unquoted names. For example, you can't use EXEC sp_addtype ssn,… —you must use EXEC sp_addtype 'ssn',….• No spaces in physical type.• Only the physical type is used for validation.2.2.9 Data TypesThe following data types are supported for local variables and table columns. These datatypes are supported in that they are parsed as valid data types; however, no range or valuevalidation is performed.BINARY(n) and VARBINARY(n). The (n) size specification is mandatory.BITBOOLEANCHAR, CHAR(n), VARCHAR, and VARCHAR(n)DATETIME and SMALLDATETIME10 Caché Transact-SQL (TSQL) Migration Guide


DECIMAL, DECIMAL(p), and DECIMAL(p,s). Where p and s are integers specifying precision(total digits) and scale (decimal digits).FLOAT and FLOAT(n)INT, BIGINT, SMALLINT, and TINYINTMONEY and SMALLMONEYNCHAR(n) and NVARCHAR(n)NUMERIC, NUMERIC(p), and NUMERIC(p,s). Where p and s are integers specifying precision(total digits) and scale (decimal digits).REALTIMESTAMPThe following SQL Server data types are supported in a specific context:CURSORNTEXT, TEXT, IMAGETABLEThe following SQL Server data types are not implemented:• SQL_VARIANT• UNIQUEIDENTIFIERThe following are not implemented:• ROWVERSION• SQL92 and TSQL options• UPDATE OFCommonly Used Constructs2.2.10 Comments, Blank Lines, and SemicolonsCaché TSQL supports both single-line and multi-line comments.• A single line comment is prefaced by two hyphens. It continues to the rest of the line.When used in the TSQL shell, a comment does not encompass the end-of-line qualifier,such as /x or /c.• A multi-line comment begins with /* and ends with */. A comment can include nested/* ... */ comments.Caché Transact-SQL (TSQL) Migration Guide 11


Caché TSQL Constructs2.2.10.1 TSQL-only StatementsCaché TSQL provides the means to include executable statements within Caché TSQL codewhich are parsed as nonexecutable comments in Transact-SQL. A statement prefixed withtwo hyphens and a vertical bar is parsed by Caché as an executable statement. Sybase AdaptiveServer and Microsoft SQL Server consider this to be a Transact-SQL comment.PRINT 'any context'-- PRINT 'commented out'--| PRINT 'InterSystems only'2.2.10.2 SemicolonsYou can specify a blank line by using either two hyphens or a semicolon.A semicolon either before or after a TSQL statement is ignored. They are supported forcompatibility with Transact-SQL code that ends statements with a semicolon.2.2.11 System TablesSystem tables exist per Caché namespace.SystypesPartially supported.12 Caché Transact-SQL (TSQL) Migration Guide


3TSQL Commands3.1 Data Definition (DDL) StatementsThe following DDL statements are supported.3.1.1 CREATE TABLEThe CREATE TABLE statement defines a table, its fields, and their data types and constraints.A CREATE TABLE can create a temporary table by prefixing a # character to the table name.The table constraints PRIMARY KEY, UNIQUE, and CLUSTERED/NONCLUSTEREDare supported. The table constraint FOREIGN KEY REFERENCES is supported. The tableconstraints WITH and ON are parsed for compatibility, but are ignored.The column definition DEFAULT values can include the following TSQL functions: CUR-RENT_TIMESTAMP, CURRENT_USER, GETDATE, HOST_NAME, ISNULL, NULLIF,and USER.The column definition IDENTITY constraint is supported and assigned a system-generatedsequential integer. The IDENTITY arguments seed and increment are parsed, but ignored.The column constraints CLUSTERED and NONCLUSTERED are parsed for compatibility,but are ignored.Caché Transact-SQL (TSQL) Migration Guide 13


TSQL Commands3.1.2 DROP TABLEDeletes a table definition. You can delete a single table, or a comma-separated list of tables.You can delete both tables and temporary tables. DROP TABLE ignores a nonexistent temporarytable name and completes without error.3.1.3 CREATE INDEXCreates an index for a specified table or view. TSQL partially supports CREATE INDEXwith the following limitations:The following Transact-SQL features are parsed, but ignored:• The CLUSTERED/NONCLUSTERED keywords.• The ASC/DESC keywords.• All WITH clause index options.• The ON filegroup or IN dbspace-name clause.The following Transact-SQL features are not currently supported:• The VIRTUAL keyword.• Using a function name as an alternative to a column name.3.2 Data Management Statements3.2.1 DELETEDeletes rows of data from a table. Both DELETE and DELETE FROM are supported. Mostother options are supported, with the following exceptions:• FROM table hints• rowset functions• OPTION clause• join hints14 Caché Transact-SQL (TSQL) Migration Guide


• only very simple theta joins are supported (the FROM table clause is transformed intonested subqueries)• primary table hintsThe following table_hints are parsed but ignored: FASTFIRSTROW, HOLDINDEX,INDEX(name), NOLOCK, PAGLOCK, READCOMMITTED, READPAST, READUNCOM-MITTED, REPEATABLEREAD, ROWLOCK, SERIALIZABLE, SHARED, TABLOCK,TABLOCKX, UPDLOCK, XLOCK. Table hints can be optionally preceded by the WITHkeyword, and, if WITH is specified, optionally enclosed in parentheses. A list of table hintscan be separated by either commas or blank spaces.DELETE sets the @@ROWCOUNT system variable to the number of rows deleted, andthe @@IDENTITY system variable to the IDENTITY value of the last row deleted.3.2.2 INSERTInserts rows of data into a table. Most options are supported, with the following exceptions:• rowset functions• taking values from an execute-statement• DEFAULTThe following table_hints are parsed but ignored: FASTFIRSTROW, HOLDINDEX,INDEX(name), NOLOCK, PAGLOCK, READCOMMITTED, READPAST, READUNCOM-MITTED, REPEATABLEREAD, ROWLOCK, SERIALIZABLE, SHARED, TABLOCK,TABLOCKX, UPDLOCK, XLOCK. Table hints can be optionally preceded by the WITHkeyword, and, if WITH is specified, optionally enclosed in parentheses. A list of table hintscan be separated by either commas or blank spaces.INSERT sets the @@ROWCOUNT system variable to the number of rows inserted, and the@@IDENTITY system variable to the IDENTITY value of the last row inserted.3.2.3 UPDATEUpdates values of existing rows of data in a table. Most options are supported, with the followingexceptions:• rowset• OPTIONData Management StatementsCaché Transact-SQL (TSQL) Migration Guide 15


TSQL Commands• only very simple theta joins are supported (the FROM table clause is transformed intonested subqueries)• table hints• DEFAULT• SET @localThe following table_hints are parsed but ignored: FASTFIRSTROW, HOLDINDEX,INDEX(name), NOLOCK, PAGLOCK, READCOMMITTED, READPAST, READUNCOM-MITTED, REPEATABLEREAD, ROWLOCK, SERIALIZABLE, SHARED, TABLOCK,TABLOCKX, UPDLOCK, XLOCK. Table hints can be optionally preceded by the WITHkeyword, and, if WITH is specified, optionally enclosed in parentheses. A list of table hintscan be separated by either commas or blank spaces.UPDATE sets the @@ROWCOUNT system variable to the number of rows updated, andthe @@IDENTITY system variable to the IDENTITY value of the last row updated.3.2.4 TRUNCATE TABLEDeletes all rows from the specified table. Supported to the extent that it is considered a synonymfor DELETE FROM table with no WHERE clause. However, TRUNCATE TABLEdoes not reset the IDENTITY field counter.3.3 Query Statements3.3.1 SELECTMainly supported. The following features are not supported:• FOR• COMPUTE• OPTION• WITH CUBE• WITH ROLLUP• GROUP BY ALL16 Caché Transact-SQL (TSQL) Migration Guide


Control Flow Statements• GROUP WITH• TOP PERCENT• TOP WITH TIESThe following table_hints are parsed but ignored: FASTFIRSTROW, HOLDINDEX,INDEX(name), NOLOCK, PAGLOCK, READCOMMITTED, READPAST, READUNCOM-MITTED, REPEATABLEREAD, ROWLOCK, SERIALIZABLE, SHARED, TABLOCK,TABLOCKX, UPDLOCK, XLOCK. Table hints can be optionally preceded by the WITHkeyword, and optionally enclosed in parentheses. A list of table hints can be separated byeither commas or blank spaces.3.3.2 FETCH CursorThe OPEN, FETCH, CLOSE, and DEALLOCATE commands are mainly supported. Thefollowing features are not supported:• OPEN/FETCH/CLOSE @local• FETCH followed by any qualifier other than NEXT (the qualifier can be omitted).• Note that DEALLOCATE is supported, but that, by design, it generates no code.3.3.3 UPDATE STATISTICSOptimizes query access for a specified table. Caché passes a table name argument to $System.SQL.TuneTablefor optimization. UPDATE STATISTICS calls $System.SQL.TuneTablewith update=1 and display=0. The returned %msg is ignored and KeepClassUpToDate defaultsto 'false'. All other UPDATE STATISTICS syntax is parsed for compatibility only, andignored.In a batch or stored procedure, only the first UPDATE STATISTICS statement for a giventable generates a call to $System.SQL.TuneTable.3.4 Control Flow StatementsThe IF command is supported. The ELSE clause of an IF is optional. You can use the BEGINand END keywords to demarcate a block of statements within an IF or ELSE clause.The WHILE command is supported.Caché Transact-SQL (TSQL) Migration Guide 17


TSQL CommandsThe WAITFOR command is not supported.3.4.1 GOTO and LabelsCaché TSQL supports the GOTO command and labels. A label must be a valid identifierfollowed by a colon (:). A GOTO reference to a label does not include the colon.Because naming conventions for identifiers differ, Caché provides the DOLLAR andUNDERLINE settings to translate the dollar sign ($) and underline (_) characters used withinTransact-SQL labels or other identifiers. See SETTINGS below.3.5 Assignment Statements3.5.1 DECLAREUsed to declare the data type for a local variable. Either of the following forms are supported:DECLARE @var CHAR(20)DECLARE @var AS CHAR(20)Only the form which declares local variables is supported; cursor variables are not supported.For further details on data types, refer to the TSQL Constructs chapter of this document.3.5.2 SETUsed to assign a value to a local variable:DECLARE @var CHAR(20)SET @var='hello world'Used to set a system setting:These settings have immediate effect at parse time, whether inside a stored procedure or not.The change persists until another SET command alters it – even if the SET is made inside astored procedure, and accessed outside the SP or in another SP.The following SET variables are supported:• SET ANSI_NULLS• SET DATEFIRST18 Caché Transact-SQL (TSQL) Migration Guide


Transaction Statements• SET QUOTED_IDENTIFIER• SET ROWCOUNT Only affects the SELECT statement• SET TRANSACTION ISOLATION LEVEL See Transaction Statements below.The following SET variables are parsed, but ignored:• SET NOCOUNT• SET TEXTSIZE3.6 Transaction StatementsCaché TSQL provides basic support for transactions. It parses, but ignores transaction names.It does not support savepoints. Distributed transactions are not supported.3.6.1 SET TRANSACTION ISOLATION LEVELSupported for the following forms only:• SET TRANSACTION ISOLATION LEVEL READ COMMITTED• SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.3.6.2 BEGIN TRANSACTIONSupported as either BEGIN TRAN or BEGIN TRANSACTION. A transaction name isparsed, but ignored.3.6.3 COMMIT TRANSACTIONSupported as any of the following: COMMIT, COMMIT TRAN, COMMITTRANSACTION, or COMMIT WORK. A transaction name is parsed, but ignored.3.6.4 ROLLBACK TRANSACTIONSupported as either ROLLBACK, ROLLBACK TRAN, ROLLBACK TRANSACTION,or ROLLBACK WORK. A transaction name is parsed, but ignored. Savepoints are notsupported.Caché Transact-SQL (TSQL) Migration Guide 19


TSQL Commands3.6.5 CHECKPOINTThe CHECKPOINT statement is parsed but ignored in Caché TSQL. It performs no operation.3.7 Other StatementsThe following standard Transact-SQL statements are supported.3.7.1 CREATE PROCEDURE / CREATE FUNCTIONYou can return a single scalar value result from either a PROCEDURE or a FUNCTION. OUTPUTparameters and default values are also supported. Currently, result sets and tables can't bereturned.CREATE FUNCTION is treated as a synonym for CREATE PROCEDURE.• Any statements can be used in a FUNCTION.• The RETURNS statement is allowed after CREATE PROCEDURE.3.7.2 DROP PROCEDURESupported.3.7.3 EXECUTEThe EXECUTE (or EXEC) statements are supported as follows:EXEC is supported. The EXEC keyword cannot be omitted. Named parametersare supported.The following EXEC features are not currently supported: procedure variables,and procedure numbers (i.e. ';n'). WITH RECOMPILE is accepted but ignored.EXEC is supported. The ability to execute a string as TSQL can also be accessedfrom COS using a class method: ##class(%TSQL.Transformer).ExecuteStringAsTSQL,or from CSQL using the same method as a stored procedure:%TSQL.Transformer_ExecuteStringAsTSQL20 Caché Transact-SQL (TSQL) Migration Guide


InterSystems Extensions3.7.4 GRANTSupported for GRANT EXECUTE ON objectreflist TO granteelist where a grantee canbe a name, "PUBLIC" or "*".3.7.5 PRINTSupported.3.7.6 USE databaseSupported, also an extension: USE NONE to select no database. Effective at generation-time,persists as long as the transform object exists (e.g. in the shell or loading a batch).3.8 InterSystems ExtensionsTSQL supports a number of InterSystems extensions to Transact-SQL. To allow for theinclusion of these InterSystems-only statements in portable code, Caché TSQL also supportsa special form of the single-line comment: two hyphens followed by a vertical bar. Thisoperator is parsed as a comment by Transact-SQL implementations, but is parsed as an executablestatement in Caché TSQL. For further details, refer to the Comments section of theTSQL Constructs chapter of this document.TSQL includes the following InterSystems extensions:3.8.1 CACHEThis extension allows you to include Caché ObjectScript code in the compiled output. It takesone or more lines of Caché ObjectScript inside curly brackets:CACHE {WRITE "SQLCODE=",SQLCODE,!}Note that in the above example the WRITE command specifies a new line (,!); this is necessarybecause the CACHE extension does not issue a new line following execution.The CACHE extension can also be used to embed Caché SQL into TSQL code:CACHE {&sql(SET TRANSACTION %COMMITMODE EXTERNAL)}For further details on embedded Caché SQL, refer to Embedded SQL in Using Caché SQL.Caché Transact-SQL (TSQL) Migration Guide 21


TSQL Commands3.8.2 IMPORTASQUERYThis extension forces a stored procedure to be imported as a query rather than as a classmethod. This is useful for stored procedures that contain only an EXEC statement, becauseCaché cannot otherwise determine at import whether such a stored procedure is a query ornot.3.8.3 SETTINGSSettings are an InterSystems extension used to tailor the behavior of the compiler and colorizer.A setting has a name and an abbreviation, as in GENRAW/GR; either form can be used.Persistent settings are associated with the TSQL shell, and are stored in ^%TSQL("SETTINGS"):WRITE $GET(^%TSQL("SETTINGS"),"no settings")You can set them in the TSQL shell using =settings.You can set system-wide settings in ^%SYS using *=settings.The SETTINGS command allows you to set local settings for the current parse or compilation.3.8.3.1 SETTINGS Command SyntaxYou can use the SETTINGS command to control local settings, for a stored procedure beingcompiled, for instance.You can use SETTINGS to specify a single setting or a comma-separated list of settings.There are two syntactical forms:• SETTINGS name1=val[,name2=val] This form sets the specified settings. adding toor modifying the list of defined settings.• SETTINGS =name1=val[,name2=val] This form deletes all previous settings beforesetting the specified settings.Each setting can be assigned a value in a variety of ways:• name=value sets a setting to a value. You can set boolean flags to 1 or 0.• name sets a boolean flag setting to 1.• -name sets a setting to its default value.22 Caché Transact-SQL (TSQL) Migration Guide


In the following example, this line at the start of a stored procedure would set QE(QUITONERRORS) to 1 (true), and set CF (CONTEXTFORMAL) to "pHandle":SETTINGS QE,CF=pHandle3.8.3.2 Available SettingsThe following are the available settings:InterSystems ExtensionsName/AbbreviationATATPREFIX/AAPCASEINSCOMPARE/CICCONTEXTFORMAL/CFCONVERTTOLOGICAL/CTLDOLLAR/DLDYNAMICTEMPTABLE/DTTGENRAW/GRValuestringflagstringstringstringflagflagDescriptionSpecifies what character(s) should besubstituted for the "@@" prefix foruser-defined variables when translating toCaché ObjectScript. The default is "ATAT".If this flag is set, the comparison operators= and operate case-insensitively in mostcontexts. (For more details, see below.)If blank, the scopeless %sqlcontext isused as a %SQLProcContext. If not blank,the specified variable is used as a%SQLProcContext, and if there is aformal-list to be generated this variable isadded as the first formal parameter.Specifies a comma-delimited list of TSQLdata types to convert to logical format(unless concatenated). Specify "*" toconvert all data types.Specifies what character(s) should besubstituted for the "$" character in methodand variable names.By default, local temporary tables can onlybe used in the stored procedure in whichthey are created. Setting this flag makesthese temporary tables available to storedprocedures called (directly or indirectly) bythe stored procedure that created thetemporary table.Suppresses some scaffolding code —easier to read but the resulting code can'tusually be compiled/run.Caché Transact-SQL (TSQL) Migration Guide 23


TSQL CommandsName/AbbreviationMESSAGELIMIT/MLMESSAGEPERLINELIMIT/MPLLNODECLCHECK/NDCNOGRANTEXECUTE/NGEPREPAREIGNORE/PPIPTSYMTABPARSE/PSPQUITONERROR/QEQUITONERRORALWAYS/QEASELECTMODE/SMValueintegerintegerflagflagstringflagflagflagstringDescriptionLimits the total number of warning/errormessages in compilation output. Thedefault limit is 40.Limits the number of warning/errormessages in compilation output per line.The default limit is 1.To suppress the check that all @variablesare declared.To suppress code generation by GRANTEXECUTE.Specifies a comma-delimited list ofSQLCODE errors to ignore in thecompile-time check (default "").Check declaration of symbols at parse timewhen in parse-mode (such as the coloringeditor in Studio). Setting this should makeit color undeclared variables as errors.The compiler generates code to quit thecurrent procedure/routine whenSQLCODE


InterSystems ExtensionsName/AbbreviationTABLENAMETEMPLATE/TNTUNDERLINE/ULVERBOSEERRORMESSAGES/VEMValuestringstringflagDescriptionSpecifies how a TSQL table reference istranslated to a Caché SQL table reference.The default is to pass such referencesunchanged but if this setting is non-emptyit is used a template for constructing theCaché SQL table reference. However,originally unqualified references are leftalone. (For more details, see below.)Specifies what character(s) should besubstituted for the "_" character in methodand variable names.If set, specifies that the classname will beincluded in each compilation errormessage.You can type ?SET in the TSQL shell for a list of these supported settings. See “Using theTSQL Shell” for more details.3.8.3.3 SETTING CICThe CASEINSCOMPARE/CIC setting specifies case-insensitive equality comparisons, suchas 'A'='a'. However, there are a few contexts where such case-insensitivity does not apply:• Where a comparison is the ON condition for a JOIN.• Where either operand is a subquery.These exceptions exist because Caché SQL does not accept the %SQLUPPER operator in thesecontexts.3.8.3.4 SETTING TNTThe TABLENAMETEMPLATE/TNT setting specifies a template for parsing a table reference.The components of a TSQL table reference are Database.Owner.Table for Sybase andServer.Database.Owner.Table for SQLServer. Components other than Table are optional.The format of the TNT template is normal text interspersed with text in square brackets (caseinsensitive):• [lb] and [rb] represent left bracket and right bracket ("[" and "]"), respectivelyCaché Transact-SQL (TSQL) Migration Guide 25


TSQL Commands• [server], [database], [owner] and [object] refer to those components of the tablereference as in SQLServer.The component names have synonyms as follows:• server: ser• database: dat, schema, or sch• owner: own• object: obj, table, or tabYou can also supply alternatives to be used if components are missing. For example:[dat|ser|own] means use the database component if present, else the server if present, elsethe owner if present. For example: [dat|ser|own].[obj] will convert A.B.C.D to B.D andA..C.D to A.DAnd you can have leading and trailing non-letters just after the "[" or just before the "]" whichare only inserted into the generated name if the component expression yields a non-emptyresult. For example: [dat|ser.][obj] will convert A.B.C.D to B.D, A..C.D to A.D butC.D to D (not .D)Note that the non-letters must not go inside the |..|, they must only appear at the startand/or end of the string.26 Caché Transact-SQL (TSQL) Migration Guide


4TSQL Functions4.1 Supported FunctionsThe following TSQL functions are implemented.4.1.1 ABSABS(num)Returns the absolute value of num. Thus both 123.99 and –123.99 return 123.99.4.1.2 ASCIIASCII(char)Returns the ASCII value for the first character in string char.4.1.3 CASTCAST(expression AS datatype)Returns the expression converted to the specified datatype. Only data types legal in the CachéSQL CAST function are accepted.When expression is a date value string, such as '2004–11–23' and datatype is datetime ortimestamp, a time value of '00:00:00' is supplied.Caché Transact-SQL (TSQL) Migration Guide 27


TSQL FunctionsWhen expression is a time value string, such as '1:35PM' and datatype is datetime or timestamp,the time is converted to a 24-hour clock, the AM or PM suffix is removed, a missingseconds interval is filled in with zeros, and the default date value of '1900–01–01' is supplied.Thus '1:35PM' is converted to '1900–01–01 13:35:00'.See CONVERT.4.1.4 CEILINGCEILING(num)Returns the closest integer greater than or equal to num. Thus 123.99 returns 124, –123.99returns –123.4.1.5 CHARCHAR(num)Returns the character corresponding to the ASCII value num.4.1.6 CHARINDEXCHARINDEX(seekstring,target[,startpoint])Returns the position in target (counting from 1) corresponding to first character of the firstoccurrence of seekstring. You can use the optional startpoint integer to specify where to beginthe search. The return value counts from the beginning of target, regardless of the startpoint.If startpoint is not specified, specified as 0, 1, or as a negative number, target is searchedfrom the beginning. CHARINDEX returns 0 if seekstring is not found.4.1.7 CONVERTCONVERT(datatype,expression[,style])Returns the expression converted to the specified datatype.When expression is a date value string, such as '2004–11–23' and datatype is datetime ortimestamp, a time value of '00:00:00' is supplied.When expression is a time value string, such as '1:35PM' and datatype is datetime or timestamp,the time is converted to a 24-hour clock, the AM or PM suffix is removed, a missing28 Caché Transact-SQL (TSQL) Migration Guide


seconds interval is filled in with zeros, and the default date value of '1900–01–01' is supplied.Thus '1:35PM' is converted to '1900–01–01 13:35:00'.The optional style argument is used to specify a date/time format when converting a datetimeor timestamp value to a string. By specifying various style codes you can return a dates andtimes in a variety of different formats. The available style codes are 0 through 14 (100 through114), 20 & 21 (120 & 121), 126, 130, and 131. The default style is 120:yyyy-mm-dd hh:mm:ssSee CAST.4.1.8 CURRENT_TIMESTAMPCURRENT_TIMESTAMPReturns the current local date and time in the following format:yyyy-mm-dd hh:mm:ssTime is specified using a 24-hour clock, Fractional seconds are not returned.Note that no parentheses are used with this function.4.1.9 CURRENT_USERCURRENT_USERReturns the name of the current user.Note that no parentheses are used with this function.4.1.10 DATALENGTHDATALENGTH(expression)Supported FunctionsReturns an integer specifying the number of bytes used to represent expression. Thus 'fred'returns 4, and +007.500 returns 3.Caché Transact-SQL (TSQL) Migration Guide 29


TSQL Functions4.1.11 DATEADDDATEADD(code,num,date)Returns the value of date modified by adding the interval specified in code the num numberof times. The date can be a date, time, or date/time string in a variety of formats. Availablecode values are:yyqqmmdyddwkhhmissmsYearQuarterMonthDay of yearDayWeekHourMinuteSecondMillisecondThe value returned by DATEADD always includes both date and time in the format:yyyy-mm-dd hh:mm:ss.nFractional seconds are only returned if the source contained fractional seconds.If a date is not specified (that is, if date contains only a time value), it defaults to 1/1/1900.If a time is not specified in date, it defaults to 00:00:00. Hours are always returned based ona 24-hour clock.4.1.12 DATEDIFFDATEADD(code,startdate,enddate)Returns the number of code intervals between startdate and enddate. The two dates can bea date, a time, or a date/time string. in the following format:yyyy-mm-dd hh:mm:ss.n30 Caché Transact-SQL (TSQL) Migration Guide


Supported FunctionsAvailable code values are:yymmddwkhhmissmsYearMonthDayWeekHourMinuteSecondMillisecondIf a date is not specified (that is, if startdate or enddate contains only a time value), it defaultsto 1/1/1900.If a time is not specified in startdate or enddate, it defaults to 00:00:00.4.1.13 DATENAMEDATENAME(code,date)Returns the value of the part of the date specified in code. The date can be a date, time, ordate/time string in a variety of formats. Available code values are:Caché Transact-SQL (TSQL) Migration Guide 31


TSQL Functionsyyyy, yyqq, qmm, mdy, ydd, dwk, wwdwhhmi, nss, smsYear. Returns a four-digit year.Quarter. Returns an integer 1 through 4.Month. Returns the full name of the month.For example, 'December'.Day of Year. Returns an integer count ofdays 1 through 366.Day of Month. Returns an integer count 1through 31.Week of Year. Returns an integer count 1through 53.Day of Week. Returns the full name of theweekday. For example, 'Tuesday'.Hour. Returns the hour of the day (24–hourclock), an integer 0 through 23.Minute. Returns an integer 0 through 59.Second. Returns a decimal number 0through 59 which may have a fractional partrepresenting milliseconds.Millisecond. Returns the fractional part ofa second as an integer.If a date is not specified, it defaults to 1/1/1900. Two-digit years default to 19xx.If a time is not specified, it defaults to 00:00:00. Hours are always returned based on a 24-hour clock. Seconds are always returned with fractional seconds, if fractional seconds aredefined. Milliseconds are returned as an integer, not a decimal fraction.4.1.14 DAYDAY(date)Returns the day portion of the specified date or date/time string. This string must be specifiedin ODBC timestamp format:yyyy-mm-dd hh:mm:ss.nThe date must contain a date component. The date separator must be a hyphen (-).32 Caché Transact-SQL (TSQL) Migration Guide


Supported Functions4.1.15 DB_NAMEDB_NAME()Returns the current namespace name. No argument is permitted.4.1.16 FLOORFLOOR(num)Returns the closest integer less than or equal to num. Thus 123.99 returns 123, –123.99 returns–124.4.1.17 GETDATEGETDATE()Returns the current local date and time in the following format:yyyy-mm-dd hh:mm:ss.nTime is specified using a 24-hour clock, Fractional seconds are returned.4.1.18 HOST_NAMEHOST_NAME()Returns the system name of the current host system.4.1.19 ISNULLISNULL(expr,default)If expr is NULL, returns default. If expr is not NULL, returns expr.Caché Transact-SQL (TSQL) Migration Guide 33


TSQL Functions4.1.20 ISNUMERICISNUMERIC(expression)A boolean function that returns 1 if expression is a valid numeric value; otherwise, returns0.4.1.21 LEFTLEFT(string,int)Returns int number of characters from string, counting from the left. If int is larger than string,the full string is returned. See RIGHT.4.1.22 LENLEN(string)Returns the number of characters in string.4.1.23 LOGLOG(num)Returns the natural logarithm of num.4.1.24 LOWERLOWER(string)Returns string with all uppercase letters converted to lowercase. See UPPER.4.1.25 LTRIMLTRIM(string)Removes leading blanks from string. See RTRIM.34 Caché Transact-SQL (TSQL) Migration Guide


Supported Functions4.1.26 MONTHMONTH(date)Returns the month portion of the specified date or date/time string. This string must bespecified in ODBC timestamp format:yyyy-mm-dd hh:mm:ss.nThe date separator must be a hyphen (-). Dates in any other format return 0.4.1.27 NULLIFNULLIF(expr1,expr2)Returns NULL if expr1 is equivalent to expr2. Otherwise, returns expr1.4.1.28 OBJECT_IDOBJECT_ID(objname)Partially support; returns an existence flag, not an object identification number. Returns 1 ifthe objname (a table, view, or stored procedure) exists. Otherwise returns NULL.This behavior supports this style of use:IF OBJECT_ID('selectAuditAdColumns') IS NOT NULLBEGINDROP PROCEDURE selectAuditAdColumnsPRINT '>'END4.1.29 PATINDEXPATINDEX(pattern,string)Returns an integer specifying the beginning position of pattern in string, counting from 1. Ifpattern is not found in string, the 0 is returned. The pattern consists of a search string enclosedin percent (%) characters: '%Chicago%'. It can contain an underbar characters (_) as a singlecharacter wildcard.Caché Transact-SQL (TSQL) Migration Guide 35


TSQL Functions4.1.30 POWERPOWER(num,exponent)Returns the value num raised to exponent.4.1.31 RANDRAND([seed])Returns a random number as a fractional number less than 1. The optional seed argument isignored; it is provided for compatibility. If RAND is used more than once in a query it returnsdifferent random values.4.1.32 RAISERRORRAISERROR('message')RAISEERROR('message')Both spellings, RAISERROR and RAISEERROR, are supported and synonymous.4.1.33 REPLACEREPLACE(target,search,replace)Finds every instance of the search string in the target string and replaces it with the replacestring. To remove the search string from the target string, specify replace as an empty string.4.1.34 REPLICATEREPLICATE(string,num)Repeats string for the number of times specified by the integer num.4.1.35 REVERSEREVERSE(string)Reverses the order of the characters in string.36 Caché Transact-SQL (TSQL) Migration Guide


Supported Functions4.1.36 RIGHTRIGHT(string,int)Returns int number of characters from string, counting from the right. If int is larger thanstring, the full string is returned. See LEFT.4.1.37 ROUNDROUND(num,length)Returns num rounded to the number of decimal digits specified by the integer length. If lengthis greater than the number of decimal digits, no rounding is performed. If length is zero, numis rounded to an integer. If length is a negative integer, num is rounded to the left of the decimalpoint. A third argument is not accepted by ROUND.4.1.38 RTRIMRTRIM(string)Removes trailing blanks from string.4.1.39 SCOPE_IDENTITYSCOPE_IDENTITY()Returns the value of the most recently IDENTITY column inserted by the current storedprocedure, function, or batch process. See the similar @@IDENTITY special variable, whichis not limited to the scope of the current process.4.1.40 SIGNSIGN(num)Returns a value indicating the sign of num. If num is negative (for example, -32), it returns-1. If num is positive (for example, 32 or +32), it returns 1. If num is zero (for example, 0 or-0), it returns 0.Caché Transact-SQL (TSQL) Migration Guide 37


TSQL Functions4.1.41 SPACESPACE(num)Returns a string of blank spaces of length num.4.1.42 STRSTR(num,[length[,precision]])Returns a string of length characters. If the integer length is equal to or greater than thenumber of characters in the numeric num (including decimal point and sign characters), STRreturns num converted to a string and padded with leading blanks to make the resulting stringof length characters.If the optional integer precision is specified, num is truncated to the specified number ofdecimal digits before string conversion. If precision is omitted, num is truncated to its integerportion. If precision is larger than the number of decimal digits, num is padded with trailingzeros before string conversion.If length is omitted, it defaults to 10. If length is less than the number of characters in num(after adjustment by precision) a dummy string consisting of all asterisks of length numberof characters is returned.4.1.43 STUFFSTUFF(string,start,length,replace)Returns string with length number of characters removed and the replace string inserted. Thepoint of removal and insertion is specified by the start integer, counting from the beginningof string. If length is 0, no characters are removed. If replace is the empty string, no charactersare inserted.If start is greater than the number of characters in string, no value is returned. If start is 1,length number of characters are removed from the beginning of string and the replace stringinserted. If start is 0, length minus 1 number of characters are removed from the beginningof string and the replace string inserted.If length is greater than or equal to the number of characters in string, the replace string isreturned. The replace string length is not limited by the length of string or length.38 Caché Transact-SQL (TSQL) Migration Guide


Supported Functions4.1.44 SUBSTRINGSUBSTRING(string,start,length)Returns a substring of string beginning at the location start for the length number of characters.If start is greater than the length of string, or if length is 0, no string is returned.4.1.45 SUSER_NAMESUSER_NAME()Returns the name of the current OS user. No argument is permitted.4.1.46 UPPERUPPER(string)Returns string with all lowercase letters converted to uppercase. See LOWER.4.1.47 USERUSERReturns the name of the current user.Note that no parentheses are used with this function.4.1.48 USER_IDUSER_ID([username])Returns the user ID of the user specified by name. If the optional username is omitted, returnsthe user ID of the current user. The argument is optional; the parentheses are mandatory.4.1.49 USER_NAMEUSER_NAME([userid])Returns the name of the user specified by user ID. If the optional userid is omitted, returnsthe name of the current user. The argument is optional; the parentheses are mandatory.Caché Transact-SQL (TSQL) Migration Guide 39


TSQL Functions4.1.50 YEARYEAR(date)Returns the year portion of the specified date or date/time string. This string must be specifiedin ODBC timestamp format:yyyy-mm-dd hh:mm:ss.nThe date separator can be either a hyphen (-) or a slash (/).4.2 Unsupported FunctionsThe following Microsoft Transact-SQL functions are not supported by TSQL at this time:ACOS, APP_NAME, ASIN, ATAN, ATN2, COALESCE, COL_LENGTH, COS, COT,DB_ID, DEGREES, DIFFERENCE, EXP, FILE_ID, FILE_NAME, FILEGROUP_ID,GETANSINULL, GETUTCDATE, HOST_ID, IDENT_CURRENT, IDENT_INCR,IDENT_SEED, ISDATE, LOG10, NEWID, OBJECT_NAME, PI, QUOTENAME, RADIANS,SESSION_USER, SIN, SOUNDEX, SQUARE, SQRT, STDEV, STDEVP, SYSTEM_USER,TAN, TYPEPROPERTY, UNICODE40 Caché Transact-SQL (TSQL) Migration Guide


5TSQL Variables5.1 Host Variables and LiteralsStandard host variables and literal numbers and strings (including multiline strings) are supported.TSQL variables are specified using an at sign (@) prefix. For example, @a or @myvar. TSQLspecial (system-defined) variables are identified by an @@ prefix. For Example,@@ROWCOUNT.Variables must be declared (using DECLARE or as a formal parameter) before use. The declarationmust specify a data type, though strict data typing is not enforced in Caché TSQL. Fora list of supported data types, refer to the TSQL Constructs chapter of this document.The following example shows a local variable being declared, set, and displayed:DECLARE @a CHAR(20)SET @a='hello world'PRINT @aDeclared variables are initialized to "" (SQL NULL) at the start of the procedure.If declaring variables is inconvenient you can switch this check off using the NDC setting(type ? in the shell for more details). However, cursors must be declared, even if NDC is used.Stored procedure arguments are automatically declared as local variables.Caché Transact-SQL (TSQL) Migration Guide 41


TSQL Variables5.2 Special VariablesThe following special variables are implemented. Caché ObjectScript (COS) and Caché SQLgenerated code follows each description:5.2.1 @@DATEFIRSTContains an integer specifying which day is the first day of the week. 1=Monday, 2=Tuesday... 7=Sunday. The default is 7. You can change this value using SET DATEFIRST.COS %tsqlDATEFIRSTSQL :%tsqlDATEFIRST5.2.2 @@ERRORContains a boolean value indicating whether or not an error has occurred. 0 indicates successfulcompletion.COS SQLCODESQL :SQLCODESince the codes are not translated to Cache' SQL, comparing this to 0 is the only sensiblething that you can do with it.5.2.3 @@FETCH_STATUSContains an integer specifying the status of the last FETCH cursor statement. The availableoptions are: 0=row successfully fetched; –1=no data could be fetched; –2 row fetched ismissing(?). A value of –1 can indicate that there is no data to FETCH, or that the fetch hasreached the end of the data.COS $Case($Get(SQLCODE,0),0:0,100:-1,:-2)SQL CASE :SQLCODE WHEN 0 THEN 0 WHEN 100 THEN –1 ELSE –2 END5.2.4 @@IDENTITYContains the IDENTITY field value of the most recently inserted, updated, or deleted row.COS %ROWID42 Caché Transact-SQL (TSQL) Migration Guide


Special VariablesSQL :%ROWID5.2.5 @@ROWCOUNTContains the number of rows affected by the most recent INSERT, UPDATE, or DELETEcommand.COS %ROWCOUNTSQL :%ROWCOUNT5.2.6 @@SPIDContains the server process ID of the current process.COS ##class(%TSQL.SysFunc).SPID()")SQL %TSQL.SPID()5.2.7 @@SQLSTATUSContains an integer specifying the completion status of the most recent SQL statement.Available values are: 0=successful completion; 1=failure; 2=no (more) data available.COS $Case($Get(SQLCODE,0),0:0,100:2,:1)SQL CASE :SQLCODE WHEN 0 THEN 0 WHEN 100 THEN 2 ELSE 1 END5.2.8 @@TRANSCOUNTContains the number of currently active transactions.COS ##class(%TSQL.SysFunc).TRANCOUNT()SQL %TSQL.TRANCOUNT()5.2.9 @@VERSIONContains the Caché version number and date and time of its installation.COS $ZVERSIONCaché Transact-SQL (TSQL) Migration Guide 43


6Using the TSQL Shell6.1 Getting StartedAt the terminal prompt enter: DO ^%apiTSQL.You should see something like this:Current settings :-No current settingsUSER:TSQL>What is shown as USER here is the current namespace. You can change the namespace byinvoking the Cache ObjectScript ZNSPACE command from within TSQL using the CACHEextension, as follows:USER:TSQL>CACHE {ZNSPACE "SAMPLES"} /xPress the return key twice to compile and execute. The terminal prompt now is:SAMPLES:TSQL>To begin entering TSQL code, try the following:SAMPLES:TSQL>PRINT GETDATE() /xAgain, press the return key twice. The '/x' at the end of the line tells TSQL to compile andexecute. The GETDATE function returns the current date and time.Caché Transact-SQL (TSQL) Migration Guide 45


Using the TSQL Shell6.1.1 Caché Commands in the TSQL ShellThe above example of invoking the Cache ObjectScript ZNSPACE command from withinTSQL using the CACHE extension demonstrates how Caché commands can be compiledand executed as part of TSQL code. However, some Caché commands (including ZNSPACE)can be invoked directly from within the TSQL shell, without a TSQL compile and withoutusing the CACHE extension.The TSQL shell supports direct invocation of the following Cache ObjectScript commands.Note that at Caché 5.2, only the abbreviated form of the command name can be used:AbbreviationBDFIKLMSWXZNZWCommand NameBREAKDOFORIFKILLLOCKMERGESETWRITEXECUTEZNSPACEZWRITE6.1.2 Compiling a Table DefinitionTo define a table, type something like:SAMPLES:TSQL>CREATE TABLE Sample.MyTest (SAMPLES:TSQL>f1 INT,SAMPLES:TSQL>f2 CHAR(20),SAMPLES:TSQL>date DATETIME DEFAULT GETDATE() )At the end of each line you press the return key. The SAMPLES:TSQL> prompt reappears,prompting you for the next line of code. Lines are accepted until you press return without46 Caché Transact-SQL (TSQL) Migration Guide


Getting Startedentering anything (press return twice), at which point all the lines are compiled and theresulting code is listed on the screen. It will look something like this:STATS:GENCODEGenerated code :-;^TSQL LOCALVARS=tsqlgen0002;^TSQL SIMPLEQUERY=0;^TSQL QUERYLOGGING=New %tsqlspcontext,%tsqltableid,%ROWCOUNT,%tsqlScopeIdentitySet %tsqlspcontext=##class(%TSQL.SPContext).%New("SPCLASSzSPMETHOD")If $Data(%sqlcontext) {Set %sqlcontext.SQLCode=0,%sqlcontext.Message=""}Set (tsqlgen0002)="";;Set tsqlgen0002=$$ESu^%apiTSQL2(.SQLCODE,.%msg," CREATE TABLE Sample.MyTest (f1 %Library.Integer(MAXVAL=2147483647,MINVAL=-2147483648), f2 %Library.String(MAXLEN=20), ""date"" %Library.TimeStamp DEFAULTOBJECTSCRIPT '##class(%TSQL.SysFunc).GETDATE()') ","",0)#execute Do CheckPrepare^%apiTSQL2(" CREATE TABLESample.MyTest (f1 %Library.Integer(MAXVAL=2147483647,MINVAL=-2147483648), f2 %Library.String(MAXLEN=20),""date"" %Library.TimeStamp DEFAULT OBJECTSCRIPT'##class(%TSQL.SysFunc).GETDATE()')","")%tsqlexit#execute Do SPFinal^%apiTSQL()#execute Do SPWriteQuit^%apiTSQL(0)6.1.3 Using the GENRAW SettingThe output returned by the above table compile is difficult to follow; you can use theGENRAW/GR setting to trim much of this compilation scaffolding. At the terminal prompt,enter:SAMPLES:TSQL>=GR=1Then enter the CREATE TABLE lines again. The compile generates a much shorter output:STATS:GENCODEGenerated code :-Set tsqlgen0002=$$ESu^%apiTSQL2(.SQLCODE,.%msg," CREATE TABLE Sample.MyTest (f1 %Library.Integer(MAXVAL=2147483647,MINVAL=-2147483648), f2 %Library.String(MAXLEN=20), ""date"" %Library.TimeStamp DEFAULTOBJECTSCRIPT '##class(%TSQL.SysFunc).GETDATE()') ","",0)#execute Do CheckPrepare^%apiTSQL2(" CREATE TABLESample.MyTest (f1 %Library.Integer(MAXVAL=2147483647,MINVAL=-2147483648), f2 %Library.String(MAXLEN=20),""date"" %Library.TimeStamp DEFAULT OBJECTSCRIPT'##class(%TSQL.SysFunc).GETDATE()')","")This setting (GR=1) will persist until you change it. It only affects the shell and the batchloader, not Studio (use the SETTINGS command there). Code compiled using the GR=1setting usually cannot be run. Also, temporary tables and queries now require a stored procedurecontext and can no longer be created on-the-fly in the shell.Caché Transact-SQL (TSQL) Migration Guide 47


Using the TSQL Shell6.1.4 TSQL Shell HelpFor shell help, type:• ? — for general help on using the shell.• ?SET — for help on settings.• ?EXT — for help on Caché extensions to TSQL.• ?BUF — for help on the simple buffer-editing facilities of the shell.6.1.5 Exiting the TSQL ShellTo exit the TSQL shell, type ^ at the terminal prompt.6.2 Qualifiers/c and /xIn its simplest form, ending a line of code with /c tells the TSQL shell to compile the TSQLcode. Ending a line of code with /x tells the TSQL shell to compile and execute the TSQLcode. However, ending a line with /c or /x can mean several different things, depending onwhether the code being compiled is a CREATE PROCEDURE or not, and whether thetarget is TSQL or Caché ObjectScript. The useful settings are given below:/cTarget = COS/cTarget = TSQL/xTarget = COS/xTarget = TSQLCREATE PROCwrites ObjectScript methodwrites TSQL methodn/an/anot CREATE PROCcompile MAC to INTn/acompile MAC to INT and executeINTn/a48 Caché Transact-SQL (TSQL) Migration Guide


If no CREATE PROCEDURE is given, the code is compiled to a temporary routine. IfCREATE PROCEDURE is given, the code is compiled to a class method.Writing a Caché ObjectScript method using /c on procedure code isn't useful in the usualway, in that you don't generally want ObjectScript methods, you want TSQL ones that youcan compile in Studio. However, it is a useful technique in the early stages of a project usingthe batch loader because you can quickly test-compile many stored procedures and get adetailed log of the results./tThe code-generation target defaults to "COS" in the shell. To set it to "TSQL" (for the nextcompilation only) type this:tsql/tSettings6.3 SettingsSettings are a Caché TSQL extension used to tailor the behavior of the compiler and colorizer.Each setting has a name and an abbreviation, as in GENRAW/GR. Either form may be used.Persistent settings are associated with the shell, and are stored in ^%TSQL("SETTINGS").You can set them in the TSQL shell using the = command. You can set a single setting, or acomma-separated list of settings. Issuing an = command deletes all previous settings. To resetall settings to defaults specify just the = command.A boolean flag setting can be set to a value either by assignment (for example, =CIC=1), orby just naming the setting (=CIC, which is equivalent to =CIC=1). You can turn off a flagsetting by setting it to 0 (=CIC=0).A string or integer setting is set to a value using assignment (for example, =SM='LOGICAL').You can revert to the default setting by assigning an empty string (=SM='').The shell command ?SET lists the available settings. For further details on these settings,refer to the Commands chapter.There is also a Caché TSQL extension command called SETTINGS which can be used tocontrol local settings. For further details, refer to the Commands chapter.^%SYS("tsql","defaultsettings")Holds system-wide default TSQL settings.Caché Transact-SQL (TSQL) Migration Guide 49


Using the TSQL ShellSettings in this global node provide system-wide default settings which can be overriddenusing the SETTINGS command. The format is a comma-separated list ofsettings (for example, GR,CIC,TNT=[dat.]obj).There is currently no way of setting or examining this except by setting or viewingthe global node directly.^%SYS("tsql","suppressfetch")Holds a list of FetchXxx methods whose code-generation is to be suppressed.Set this node to one or more of these names (case-insensitive) separated by ":"s:• FETCH• FETCHROWS• FETCHODBCAny name which appears in the list will not have code generated for it when a TSQLquery is compiled. This means that the functionality provided by that method willnot be available:• FETCH — local use of %ResultSet• FETCHROWS — use of the FetchRows method• FETCHODBC — ODBC/JDBCThere is currently no way of setting or examining this except by setting or viewingthe global node directly.50 Caché Transact-SQL (TSQL) Migration Guide

More magazines by this user
Similar magazines