DB2 Universal Database for iSeries SQL Reference

ERserver

iSeries

DB2 Universal Database for iSeries SQL Reference
Version 5

ERserver
iSeries

DB2 Universal Database for iSeries SQL Reference
Version 5

© Copyright International Business Machines Corporation 1998, 2002. All rights reserved. US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

Contents
About DB2 UDB for iSeries SQL Reference . . . . . . . . . . . . . xiii
| Standards Compliance . . . . . . . . . . xiii
Who should read the SQL Reference book . . . Assumptions Relating to Examples of SQL Statements . . . . . . . . . . . . How to Read Syntax Diagrams . . . . . . Conventions for Describing Mixed Data Values SQL Accessibility . . . . . . . . . . . What’s new for V5R2 in the SQL Reference book . xiii . xiv . xv xvii . xvii xviii Authorization, Privileges and Object Ownership . Storage Structures . . . . . . . . . . . . 36 . 38

Chapter 2. Language Elements . . . . 39
Characters . . . . . . . . . . . . . . . 39 Tokens . . . . . . . . . . . . . . . . 41 Identifiers . . . . . . . . . . . . . . . 43 SQL Identifiers . . . . . . . . . . . . 43 System identifiers . . . . . . . . . . . 43 Host Identifiers . . . . . . . . . . . . 44 Naming Conventions . . . . . . . . . . . 45 SQL Path . . . . . . . . . . . . . . 53 Qualification of Unqualified Object Names . . . 53 SQL Names and System Names: Special Considerations . . . . . . . . . . . . 55 Aliases . . . . . . . . . . . . . . . . 56 Authorization IDs and Authorization-Names . . . 57 Example . . . . . . . . . . . . . . 58 Data Types . . . . . . . . . . . . . . 59 Nulls . . . . . . . . . . . . . . . 61 Numbers . . . . . . . . . . . . . . 61 Character Strings . . . . . . . . . . . 62 Character Encoding Schemes . . . . . . . 63 Graphic Strings . . . . . . . . . . . . 64 Graphic Encoding Schemes . . . . . . . . 65 Binary Strings . . . . . . . . . . . . 65 Large Objects (LOBs) . . . . . . . . . . 65 Limitations on Use of Strings . . . . . . . 67 Datetime Values . . . . . . . . . . . . 67 DataLink Values . . . . . . . . . . . . 72 Row ID Values . . . . . . . . . . . . 73 User-Defined Types . . . . . . . . . . . 73 Promotion of Data Types . . . . . . . . . . 76 Casting Between Data Types . . . . . . . . . 78 Assignments and Comparisons . . . . . . . . 81 Numeric Assignments . . . . . . . . . . 83 String Assignments . . . . . . . . . . . 84 Datetime Assignments . . . . . . . . . . 86 DataLink Assignments . . . . . . . . . . 87 Row ID Assignments . . . . . . . . . . 88 Distinct Type Assignments . . . . . . . . 88 Numeric Comparisons . . . . . . . . . . 90 String Comparisons. . . . . . . . . . . 90 Datetime Comparisons . . . . . . . . . 92 Distinct Type Comparisons . . . . . . . . 92 Rules for Result Data Types . . . . . . . . . 94 Numeric Operands . . . . . . . . . . . 94 Character and Graphic String Operands . . . . 95 Binary String Operands . . . . . . . . . 96 Datetime Operands . . . . . . . . . . . 96 Distinct Type Operands . . . . . . . . . 97 DataLink Operands . . . . . . . . . . . 97 Conversion Rules for Operations That Combine Strings . . . . . . . . . . . . . . . . 98 Constants . . . . . . . . . . . . . . 100

| |

Chapter 1. Concepts . . . . . . . . . 1
Relational Database . . . . . . . . . . . . 1 Structured Query Language . . . . . . . . . 3 Static SQL . . . . . . . . . . . . . . 3 Dynamic SQL . . . . . . . . . . . . . 3 Extended Dynamic SQL . . . . . . . . . 4 Interactive SQL . . . . . . . . . . . . 4 SQL Call Level Interface (CLI) and Open Database Connectivity (ODBC) . . . . . . . . . . 4 Java Database Connectivity (JDBC) and Embedded SQL for Java (SQLJ) Programs . . . . . . . 4 Schemas . . . . . . . . . . . . . . . . 5 Tables . . . . . . . . . . . . . . . . 5 Keys . . . . . . . . . . . . . . . . . 6 Primary Keys and Unique Keys . . . . . . . . 6 Referential Integrity . . . . . . . . . . . . 7 Check Constraints . . . . . . . . . . . . 9 Triggers . . . . . . . . . . . . . . . . 9 Indexes . . . . . . . . . . . . . . . . 11 Views . . . . . . . . . . . . . . . . 12 Aliases . . . . . . . . . . . . . . . . 13 Packages and Access Plans . . . . . . . . . 13 Procedures . . . . . . . . . . . . . . 14 Catalog . . . . . . . . . . . . . . . . 15 Application Processes, Concurrency, and Recovery 15 Locking, Commit, and Rollback . . . . . . 17 Unit of Work . . . . . . . . . . . . . 18 Rolling Back Work . . . . . . . . . . . 19 Rolling back all changes . . . . . . . . . 19 Rolling back selected changes using savepoints 20 Threads . . . . . . . . . . . . . . 20 Isolation Level . . . . . . . . . . . . . 21 Comparison of Isolation Levels . . . . . . . 24 Distributed Relational Database . . . . . . . 25 Application Servers . . . . . . . . . . . 26 CONNECT (Type 1) and CONNECT (Type 2) . . 27 Remote Unit of Work . . . . . . . . . . 27 Application-Directed Distributed Unit of Work 29 Data Representation Considerations . . . . . 32 Character Conversion . . . . . . . . . . . 32 Character Sets and Code Pages . . . . . . . 33 Coded Character Sets and CCSIDs . . . . . . 34 Default CCSID . . . . . . . . . . . . 35 Sort Sequence . . . . . . . . . . . . . 35
© Copyright IBM Corp. 1998, 2002

|

| | | | |

iii

|

|

|

Integer Constants . . . . . . . . . . Floating-Point Constants. . . . . . . . Decimal Constants. . . . . . . . . . Character-String Constants . . . . . . . Graphic-String Constants . . . . . . . Binary-String Constants . . . . . . . . Decimal Point . . . . . . . . . . . Delimiters . . . . . . . . . . . . Special Registers . . . . . . . . . . . CURRENT DATE or CURRENT_DATE . . . CURRENT PATH, CURRENT_PATH, or CURRENT FUNCTION PATH . . . . . . CURRENT SCHEMA . . . . . . . . . CURRENT SERVER or CURRENT_SERVER . CURRENT TIME or CURRENT_TIME . . . CURRENT TIMESTAMP or CURRENT_TIMESTAMP . . . . . . . CURRENT TIMEZONE or CURRENT_TIMEZONE . . . . . . . . USER . . . . . . . . . . . . . . Column Names. . . . . . . . . . . . Qualified Column Names . . . . . . . Correlation Names . . . . . . . . . Column Name Qualifiers to Avoid Ambiguity Column Name Qualifiers in Correlated References . . . . . . . . . . . . Unqualified Column Names . . . . . . References to Variables . . . . . . . . . References to Host Variables . . . . . . Host Variables in Dynamic SQL . . . . . References to LOB Host Variables . . . . References to LOB Locator Variables . . . . References to LOB File Reference Variables . Host Structures . . . . . . . . . . . Host Structure Arrays . . . . . . . . Functions . . . . . . . . . . . . . . Types of Functions . . . . . . . . . Function resolution . . . . . . . . . Determining the Best Fit . . . . . . . . Function Invocation . . . . . . . . . Expressions . . . . . . . . . . . . . Without Operators. . . . . . . . . . With Arithmetic Operators . . . . . . . With the Concatenation Operator . . . . . Scalar Subselect . . . . . . . . . . Datetime Operands and Durations . . . . Datetime Arithmetic in SQL . . . . . . Precedence of Operations . . . . . . . CASE Expressions . . . . . . . . . . CAST Specification . . . . . . . . . Predicates . . . . . . . . . . . . . Basic Predicate . . . . . . . . . . . Quantified Predicate . . . . . . . . . BETWEEN Predicate . . . . . . . . . EXISTS Predicate . . . . . . . . . . IN Predicate . . . . . . . . . . . . LIKE Predicate . . . . . . . . . . . NULL Predicate . . . . . . . . . . Search Conditions . . . . . . . . . . . Examples . . . . . . . . . . . . .

. . . . . . . . . . . . . .

100 100 100 100 101 103 103 104 106 106 106 107 107 107

Chapter 3. Built-In Functions . . . . . 165
Column Functions . . . . . . . AVG . . . . . . . . . . COUNT . . . . . . . . . COUNT_BIG . . . . . . . MAX . . . . . . . . . . MIN . . . . . . . . . . STDDEV_POP or STDDEV . . . SUM . . . . . . . . . . VAR_POP or VARIANCE or VAR Scalar Functions . . . . . . . Example . . . . . . . . . ABS . . . . . . . . . . ACOS . . . . . . . . . . ANTILOG . . . . . . . . ASIN . . . . . . . . . . ATAN . . . . . . . . . . ATANH . . . . . . . . . ATAN2 . . . . . . . . . BIGINT . . . . . . . . . BLOB . . . . . . . . . . CEILING . . . . . . . . . CHAR . . . . . . . . . . CHARACTER_LENGTH . . . CLOB . . . . . . . . . . COALESCE . . . . . . . . CONCAT . . . . . . . . . COS . . . . . . . . . . COSH . . . . . . . . . . COT . . . . . . . . . . CURDATE . . . . . . . . CURTIME . . . . . . . . DATE . . . . . . . . . . DAY . . . . . . . . . . DAYOFMONTH . . . . . . DAYOFWEEK . . . . . . . DAYOFWEEK_ISO . . . . . DAYOFYEAR . . . . . . . DAYS . . . . . . . . . . DBCLOB . . . . . . . . . DECIMAL or DEC . . . . . DEGREES . . . . . . . . DIFFERENCE . . . . . . . DIGITS . . . . . . . . . DLCOMMENT . . . . . . . DLLINKTYPE . . . . . . . DLURLCOMPLETE . . . . . DLURLPATH . . . . . . . DLURLPATHONLY . . . . . DLURLSCHEME . . . . . . DLURLSERVER . . . . . . DLVALUE . . . . . . . . DOUBLE_PRECISION or DOUBLE EXP . . . . . . . . . . FLOAT . . . . . . . . . FLOOR . . . . . . . . . GRAPHIC . . . . . . . . HASH . . . . . . . . . . HEX . . . . . . . . . . HOUR. . . . . . . . . . IDENTITY_VAL_LOCAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 171 172 174 175 176 177 178 179 180 180 181 182 183 184 185 186 187 188 189 191 192 197 198 202 203 204 205 206 207 208 209 211 212 213 214 215 216 217 219 222 223 224 225 226 227 228 229 230 231 232 234 236 237 238 239 242 243 244 245

|

. 108 . . . . . 108 108 109 109 109 111 112 113 115 115 118 118 118 119 121 123 124 124 125 126 128 130 130 130 133 135 135 136 140 141 144 148 149 150 152 153 154 156 161 162 163

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

|

iv

DB2 UDB for iSeries SQL Reference V5R2

|

|

|

IFNULL . . . . . . INTEGER or INT . . . JULIAN_DAY . . . . LAND . . . . . . . LCASE . . . . . . LEFT . . . . . . . LENGTH . . . . . . LN . . . . . . . . LNOT . . . . . . . LOCATE . . . . . . LOG10 . . . . . . LOR . . . . . . . LOWER . . . . . . LTRIM . . . . . . MAX . . . . . . . MICROSECOND . . . MIDNIGHT_SECONDS . MIN . . . . . . . MINUTE . . . . . . MOD . . . . . . . MONTH . . . . . . NODENAME . . . . NODENUMBER . . . NOW . . . . . . . NULLIF . . . . . . PARTITION . . . . . PI . . . . . . . . POSITION or POSSTR . POWER . . . . . . QUARTER . . . . . RADIANS . . . . . RAND . . . . . . . REAL . . . . . . . ROUND . . . . . . ROWID . . . . . . RRN . . . . . . . RTRIM . . . . . . SECOND . . . . . . SIGN . . . . . . . SIN . . . . . . . . SINH . . . . . . . SMALLINT . . . . . SOUNDEX . . . . . SPACE . . . . . . SQRT . . . . . . . STRIP . . . . . . . SUBSTRING or SUBSTR . TAN . . . . . . . TANH . . . . . . . TIME . . . . . . . TIMESTAMP . . . . TIMESTAMPDIFF . . . TRANSLATE . . . . TRIM . . . . . . . TRUNCATE or TRUNC . UCASE . . . . . . UPPER . . . . . . VALUE . . . . . . VARCHAR . . . . . VARGRAPHIC . . . . WEEK . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

249 250 252 253 254 255 257 258 259 260 261 262 263 264 265 266 267 268 269 270 272 273 274 275 276 277 278 279 281 282 283 284 285 286 288 289 290 291 292 293 294 295 296 297 298 299 300 303 304 305 306 308 309 311 313 315 316 317 318 322 325

WEEK_ISO XOR . . YEAR . . ZONED .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

326 327 328 329

Chapter 4. Queries . . . . . . . . . 331
Authorization . . . . . . . subselect . . . . . . . . . select-clause . . . . . . . from-clause . . . . . . . where-clause . . . . . . group-by-clause . . . . . having-clause . . . . . . Examples of a subselect . . . fullselect . . . . . . . . . Rules for Columns . . . . Examples of a fullselect . . . select-statement . . . . . . common-table-expression . . order-by-clause . . . . . . fetch-first-clause . . . . . update-clause . . . . . . read-only-clause . . . . . optimize-clause . . . . . . isolation-clause . . . . . . Examples of a select-statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 332 333 337 342 343 345 346 348 348 350 351 352 353 355 356 357 358 359 360

Chapter 5. Statements

. . . . . . . 363
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 368 368 369 369 369 370 370 370 372 372 372 373 378 378 384 386 386 387 389 389 390 391 393 395 395 395 395 395 396

|

|

How SQL Statements Are Invoked . . . . Embedding a Statement in an Application Program . . . . . . . . . . . . Dynamic Preparation and Execution . . . Static Invocation of a select-statement . . Dynamic Invocation of a select-statement . Interactive Invocation . . . . . . . SQL Return Codes . . . . . . . . . . SQLSTATE . . . . . . . . . . . SQLCODE . . . . . . . . . . . SQL Comments . . . . . . . . . . . ALTER TABLE . . . . . . . . . . . Invocation . . . . . . . . . . . Authorization . . . . . . . . . . Syntax . . . . . . . . . . . . . Description . . . . . . . . . . . ADD column-definition . . . . . . . ALTER column-alteration . . . . . . . DROP COLUMN . . . . . . . . . ADD unique-constraint . . . . . . . ADD referential-constraint . . . . . . ADD check-constraint . . . . . . . DROP . . . . . . . . . . . . . Notes . . . . . . . . . . . . . Cascaded Effects . . . . . . . . . Examples . . . . . . . . . . . . BEGIN DECLARE SECTION . . . . . . Invocation . . . . . . . . . . . Authorization . . . . . . . . . . Syntax . . . . . . . . . . . . . Description . . . . . . . . . . . Examples . . . . . . . . . . . .

Contents

v

|

|

|

CALL . . . . . . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . CLOSE . . . . . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Example . . . . . . . . . . COMMENT . . . . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . COMMIT . . . . . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Example . . . . . . . . . . CONNECT (Type 1) . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . CONNECT (Type 2) . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . CREATE ALIAS . . . . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . CREATE DISTINCT TYPE . . . . . Invocation . . . . . . . . . Authorization . . . . . . . . Syntax . . . . . . . . . . . Description . . . . . . . . . Notes . . . . . . . . . . . Examples . . . . . . . . . . CREATE FUNCTION . . . . . . . Notes . . . . . . . . . . . CREATE FUNCTION (External Scalar) . Invocation . . . . . . . . . Authorization . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

397 397 397 397 398 400 402 403 403 403 403 403 403 404 405 405 405 407 409 413 413 414 414 414 414 414 414 416 417 417 417 417 417 418 421 422 422 422 422 422 424 425 426 426 426 426 426 427 428 429 429 429 429 430 432 435 436 436 440 440 440

| | | | | | |

| | | | | | |

| |

| | | | | |

Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Examples . . . . . . . . . CREATE FUNCTION (External Table) Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Example . . . . . . . . . CREATE FUNCTION (Sourced) . . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Examples . . . . . . . . . CREATE FUNCTION (SQL Scalar) . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Example . . . . . . . . . CREATE FUNCTION (SQL Table) . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Example . . . . . . . . . CREATE INDEX . . . . . . . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Examples . . . . . . . . . CREATE PROCEDURE . . . . . Notes . . . . . . . . . . CREATE PROCEDURE (External) . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Example . . . . . . . . . CREATE PROCEDURE (SQL) . . . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . . Example . . . . . . . . . CREATE SCHEMA . . . . . . Invocation . . . . . . . . Authorization . . . . . . . Syntax . . . . . . . . . . Description . . . . . . . . Notes . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

441 443 453 454 456 456 456 457 459 467 468 470 470 470 471 473 476 477 479 479 479 479 482 485 487 488 488 488 488 491 494 496 497 497 497 497 498 499 500 501 501 502 502 502 502 505 511 512 513 513 513 514 517 519 521 522 522 522 522 523 524

vi

DB2 UDB for iSeries SQL Reference V5R2

|

| |

| | | | | | | | | | |

Examples . . . . . . . . . . . CREATE TABLE . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . column-definition . . . . . . . . LIKE . . . . . . . . . . . . as-subquery-clause . . . . . . . copy-options . . . . . . . . . unique-constraint . . . . . . . . referential-constraint . . . . . . . check-constraint . . . . . . . . nodegroup-clause . . . . . . . . Notes . . . . . . . . . . . . Rules for System Name Generation . . Examples . . . . . . . . . . . CREATE TRIGGER . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . CREATE VIEW . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . DECLARE CURSOR . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . DECLARE GLOBAL TEMPORARY TABLE Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . column-definition . . . . . . . . LIKE . . . . . . . . . . . . as-subquery-clause . . . . . . . copy-options . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . DECLARE PROCEDURE . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . DECLARE STATEMENT . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

525 526 526 526 527 533 533 544 545 546 547 548 550 550 551 554 555 557 557 557 559 560 565 568 570 570 570 571 571 574 575 577 577 577 578 578 580 582 584 584 584 585 588 588 594 594 595 597 598 599 599 599 599 602 607 607 608 608 608 608 608

|

Example . . . . . DECLARE VARIABLE . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Notes . . . . . . Example . . . . . DELETE . . . . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . DELETE Rules . . . Notes . . . . . . Examples . . . . . DESCRIBE . . . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Notes . . . . . . Example . . . . . DESCRIBE TABLE . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Notes . . . . . . Example . . . . . DISCONNECT . . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Notes . . . . . . Examples . . . . . DROP . . . . . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Note . . . . . . Examples . . . . . END DECLARE SECTION Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Examples . . . . . EXECUTE . . . . . Invocation . . . . Authorization . . . Syntax . . . . . . Description . . . . Notes . . . . . . Example . . . . . EXECUTE IMMEDIATE . Invocation . . . . Authorization . . . Syntax . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

608 610 610 610 610 610 611 611 613 613 613 614 614 616 616 617 619 619 619 619 619 621 622 624 624 624 624 624 626 626 628 628 628 628 628 629 629 630 630 630 631 633 638 639 640 640 640 640 640 640 641 641 641 641 641 642 643 644 644 644 644

Contents

vii

| | | | | | |

Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . FETCH . . . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . single-fetch . . . . . . . . . . multiple-row-fetch . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . FREE LOCATOR . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Example . . . . . . . . . . . GRANT (Distinct Type Privileges) . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . GRANT (Function or Procedure Privileges) Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . GRANT (Package Privileges) . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . GRANT (Table or View Privileges) . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . HOLD LOCATOR . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . INCLUDE . . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . INSERT . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

644 645 645 646 646 646 646 647 648 648 650 651 652 652 652 652 652 652 653 653 653 653 653 654 655 656 656 656 656 658 661 662 663 663 663 663 663 664 664 665 665 665 665 666 667 669 670 670 670 670 670 670 670 672 672 672 672 672 673 673 674

| | | | | | |

Invocation . . . Authorization . . Syntax . . . . . Description . . . insert-multiple-rows INSERT Rules . . Notes . . . . . Examples . . . . LABEL . . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . LOCK TABLE . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Example . . . . OPEN . . . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . PREPARE . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . RELEASE (Connection) Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . RELEASE SAVEPOINT Invocation . . . Authorization . . Syntax . . . . . Description . . . Note . . . . . Example . . . . RENAME . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . REVOKE (Distinct Type Invocation . . . Authorization . . Syntax . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Privileges) . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

674 674 675 676 678 678 679 680 682 682 682 682 683 683 684 685 685 685 685 685 686 686 687 687 687 687 687 688 690 692 692 692 692 693 695 699 701 701 701 701 701 702 702 703 703 703 703 703 703 703 704 704 704 704 704 705 706 707 707 707 707

viii

DB2 UDB for iSeries SQL Reference V5R2

| | | | | | | |

Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . REVOKE (Function or Procedure Privileges) Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . REVOKE (Package Privileges) . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . REVOKE (Table or View Privileges) . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . ROLLBACK . . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . SAVEPOINT . . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Example . . . . . . . . . . . SELECT . . . . . . . . . . . . SELECT INTO . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Note . . . . . . . . . . . . Examples . . . . . . . . . . . SET CONNECTION . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Example . . . . . . . . . . . SET OPTION . . . . . . . . . . Invocation . . . . . . . . . . Authorization . . . . . . . . . Syntax . . . . . . . . . . . . Description . . . . . . . . . . Notes . . . . . . . . . . . . Examples . . . . . . . . . . . SET PATH . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

707 708 708 709 709 709 709 711 714 715 716 716 716 716 716 717 717 718 718 718 718 718 719 720 721 721 721 721 721 722 724 725 725 725 725 725 726 726 727 728 728 728 728 729 729 730 731 731 731 731 731 732 732 734 734 734 734 738 747 747 748

| | | | | | |

| | | | | | |

Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Example . . . . SET RESULT SETS . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Example . . . . SET SCHEMA . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . SET TRANSACTION . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . SET transition-variable Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . SET variable . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . UPDATE . . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . UPDATE Rules . . Notes . . . . . Examples . . . . VALUES . . . . . Invocation . . . Authorization . . Syntax . . . . . Description . . . Notes . . . . . Examples . . . . VALUES INTO . . . Invocation . . . Authorization . . Syntax . . . . . Description . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

748 748 748 748 749 750 751 751 751 751 751 752 753 754 754 754 754 754 754 755 756 756 756 756 756 757 758 759 759 759 759 759 760 760 761 761 761 761 761 762 762 763 763 763 765 766 769 769 771 772 772 772 772 772 772 772 774 774 774 774 774

Contents

ix

Notes . . . Examples . . WHENEVER . Invocation . Authorization Syntax . . . Description . Notes . . . Example . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

774 775 777 777 777 777 777 777 778

Chapter 6. SQL Control Statements
SQL procedure statement . . Syntax . . . . . . . . Notes . . . . . . . . assignment-statement . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Example . . . . . . . CALL statement . . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Example . . . . . . . CASE statement . . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Examples . . . . . . . compound-statement . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Examples . . . . . . . FOR statement . . . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Example . . . . . . . GET DIAGNOSTICS statement Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Example . . . . . . . GOTO statement . . . . . Syntax . . . . . . . . Description . . . . . . Notes . . . . . . . . Example . . . . . . . IF statement . . . . . . . Syntax . . . . . . . . Description . . . . . . Example . . . . . . . ITERATE statement . . . . Syntax . . . . . . . . Description . . . . . . Example . . . . . . . LEAVE statement . . . . . Syntax . . . . . . . . Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

779
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782 782 783 784 784 784 785 785 786 786 786 786 787 788 788 788 789 789 790 790 793 795 796 797 797 797 798 798 799 799 799 800 800 802 802 802 802 802 804 804 804 804 806 806 806 806 807 807 807

| References to SQL Parameters and Variables . . . 781

Notes . . . . . Examples . . . . LOOP statement . . Syntax . . . . . Description . . . Examples . . . . REPEAT statement . Syntax . . . . . Description . . . Example . . . . RESIGNAL statement . Syntax . . . . . Description . . . Notes . . . . . Example . . . . RETURN statement . Syntax . . . . . Description . . . Notes . . . . . Example . . . . SIGNAL statement . Syntax . . . . . Description . . . Notes . . . . . Example . . . . WHILE statement . . Syntax . . . . . Description . . . Example . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

807 807 808 808 808 808 809 809 809 809 811 811 811 812 813 814 814 814 814 815 816 816 816 817 818 819 819 819 819

Appendix A. SQL Limits . . . . . . . 821 Appendix B. SQL Communication Area . . . . . . . . . . . . . . . 825
Field Descriptions . . . . . . INCLUDE SQLCA Declarations . . . . . . . . . . . . 825 . 831

Appendix C. Characteristics of SQL Statements . . . . . . . . . . . . 835
| |
Actions Allowed on SQL Statements . . . . . . 836 SQL Statement Data Access Indication in Routines 838 Considerations for Using Distributed Relational Database . . . . . . . . . . . . . . . 840 CONNECT (Type 1) and CONNECT (Type 2) Differences . . . . . . . . . . . . . 845

|

Appendix D. SQL Descriptor Area (SQLDA) . . . . . . . . . . . . . 847
Field Descriptions in an SQLDA Header . . . Determining How Many SQLVAR Occurrences are Needed . . . . . . . . . . . . Field Descriptions in an Occurrence of SQLVAR SQLTYPE and SQLLEN . . . . . . . . . CCSID Values in SQLDATA or SQLNAME . . Unrecognized and Unsupported SQLTYPES . . INCLUDE SQLDA Declarations . . . . . . For C and C++ . . . . . . . . . . . For COBOL . . . . . . . . . . . . For ILE COBOL . . . . . . . . . . . 849 . 850 852 . 854 . 856 . 856 . 857 . 857 . 860 . 860

x

DB2 UDB for iSeries SQL Reference V5R2

For PL/I . . . . For ILE RPG/400 .

. .

. .

. .

. .

. .

. .

. .

. .

. .

. 861 . 862

Appendix E. CCSID Values . . . . . . 863 Appendix F. DB2 UDB for iSeries Catalog Views . . . . . . . . . . . 881
|
Notes . . . . . . . . . . iSeries Catalog Tables and Views . SYSCATALOGS . . . . . SYSCHKCST . . . . . . SYSCOLUMNS . . . . . . SYSCST . . . . . . . . SYSCSTCOL . . . . . . . SYSCSTDEP . . . . . . . SYSFUNCS . . . . . . . SYSINDEXES . . . . . . SYSJARCONTENTS . . . . SYSJAROBJECTS . . . . . SYSKEYCST . . . . . . . SYSKEYS . . . . . . . . SYSPACKAGE . . . . . . SYSPARMS . . . . . . . SYSPROCS . . . . . . . SYSREFCST . . . . . . . SYSROUTINEDEP . . . . . SYSROUTINES . . . . . . SYSTABLES . . . . . . . SYSTRIGCOL . . . . . . SYSTRIGDEP . . . . . . SYSTRIGGERS . . . . . . SYSTRIGUPD . . . . . . SYSTYPES . . . . . . . SYSVIEWDEP . . . . . . SYSVIEWS . . . . . . . ODBC and JDBC Catalog Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 882 884 885 887 888 897 898 899 900 906 907 908 909 910 911 913 917 922 923 924 932 934 935 936 940 941 946 948 949

|

| SQLCOLPRIVILEGES . . . . . . . . . 950 | SQLCOLUMNS . . . . . . . . . . . 951 | SQLFOREIGNKEYS . . . . . . . . . . 956 | SQLPRIMARYKEYS . . . . . . . . . . 957 | SQLPROCEDURECOLS . . . . . . . . . 958 | SQLPROCEDURES . . . . . . . . . . 962 | SQLSCHEMAS . . . . . . . . . . . . 963 | SQLSPECIALCOLUMNS . . . . . . . . 964 | SQLSTATISTICS . . . . . . . . . . . 966 | SQLTABLEPRIVILEGES . . . . . . . . . 967 | SQLTABLES . . . . . . . . . . . . . 968 | SQLTYPEINFO . . . . . . . . . . . . 969 | SQLUDTS . . . . . . . . . . . . . 974 | ANS and ISO Catalog Views . . . . . . . . 976 | CHARACTER_SETS . . . . . . . . . . 977 | CHECK_CONSTRAINTS . . . . . . . . 978 | COLUMNS . . . . . . . . . . . . . 979 | INFORMATION_SCHEMA_CATALOG_NAME 983 | PARAMETERS . . . . . . . . . . . . 984 | REFERENTIAL_CONSTRAINTS . . . . . . 988 | ROUTINES . . . . . . . . . . . . . 989 | SCHEMATA . . . . . . . . . . . . . 997 | SQL_FEATURES . . . . . . . . . . . 998 | SQL_LANGUAGES . . . . . . . . . . 999 | SQL_SIZING . . . . . . . . . . . . 1001 | TABLE_CONSTRAINTS . . . . . . . . 1002 | TABLES . . . . . . . . . . . . . . 1003 | USER_DEFINED_TYPES . . . . . . . . 1004 | VIEWS . . . . . . . . . . . . . . 1008 | Appendix G. Reserved Words . . . . 1009

Bibliography . . . . . . . . . . . 1011 Index . . . . . . . . . . . . . . 1013

|

Contents

xi

xii

DB2 UDB for iSeries SQL Reference V5R2

About DB2 UDB for iSeries SQL Reference
This book defines Structured Query Language (SQL) as supported by DB2 Query Manager and SQL Development Kit. It contains reference information for the tasks of system administration, database administration, application programming, and operation. This manual includes syntax, usage notes, keywords, and examples for each of the SQL statements used on the system. For more information about this guide, see the following sections: v “Standards Compliance” v “Who should read the SQL Reference book” v “Assumptions Relating to Examples of SQL Statements” on page xiv v “How to Read Syntax Diagrams” on page xv v “Conventions for Describing Mixed Data Values” on page xvii v “SQL Accessibility” on page xvii v “What’s new for V5R2 in the SQL Reference book” on page xviii | | | | | | | | | | | | | | | | | | |

Standards Compliance
DB2 UDB for iSeries Version 5 Release 2 complies with the following IBM and Industry SQL Standards: v ISO (International Standards Organization) 9075: 1992, Database Language SQL Entry Level v ISO (International Standards Organization) 9075-4: 1996, Database Language SQL - Part 4: Persistent Stored Modules (SQL/PSM) v ISO (International Standards Organization) 9075: 1999, Database Language SQL Core v ANSI (American National Standards Institute) X3.135-1992, Database Language SQL - Entry Level v ANSI (American National Standards Institute) X3.135–4: 1996, Database Language SQL - Part 4: Persistent Stored Modules (SQL/PSM) v ANSI (American National Standards Institute) X3.135-1999, Database Language SQL - Core v IBM SQL Reference Version 2, SC26-8416. For strict adherence to the standards, consider using the standards option. For more information, see SQLCURRULE in “SET OPTION” on page 734 and on the SQL precompiler commands.

Who should read the SQL Reference book
This book is intended for programmers who want to write applications that will use SQL to access an iSeries database. It is assumed that you possess an understanding of system administration, database administration, or application programming for the iSeries server, as provided by the SQL Programming Concepts book and that you have some knowledge of the following: v COBOL for iSeries
© Copyright IBM Corp. 1998, 2002

xiii

|

v v v v v v v

ILE C compiler ILE C++ compiler ILE COBOL compiler Toolbox for Java or Developer Kit for Java ILE RPG compiler iSeries PL/I REXX

v RPG III (part of RPG for iSeries) v Structured Query Language (SQL) References in this book to RPG and COBOL refer to the RPG or COBOL language in general. References to COBOL for iSeries, ILE COBOL for iSeries, RPG for iSeries, or RPG III (part of RPG for iSeries) refer to specific elements of the product where they differ from each other. This manual is a reference rather than a tutorial. It assumes you are already familiar with SQL programming. This manual also assumes that you will be writing applications solely for the iSeries server. If you need more information about using SQL statements, statement syntax, and parameters, see the SQL Programming Concepts book. If you are planning applications that are portable to other IBM environments, it will be necessary for you to refer to books for those environments in addition to this one (such as IBM SQL Reference Version 2, SC26-8416). See the following sections for more details: v “Assumptions Relating to Examples of SQL Statements” v “How to Read Syntax Diagrams” on page xv

Assumptions Relating to Examples of SQL Statements
The examples of SQL statements shown in this guide are based on the sample tables in Appendix A of the SQL Programming Concepts book and assume the following: v They are shown in the interactive SQL environment or written in COBOL. EXEC SQL and END-EXEC are used to delimit an SQL statement in a COBOL program. A description of how to use SQL statements in a COBOL program is provided in the SQL Programming with Host Languages book. v Each SQL example is shown on several lines, with each clause of the statement on a separate line. v SQL keywords are highlighted. v Table names used in the examples are the sample tables provided in Appendix A of the SQL Programming Concepts book and use the schema CORPDATA. Table names that are not provided in that appendix should use schemas that you create. You can create a set of sample tables in your own schema by issuing the following SQL statement:
CALL QSYS.CREATE_SQL_SAMPLE (’your-schema-name’)

| | | | | |

v Calculated columns are enclosed in parentheses, (). v The SQL naming convention is used. v The APOST and APOSTSQL precompiler options are assumed (although they are not the default in COBOL). Character-string constants within SQL and host language statements are delimited by apostrophes (’).

xiv

DB2 UDB for iSeries SQL Reference V5R2

v A sort sequence of *HEX is used. Whenever the examples vary from these assumptions, it is stated. See also “Code disclaimer information.” | | | | | | | | | | |

Code disclaimer information
This document contains programming examples. IBM grants you a nonexclusive copyright license to use all programming code examples from which you can generate similar function tailored to your own specific needs. All sample code is provided by IBM for illustrative purposes only. These examples have not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you ″AS IS″ without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.

How to Read Syntax Diagrams
Throughout this book, syntax is described using the structure defined as follows: v Read the syntax diagrams from left to right, from top to bottom, following the path of the line. The ─── symbol indicates the beginning of a statement. The ─── symbol indicates that the statement syntax is continued on the next line. The ─── symbol indicates that a statement is continued from the previous line. The ─── symbol indicates the end of a statement. Syntax fragments start with the |─── symbol and end with the ───| symbol. v Required items appear on the horizontal line (the main path).
required_item

|

v Optional items appear below the main path.
required_item optional_item

If an optional item appears above the main path, that item has no effect on the execution of the statement and is used only for readability.
optional_item required_item

v If you can choose from two or more items, they appear vertically, in a stack. If you must choose one of the items, one item of the stack appears on the main path.
required_item required_choice1 required_choice2

About DB2 UDB for iSeries SQL Reference

xv

If choosing one of the items is optional, the entire stack appears below the main path.
required_item optional_choice1 optional_choice2

If one of the items is the default, it will appear above the main path and the remaining choices will be shown below.
default_choice required_item optional_choice optional_choice

v An arrow returning to the left, above the main line, indicates an item that can be repeated.

required_item

repeatable_item

If the repeat arrow contains a comma, you must separate repeated items with a comma.
, required_item repeatable_item

A repeat arrow above a stack indicates that you can repeat the items in the stack. v Keywords appear in uppercase (for example, FROM). They must be spelled exactly as shown. Variables appear in all lowercase letters (for example, column-name). They represent user-supplied names or values. v If punctuation marks, parentheses, arithmetic operators, or other such symbols are shown, you must enter them as part of the syntax. | | | | v The syntax diagrams only contain the preferred or standard keywords. If non-standard synonyms are supported in addition to the standard keywords, they are described the Notes sections instead of the syntax diagrams. For maximum portability, only the preferred or standard keywords should be used.

xvi

DB2 UDB for iSeries SQL Reference V5R2

Conventions for Describing Mixed Data Values
When mixed data values are shown in the examples, the following conventions apply:

Convention

Meaning Represents the EBCDIC shift-out control character (X’ 0E ’) Represents the EBCDIC shift-in control character (X’ 0F ’)

sbcs-string dbcs-string

Represents a string of zero or more single-byte characters Represents a string of zero or more double-byte characters Represents a DBCS apostrophe (EBCDIC X’ 427D ’) Represents a DBCS G (EBCDIC X’ 42C7 ’)

| | | | | | | | | | | | | | | | | | | | | | | | | | |

SQL Accessibility
IBM is committed to providing interfaces and documentation that are easily accessible to the disabled community. For general information on IBM’s Accessibility support visit the Accessibility Center at http://www.ibm.com/able.

SQL accessibility support falls in two main categories. v iSeries Navigator is graphical user interface to iSeries and DB2 UDB. For information about the Accessibility features supported in Windows graphical user interfaces, see Accessibility in the Windows Help Index. v Online documentation, online help, and prompted SQL interfaces can be accessed by a Windows Reader program such as the IBM Home Page Reader. For information on the IBM Home Page Reader and other tools, visit the Accessibility Center .

The IBM Home Page Reader can be used to access all descriptive text in this book, all articles in the SQL Information Center, and all SQL messages. Due to the complex nature of SQL syntax diagrams, however, the reader will skip syntax diagrams. Two alternatives are provided for better ease of use: v Interactive SQL and Query Manager Interactive SQL and Query Manager are traditional file interfaces that provide prompting for SQL statements. These are part of the DB2 UDB Query Manager and SQL Development Kit. For more information about Interactive SQL and Query Manager, see the SQL Programming Concepts and Query Manager Use books. v SQL Assist SQL Assist is a graphical user interface that provides a prompted interface to SQL statements. This is part of iSeries Navigator. For more information, see the iSeries Navigator online help and the Information Center.

About DB2 UDB for iSeries SQL Reference

xvii

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

What’s new for V5R2 in the SQL Reference book
The major new features covered in this book include: v ROWID data type and ROWID scalar function v IDENTITY column attribute v CREATE TABLE AS (subselect) v DECLARE GLOBAL TEMPORARY tables v User-defined Table Functions v COMMIT ON RETURN procedures v UNION in views v Scalar subselect enhancements v READ ONLY and READ WRITE in SET TRANSACTION v ITERATE and nested Compound statements in SQL procedures, SQL functions, and SQL triggers v Fullselect in derived tables and common table expressions v Parameter markers in labeled durations v Savepoints v SET SCHEMA and SET SQLID v HOLD LOCATOR v ORDER BY expression not required in the select-list v ORDER BY and FETCH FIRST n ROWS ONLY in derived tables and common table expressions v Length of SQL statements increased to 64K v Length of delimited column name identifiers increased v SUBSTRING enhancements v VARCHAR concatenation enhancement v Debug of original source statements in SQL procedures, SQL functions, and SQL triggers v Multiple relational databases on iSeries v Standard and ODBC and JDBC catalog views v C derived variables

xviii

DB2 UDB for iSeries SQL Reference V5R2

Chapter 1. Concepts
DB2 UDB for &is; SQL Reference describes the following concepts: v “Relational Database” v “Structured Query Language” on page 3 v “Schemas” on page 5 v “Tables” on page 5 v “Keys” on page 6 v “Primary Keys and Unique Keys” on page 6 v “Referential Integrity” on page 7 v v v v v v v v “Check Constraints” on page 9 “Triggers” on page 9 “Indexes” on page 11 “Views” on page 12 “Aliases” on page 13 “Packages and Access Plans” on page 13 “Procedures” on page 14 “Catalog” on page 15

v “Application Processes, Concurrency, and Recovery” on page 15 v “Threads” on page 20 v “Isolation Level” on page 21 v v v v v “Distributed Relational Database” on page 25 “Character Conversion” on page 32 “Sort Sequence” on page 35 “Authorization, Privileges and Object Ownership” on page 36 “Storage Structures” on page 38

Relational Database
| | | | | | | | | | | | | | A relational database is a database that can be perceived as a set of tables and can be manipulated in accordance with the relational model of data. The relational database contains a set of objects used to store, access, and manage data. The set of objects includes tables, views, indexes, aliases, distinct types, functions, procedures and packages. There are three types of relational databases a user can access from an iSeries system. system relational database There is one default relational database on any iSeries system. The system relational database is always local to that iSeries system. It consists of all the database objects that exist on disk attached to the iSeries system that are not stored on independent auxiliary storage pools. For more information on independent auxiliary storage pools, see the System Management category of the iSeries Information Center.

© Copyright IBM Corp. 1998, 2002

1

see the System Management category of the iSeries Information Center. The name of the user relational database is. operations on such an object may fail if the other relational database is not available. v The parent table and dependent table in a referential constraint must both exist in the same relational database. views. Independent auxiliary storage pools can be varied off on one iSeries system and then varied on to another iSeries system. a different name can be assigned through the use of the ADDRDBDIRE (Add RDB Directory Entry) command or iSeries Navigator. the same as the iSeries system name. v The parent table and dependent table in a referential constraint must both exist in the same relational database. For example. Additionally. A user relational database is local to an iSeries system while the independent auxiliary storage pool is varied on. remote relational database Relational databases on other iSeries and non-iSeries systems can be 2 DB2 UDB for iSeries SQL Reference V5R2 . v A trigger or constraint must be created into a schema that exists in the same relational database as its base table. a different name can be assigned through the use of the ADDRDBDIRE (Add RDB Directory Entry) command or iSeries Navigator.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The name of the system relational database is. certain dependencies between the objects in the system relational database and the user relational database are not allowed: v A view must be created into a schema that exists in the same relational database as its referenced tables. if a user relational database is varied off and then varied on to another system. user relational database The user may create additional relational databases on an iSeries system by configuring independent auxiliary storage pools on the system. Each primary independent auxiliary storage pool is a relational database. by default. It consists of all the database objects that exist on the independent auxiliary storage pool disks. Although the objects in the system relational database are logically included in a user relational database. or functions. Other dependencies between the objects in the system relational database and the user relational database are allowed. the same as the independent auxiliary storage pool name. For example. Thus. v An index must be created into a schema that exists in the same relational database as its referenced table. v A table must be created into a schema that exists in the same relational database as any referenced distinct types. a user relational databases may be local to a given iSeries system at one point in time and remote at a different point in time. a procedure in a schema in a user relational database may reference objects in the system relational database. all database objects in the system relational database of the iSeries system to which the independent auxiliary storage pool is connected are logically included in a user relational database. Hence. the name of any schema created in a user relational database must not already exist in that user relational database or in the associated system relational database. However. For more information on independent auxiliary storage pools. However. However. by default.

The source form of the statement is a character string that is passed to the database manager by the program using the static SQL statement PREPARE or EXECUTE IMMEDIATE. The preparation of an SQL application program includes precompilation. SQL statements embedded in a REXX application are dynamic SQL statements. Dynamic SQL A dynamic SQL statement is prepared during the execution of an SQL application. Chapter 1. The result of preparation is the executable or operational form of the statement. the preparation of its static SQL statements.| | | accessed remotely. The precompiler checks the syntax of the SQL statements. These relational databases must be registered through the use of the ADDRDBDIRE (Add RDB Directory Entry) command or iSeries Navigator. One of the functions of the database manager is to transform the specification of a result table into a sequence of internal operations that optimize data retrieval. The statement is prepared before the program is executed and the operational form of the statement persists beyond the execution of the program. The database manager is the name used generically to identify the iSeries Licensed Internal Code and the DB2 UDB for iSeries portion of the code that manages the relational database. and data is retrieved by specifying a result table that can be derived from one or more base tables. and generates host language statements to call the database manager. and compilation of the changed source program. This transformation occurs when the SQL statement is prepared. A source program containing static SQL statements must be processed by an SQL precompiler before it is compiled. The operational form of the statement persists until the last SQL program leaves the call stack. SQL statements submitted to the interactive SQL facility are also dynamic SQL statements. Concepts 3 . relationships are represented by values in tables. SQL statements are executed by a database manager. In accordance with the relational model of data. the database is perceived as a set of tables. Structured Query Language Structured Query Language (SQL) is a standardized language for defining and manipulating data in a relational database. The method of preparing an SQL statement and the persistence of its operational form distinguish static SQL from dynamic SQL. This transformation is also known as binding. turns them into host language comments. All executable SQL statements must be prepared before they can be executed. Static SQL The source form of a static SQL statement is embedded within an application program written in a host language such as COBOL.

described. For more information about the interactive facilities for SQL. Both can be used to create Java applications and applets that access DB2. Unlike dynamic SQL. every interactive SQL facility is an SQL application program that reads statements from a terminal. see the SQL Programming Concepts and Query Manager Use books. SQL statements prepared into a package by this API persist until the package or statement is explicitly dropped. see the OS/400 APIs information in the Programming category of the iSeries Information Center. applications use procedure calls at execution time to connect to databases. statements can be prepared. and displays the results to the user. For a complete description of all the available functions. available from Microsoft or other vendors. Such SQL statements are said to be issued interactively. This reduces the need to write application server specific catalog queries. The QSQPRCED API provides users with extended dynamic SQL capability. to issue SQL statements. enabling access to ODBC data sources. Unlike using embedded SQL. SQL Call Level Interface (CLI) and Open Database Connectivity (ODBC) The DB2 Call Level Interface is an application programming interface in which functions are provided to application programs to process dynamic SQL statements. The DB2 CLI interface provides many features not available in embedded SQL. CLI programs can also be compiled using an Open Database Connectivity (ODBC) Software Developer’s Kit. see SQL Call Level Interfaces (ODBC) book. Like dynamic SQL. Java Database Connectivity (JDBC) and Embedded SQL for Java (SQLJ) Programs DB2 UDB for iSeries implements two standards-based Java programming APIs: Java Database Connectivity (JDBC) and embedded SQL for Java (SQLJ). and their syntax. and executed using this API. the STRQM command. Essentially. prepares and executes them dynamically. no precompilation is required.Extended Dynamic SQL An extended dynamic SQL statement is neither fully static nor fully dynamic. v Stored procedures called from application programs written using CLI can return result sets to those programs. For example: v CLI provides function calls which support a consistent way to query and retrieve database system catalog information across the DB2 family of database management systems. Through the interface. or the SQL Script support of iSeries Navigator. The interactive facilities for DB2 UDB for iSeries are invoked by the STRSQL command. 4 DB2 UDB for iSeries SQL Reference V5R2 . Interactive SQL An interactive SQL facility is associated with every database manager. Applications developed using this interface may be executed on a variety of databases without being compiled against each of the databases. DB2 CLI allows users of any of the ILE languages to access SQL functions directly through procedure calls to a service program provided by DB2 UDB for iSeries. and to get returned data and status information. For more information.

For example. and packages. Schemas A schema is a collection of named objects. An SQLJ source file has to be translated with the SQLJ translator before the resulting Java source code can be compiled. A column is a set of values of the same type. see IBM Toolbox for Java. You can access iSeries databases through two JDBC drivers: IBM Developer Kit for Java driver or IBM Toolbox for Java JDBC driver. Concepts 5 . SQLJ applications use JDBC as a foundation for such tasks as connecting to databases and handling SQL errors. For specific information about the IBM Toolbox for Java JDBC driver.JDBC calls are translated to calls to DB2 CLI through Java native methods. Static SQL cannot be used by JDBC. the catalog views and journal created by using the CREATE SCHEMA statement will not be created with CRTLIB. The schema to which it is assigned is determined by the name of the object if specifically qualified with a schema name or by the default schema name if not qualified.1 A schema name is used as the high-order part of a two-part object name. procedures. refer to the Developer Kit for Java book. Some of the objects that a schema may contain include tables. A row is a sequence of values such that the nth value is a value of the nth column of the table. Tables are made up of columns and rows. A schema is also an object in the relational database. For more information about JDBC and SQLJ applications. 1. A result table is a set of rows that the database manager selects or generates from one or more base tables. It is explicitly created using the CREATE SCHEMA statement. A schema can also be created using the CRTLIB CL command. Schemas provide a logical classification of objects in a relational database. A schema is also called a collection or library. views. Chapter 1. however. At the intersection of every column and row is a specific data item called a value. A base table is created with the CREATE TABLE statement and is used to hold persistent user data. functions. aliases. a user creates a schema called C: CREATE SCHEMA C The user can then issue the following statement to create a table called X in schema C: CREATE TABLE C. types.X (COL1 INT) Tables Tables are logical structures maintained by the database manager. There is no inherent order of the rows within a table. An object that is contained in a schema is assigned to the schema when the object is created. but can also contain embedded static SQL statements in the SQLJ source files.

For more information about distributed tables. A partitioning key is a set of one or more columns in a distributed table that are used to determine on which system a row belongs. A parent key is either a primary key or a UNIQUE key. Alternatively. Either name is acceptable wherever column-name is specified in SQL statements. a rule such as “the value of the foreign key must be equal to the value of the primary key” means that each component of the value of the foreign key must be equal to the corresponding component of the value of the primary key. A CHECK constraint will be added implicitly to enforce the rule that the NULL value is not allowed in the columns that make up the primary key. For more information see “CREATE TABLE” on page 526. A key composed of more than one column is called a composite key. Primary Keys and Unique Keys A unique constraint is the rule that the values of a key are valid only if they are unique. the default parent key is its primary key. A nodegroup is an object that provides a logical grouping of a set of two or more systems. A composite key is an ordered set of columns of the same table. The system name is the name used by OS/400. 6 DB2 UDB for iSeries SQL Reference V5R2 . This table is dropped implicitly when the application disconnects from the database. or a referential constraint.A base table has a name and may have a different system name. Either name is acceptable wherever a table-name is specified in SQL statements. The same column can be part of more than one key. A table cannot have more than one primary key. A key that is constrained to have unique values is called a unique key and can be defined by using the CREATE UNIQUE INDEX statement. | | | | A declared temporary table is created with a DECLARE GLOBAL TEMPORARY TABLE statement and is used to hold temporary data on behalf of a single application. A column of a base table has a name and may have a different system column name. The ordering of the columns is not constrained by their ordering within the table. A unique index on a primary key is called a primary index. A table can have an arbitrary number of UNIQUE keys. Thus. unique keys can be defined: v As a primary key using a CREATE TABLE or ALTER TABLE statement. When a table is defined as a parent in a referential constraint. see the DB2 Multisystem book. The resulting unique index is used by the database manager to enforce the uniqueness of the key during the execution of INSERT and UPDATE statements. The system column name is the name used by OS/400. unique constraint. Keys A key is one or more columns that are identified as such in the description of an index. A unique key that is referenced by the foreign key of a referential constraint is called the parent key. v Using the UNIQUE clause of the CREATE TABLE or ALTER TABLE statement. The term value when used with respect to a composite key denotes a composite value. For more information see “CREATE TABLE” on page 526. A distributed table is a table whose data is partitioned across a nodegroup.

Referential constraints with a delete or update rule of RESTRICT are always enforced before any other referential constraints. The table containing the parent key is called the parent table of the referential constraint. Other referential constraints are enforced in an order independent manner. A row that has at least one dependent row. A table can be defined as a dependent in an arbitrary number of referential constraints. Chapter 1. v A row that was updated by a referential constraint cannot also be marked for deletion by another referential constraint with a delete rule of CASCADE. Referential constraints are optional and can be defined in CREATE TABLE statements and ALTER TABLE statements. v A row can only be updated by one referential constraint with a delete rule of SET NULL or SET DEFAULT. A set of referential constraints such that each table in the set is a descendent of itself. A row that has at least one parent row. the order does not affect the result of the operation. or v Some component of the foreign key is null. A table can be defined as a parent in an arbitrary number of referential constraints. and the table containing the foreign key is said to be a dependent of that table. That is. UPDATE. Referential constraints are enforced by the database manager during the execution of INSERT. A referential constraint is the rule that the values of the foreign key are valid only if: v They appear as values of a parent key. The enforcement is effectively performed at the completion of the statement except for delete and update rules of RESTRICT which are enforced as rows are processed. and DELETE statements. A table that is a dependent in at least one referential constraint. Concepts Dependent table Descendent table Dependent row Descendent row Referential cycle 7 . Within an SQL statement: v A row can be marked for deletion by any number of referential constraints with a delete rule of CASCADE. A table that is a parent in at least one referential constraint. A row is a descendent of row p if it is a dependent of p or a descendent of a dependent of p. A table is a descendent of table T if it is a dependent of T or a descendent of a dependent of T. The rules of referential integrity involve the following concepts and terminology: Parent key Parent row Parent table A primary key or unique key of a referential constraint.Referential Integrity Referential integrity is the state of a database in which all values of all foreign keys are valid. A foreign key is a key that is part of the definition of a referential constraint. A dependent table can also be a parent table.

and rows of D may be updated during the operation. The value of a composite foreign key is null if any component of the value is null. The constraint is called a self-referencing constraint. RESTRICT. and let p denote a parent row that is the object of a delete or propagated delete operation. D is involved in the operation and rows of D may be deleted during the operation. each column of the foreign key of each dependent of p in D is set to its default value Each referential constraint in which a table is a parent has its own delete rule. v If D is a dependent of P and the delete rule is SET DEFAULT. Let P denote the parent table. 8 DB2 UDB for iSeries SQL Reference V5R2 . The deletion of a row from parent table P involves other tables and may affect rows of these tables: v If table D is a dependent of P and the delete rule is RESTRICT or NO ACTION. SET NULL or SET DEFAULT. Thus. D is involved in the operation but is not affected by the operation. The delete rule of a referential constraint applies when a row of the parent table is deleted. let D denote the dependent table. A table that is a parent and a dependent in the same referential constraint. D is involved in the operation. v If D is a dependent of P and the delete rule is CASCADE. The value of a composite foreign key is null if any component of the value is null. v If D is a dependent of P and the delete rule is SET NULL. a row cannot be deleted if it has dependents in a referential constraint with a delete rule of RESTRICT or NO ACTION. The update rule of a referential constraint is that a nonnull update value of a foreign key must match some value of the parent key of the parent table. If the delete rule is: v RESTRICT or NO ACTION. and all applicable delete rules are used to determine the result of a delete operation. SET NULL can be specified only if some column of the foreign key allows null values. each nullable column of the foreign key of each dependent of p in D is set to null v SET DEFAULT. an error is returned and no rows are deleted v CASCADE. The choices are NO ACTION and RESTRICT. The update rule applies when a row of the parent or dependent table is updated. the rule applies when a row of the parent table is the object of a delete or propagated delete operation (defined below) and that row has dependents in the dependent table of the referential constraint. D is involved in the operation. The insert rule of a referential constraint is that a nonnull insert value of the foreign key must match some value of the parent key of the parent table. or if the deletion cascades to any of its descendants that are dependents in a referential constraint with the delete rule of RESTRICT or NO ACTION. the delete operation is propagated to the dependents of p in D v SET NULL. The update rule of a referential constraint is specified when the referential constraint is defined. and rows of D may be updated during the operation. CASCADE. The delete rule of a referential constraint is specified when the referential constraint is defined. More precisely. The choices are NO ACTION.Self-referencing row Self-referencing table A row that is a parent of itself.

Concepts 9 . or invoke functions that perform operations both inside and outside of DB2. Check constraints are optional and can be defined using the SQL statements CREATE TABLE and ALTER TABLE. SET CONNECTION. They are enforced by the database manager when: v A row is inserted into the table. insert. A few operations are not allowed. a trigger can substitute a valid value and send a notice to an administrator about the invalid update. Any table that may be involved in a delete operation on P is said to be delete-connected to P. When such an SQL operation is executed. Triggers are a useful mechanism to define and enforce transitional business rules that involve different states of the data (for example. the trigger is said to be activated. and RELEASE statements For a complete list of restrictions. Chapter 1. One of the restrictions is that a column name in a check constraint on a table T must identify a column of T. see the Database Programming book. or update operation occurs on a specified table. in turn. salary cannot be increased by more than 10 percent). to the dependents of D. Check Constraints A check constraint is a rule that specifies the values allowed in one or more columns of every row of a table. DISCONNECT. A check constraint is enforced by applying its search condition to each row that is inserted or updated.2 The set of actions can include almost any operation allowed on the system. The ADDPFTRG CL command also defines a trigger that is activated on any read operation. An error is returned if the result of the search condition is FALSE for any row. the delete operation on P is said to be propagated to D. instead of preventing an update to a column if the new value exceeds a certain amount. Triggers are more powerful than constraints because they can also be used to cause updates to other tables. a table is delete-connected to table P if it is a dependent of P or a dependent of a table to which delete operations from P cascade. For example. such as: v Commit or rollback (if the same commitment definition is used for the trigger actions and the triggering event) v CONNECT. Such a limit requires comparing the value of a salary before 2. If D is also a parent table. The definition of a check constraint is a restricted form of a search condition. Thus. Triggers can be used along with referential constraints and check constraints to enforce data integrity rules. automatically generate or transform values for inserted or updated rows. A table can have an arbitrary number of check constraints. the actions described in this list apply.If rows of D are deleted. v A row of the table is updated. Triggers A trigger defines a set of actions that are executed automatically whenever a delete.

Separate transition tables can be defined for old and new values. inserted or updated. the most recently created trigger will be the last trigger activated. The triggered actions may also cause 10 DB2 UDB for iSeries SQL Reference V5R2 . The order in which the triggers are activated is the same as the order in which they were created. With the logic in the database. Transition variables use the names of the columns in the subject table qualified by a specified name that identifies whether the reference is to the old value (prior to the update) or the new value (after the update). Thus. This is supported through the use of transition variables. Transition tables also use the names of the columns of the subject table but have a name specified that allows the complete set of affected rows to be treated as a table. DB2 checks the validity of the changes that any application makes to the salary column. Triggers are optional and are defined using the CREATE TRIGGER statement or the ADDPFTRG (Add Physical File Trigger) CL command. The SQL statements are only executed if the search condition evaluates to true. Transition tables can only be used in after triggers. v The trigger activation time defines whether the trigger should be activated before or after the trigger event is performed on the subject table. or activation time. see the CREATE TRIGGER statement. The new value can also be changed using the SET transition-variable statement in before update or insert triggers. This is the result of the activation of one trigger that executes SQL statements that cause the activation of other triggers or even the same trigger again. For more information about creating triggers. Multiple triggers can be specified for a combination of table. v The subject table defines the table for which the trigger is defined. event. see the “CREATE TRIGGER” on page 557 statement or the SQL Programming Concepts and the Database Programming books. The activation of a trigger may cause trigger cascading. insert. In addition. The statement that causes a trigger to be activated will include a set of affected rows. The trigger granularity defines whether the actions of the trigger will be performed once for the statement or once for each of the rows in the set of affected rows.and after an increase. consider using referential and check constraints. The triggered action may refer to the values in the set of affected rows. the previously mentioned limit on increases to the salary column of a table. There are a number of criteria that are defined when creating a trigger which are used to determine when a trigger should be activated. These are the rows of the subject table that are being deleted. Triggers also move the application logic that is required to enforce business rules into the database. Triggers are dropped using the DROP TRIGGER statement or the RMVPFTRG (Remove Physical File Trigger) CL command. For more information about triggers in general. The operation could be delete. The trigger action consists of an optional search condition and a set of SQL statements that are executed whenever the trigger is activated. For rules that do not involve more than one state of the data. or update. the application programs do not need to be changed when the logic changes. which can result in faster application development and easier maintenance. for example. v The trigger event defines a specific SQL operation that modifies the subject table. Another means of referring to the values in the set of affected rows is using transition tables.

Indexes An index is a set of pointers to rows of a base table. All triggers created by using the CREATE TRIGGER statement implicitly have the ALWREPCHG(*YES) attribute. This also includes any rows inserted or updated by a trigger or referential constraint caused by the same SQL statement. the database manager builds this structure and maintains it automatically. which may result in the activation of additional triggers. Either name is acceptable wherever an index-name is specified in SQL statements. insert or update statement. when the isolation level is anything other than NC (No Commit) and the trigger actions are performed using the same commitment definition as the trigger event: v The database manager ensures that the operation and the triggers executed as a result of that operation either all complete or are backed out. If the isolation level is anything other than NC (No Commit) and the trigger actions are performed using the same commitment definition as the trigger event. – A row can be updated by a trigger only if that row has not already been inserted or updated by that same SQL statement. this also includes any inserts or updates by a trigger or referential constraint caused by the same SQL statement. then within an SQL statement: – A row can be deleted by a trigger only if that row has not been inserted or updated by that same SQL statement. An index has a name and may have a different system name. v If ALWREPCHG(*YES) is specified when the trigger is defined. a significant chain of triggers may be activated causing significant change to the database as a result of a single delete. Operations that occurred prior to the triggering operation are not affected. v If ALWREPCHG(*NO) is specified when the trigger is defined. With trigger cascading. The system name is the name used by OS/400. Each index is based on the values of data in one or more table columns. v The database manager effectively checks all constraints (except for a constraint with a RESTRICT delete rule) after the operation and the associated triggers have been executed. When you request an index. The actions performed in the trigger are considered to be part of the operation that caused the trigger to be executed.updates as a result of the original modification. then within an SQL statement: – The trigger is allowed to update or delete any row that was inserted or already updated by that same SQL statement. If the isolation level is anything other than NC (No Commit) and the trigger actions are performed using the same commitment definition as the trigger event. Thus. For more information see “CREATE INDEX” on page 497. Chapter 1. An index is an object that is separate from the data in the table. Concepts 11 . this also includes any inserts or updates by a trigger or referential constraint caused by the same SQL statement. A trigger has an attribute that specifies whether it is allowed to delete or update a row that has already been inserted or updated within the SQL statement that caused the trigger to be executed.

update. For retrieval. Because of their compact size and relative simplicity. (See “CREATE VIEW” on page 570 for more information. a view can be thought of as having columns and rows just like a base table. 12 DB2 UDB for iSeries SQL Reference V5R2 . In most cases. 2. When the column of a view is directly derived from a column of a base table. The system name is the name used by OS/400. A view has a name and may have a different system name. all views can be used just like base tables. v Encoded vector index Encoded vector indexes do not provide a specific order to the rows of a table. the trigger is fired when an update is performed on the view. if a view includes a foreign key of its base table. For example.The database manager uses two types of indexes: v Binary radix tree index Binary radix tree indexes provide a specific order to the rows of a table. that column inherits any constraints that apply to the column of the base table. The specification is a SELECT statement that is effectively executed whenever the view is referenced in an SQL statement. INSERT and UPDATE operations using that view are subject to the same referential constraints as the base table. if the base table of a view has an update trigger. access to data is faster than without an index. For more information about accelerating your queries with encoded vector indexes . – Ensure uniqueness. The database manager uses them to: – Improve performance. A view also inherits any triggers that apply to its base table. go to the DB2 UDB for iSeries webpages. The elements of the array can be 1. or delete operation depends on its definition as explained in the description of CREATE VIEW. Views A view provides an alternative way of looking at the data in one or more tables. The database manager only uses these indexes to improve performance. However. You create encoded vector access paths by using the SQL CREATE INDEX statement. an index created for a table on which a view is based may improve the performance of operations on the view. or 4 bytes in length. A view is a named specification of a result table. For example. A table with a unique index cannot have rows with identical keys. encoded vector access paths provide for faster scans that can be more easily processed in parallel. Whether a view can be used in an insert. DELETE operations using that view are subject to the same rules as DELETE operations on the base table. For more information see “CREATE VIEW” on page 570. if the base table of a view is a parent table. Thus.) An index cannot be created for a view. Either name is acceptable wherever a view-name is specified in SQL statements. depending on the number of distinct values that must be represented. An encoded vector access path works with the help of encoded vector indexes and provides access to a database file by assigning codes to distinct key values and then representing these values in an array. Likewise.

This means that any packages. You can use an alias to reference a table or view in those cases where an existing table or view can be referenced. For example. An invalidated access plan will be implicitly rebuilt the next time its associated SQL statement is executed. if an index is dropped that is used in an access plan for a SELECT INTO statement. the next time that SELECT INTO statement is executed. The system column name is the name used by OS/400. the access plan will be rebuilt. For more information see “CREATE ALIAS” on page 426. Either name is acceptable wherever column-name is specified in SQL statements. JDBC and SQLJ interfaces. For example. Either name is acceptable wherever an alias-name is specified in SQL statements. and programs or service programs containing control structures referencing the dropped object are invalidated. In this book. The QSQPRCED API is used by iSeries Access for Windows to create packages for caching SQL statements executed via ODBC. 3. still require the appropriate authorization for the current statement. Concepts 13 . Packages created by the QSQPRCED API can only be used by the QSQPRCED API. triggers. procedures. the description of the DROP statement says that dropping an object also invalidates any access plans that reference the object (see “DROP” on page 630). Packages and Access Plans For distributed programs. Access to the tables and views that are referred to by the alias. The control structures can be thought of as the bound or operational form of SQL statements. a package is an object that contains control structures used to execute SQL statements. The system name is the name used by OS/400. however. and have a comment or label associated with it. An alias has a name and may have a different system name. see “CREATE VIEW” on page 570. procedures. the term access plan is used in general for packages. For non-distributed SQL programs. dropped. Aliases An alias is an alternate name for a table or view. All control structures in a package are derived from the SQL statements embedded in a single source program. see the OS/400 APIs information in the Programming category of the iSeries Information Center.A column of a view has a name and may have a different system column name. For more information. triggers. You cannot use an alias in all contexts. the control structures used to execute SQL statements are stored in the associated space of the non-distributed SQL program. an alias that refers to an individual member of a database file cannot be used in data definition language (DDL) statements. No authority is necessary to use an alias. functions. and programs or service programs that contain control structures used to execute SQL statements. functions. For example.3 Like tables and views. an alias may be created. Chapter 1. A package can also be created by the QSQPRCED API. For more information. Packages are produced during program preparation. They cannot be used at a server through DRDA protocols.

Application Without Remote Procedure 14 DB2 UDB for iSeries SQL Reference V5R2 . In fact. It will then wait for a reply that indicates whether the statement executed successfully or not and optionally returns results. When the second and each subsequent SQL statement is executed. The operations can contain host language statements and SQL statements. If the same SQL statements are stored in a procedure at a server. a common piece of code need only be written and maintained once and can be called from several programs. Procedures in SQL provide the same benefits as procedures in a host language. the application requester will send a single request to the current server to call the procedure. Figure 1. That is. SQL can also call a procedure that exists on a remote system. a CALL statement can be executed that references the remote procedure. Both external procedures and SQL procedures are supported in DB2 UDB for iSeries. the major benefit of procedures in SQL is that they can be used to enhance the performance characteristics of distributed applications. When the first SQL statement is executed. It will then wait for a single reply that indicates whether the procedure executed successfully or not and optionally returns results. The following two figures illustrate the way stored procedures can be used in a distributed application to eliminate some of the remote requests. Procedures are classified as either SQL procedures or external procedures. However.Procedures A procedure (often called a stored procedure) is a programming construct that can be called to perform a set of operations. the application requester will send a request to a server to perform the operation. SQL procedures contain only SQL statements. a source file member) which may or may not contain SQL statements. Both host languages and SQL can call procedures that exist on the local system. When the CALL statement is executed. Assume several SQL statements must be executed at a remote system. the application requester will send another request and wait for another reply. External procedures reference a host language program (or in the case of REXX.

The database manager ensures that the catalog contains accurate descriptions of the objects in the database at all times. and constraints on the system. If you have authorization. Tables and views in the catalog are like any other database tables and views. For more information about catalog tables and views. packages. packages. you can use SQL statements to look at data in the catalog views in the same way that you retrieve data from any other table in the system. The catalog tables contain information about tables. Concepts 15 . Each activation group involves the execution of one or Chapter 1. An application process is made up of one or more activation groups. indexes. views. indexes. These tables are collectively known as the catalog. views. and constraints on the system. Application With Remote Procedure Catalog The database manager maintains a set of tables containing information about the data in the database.Figure 2. The views provide more consistency with the catalog views of other IBM SQL products and with the catalog views of the ANSI and ISO standard (called Information Schema in the standard).” on page 881. indexes. The catalog views in QSYS2 contain information about all tables. packages. and Recovery | | | | | All SQL programs execute as part of an application process. parameters. Concurrency. The database manager provides views over the catalog tables. an application process is called a job. Application Processes. procedures. In OS/400. Additionally. views. “DB2 UDB for iSeries Catalog Views. an SQL schema will contain a set of these views that only contains information about tables. see Appendix F. In the case of ODBC and JDBC and DRDA. the application process ends when the connection ends even though the job they are using does not end and may be reused. and constraints in the schema.

Activation Groups without Job Commitment Definition Figure 4 on page 17 shows an application process. A commitment definition can be explicitly started through the Start Commitment Control (STRCMTCTL) command. An application process that uses commitment control can run with one or more commitment definitions. Activation group C does not run with any commitment control and does not have a commitment definition. a commitment definition is implicitly started when the first SQL statement is executed under an isolation level different than COMMIT(*NONE). the activation groups in that application process. an activation group that uses commitment control is associated with only one of the commitment definitions. For more information about activation groups. Figure 3 shows the relationship of an application process. If not already started. All programs except those created by ILE compilers run under the default activation group. Programs run under a non-default activation group or the default activation group. At any given time. and the commitment definitions. the activation groups in that application process. see the book ILE Concepts . Some of the activation groups are running with the job commitment definition. Activation groups A and B are running under the job commitment definition. More than one activation group can share a job commitment definition. and the commitment definitions. Figure 3. Activation groups A and B run with commitment control scoped to the activation group.| | | more programs. Any commit or rollback operation in 16 DB2 UDB for iSeries SQL Reference V5R2 . A commitment definition provides a means to scope commitment control at an activation group level or at a job level. These activation groups have their own commitment definitions.

activation group A or B affects both because the commitment control is scoped to the same commitment definition. Locking prevents such things as two application processes updating the same row of data simultaneously. Object locks and other resources are allocated to an activation group. Commit. Object locks associated with cursors that remain open after commit are not released. | | | | | | | | | | | | | | | | | Locking. Activation group C in this example has a separate commitment definition. When an activation group other than the default activation group ends normally. This operation is called commit. Figure 4. the database manager releases all locks obtained by the activation group. The database manager acquires locks to keep the uncommitted changes of one activation group undetected by activation groups that use a different commitment definition. Locking is used to maintain data integrity under such conditions. The recovery functions of the database manager provide a means of backing out of uncommitted changes made in a commitment definition. and Rollback Application processes and activation groups that use different commitment definitions can request access to the same data at the same time. A user can also explicitly request that most locks be released sooner. see the Commitment control topic. The database manager may implicitly back out uncommitted changes under the following situations: Chapter 1. Commit and rollback operations performed in this activation group only affect operations within C. Concepts 17 . Activation Groups with Job Commitment Definition For more information about commitment definitions. Row locks are allocated to a commitment definition.

v A DELETE or UPDATE statement associated with a different commitment definition from locking the same row. Following the subtraction step. A unit of work is ended by a commit operation. all changes performed under the commitment definition associated with remote connection are backed out. Once changes are committed. The start and end of a unit of work defines points of consistency within an activation group. a banking transaction might involve the transfer of funds from one account to another. all changes performed under the commitment definition associated with that activation group are backed out. Such a transaction would require that these funds be subtracted from the first account. other activation groups using different commitment definitions running under isolation levels COMMIT(*CS). all changes performed under the commitment definition associated with the default activation group are backed out. and added to the second. and COMMIT(*RR) cannot perceive the changes. A lock explicitly acquired by a LOCK TABLE statement can be held past the end of a unit of work if COMMIT HOLD or ROLLBACK HOLD is used to end the unit of work. and the changes can no longer be backed out. Unit of Work A unit of work (also known as a logical unit of work or unit of recovery) is a recoverable sequence of operations. the data is inconsistent. a rollback operation. A commit or rollback operation affects only the database changes made within the unit of work that the commit or rollback ends. all changes performed under the commitment definition associated with remote connection are backed out. For example. or when the previous unit of work is ended by a commit or rollback operation. This lock prevents: v Other cursors associated with a different commitment definition from locking the same row. When both steps are complete. the commit operation can be used to end the unit of work. or the ending of the activation group. A unit of work is started either when the commitment definition is started. other activation groups running in different commitment definitions can access them. v When using Distributed Unit of Work and a failure occurs while attempting to commit changes on a remote system. Each commitment definition involves the execution of one of more units of work. A user can also explicitly request that their database changes be backed out. The changes can be backed out until they are committed. A cursor can implicitly lock the row at which the cursor is positioned. When an activation group other than the default activation group ends abnormally. v When using Distributed Unit of Work and a request to back out is received from a remote system because of a failure at that site. While changes remain uncommitted. This operation is called rollback. 18 DB2 UDB for iSeries SQL Reference V5R2 . Only after the funds are added to the second account is consistency established again. After the commit operation. At any given time.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v When the application process ends. Locks acquired by the database manager on behalf of an activation group are held until the unit of work is ended. COMMIT(*RS). a commitment definition has a single unit of work.

Unit of Work with a Rollback Statement Chapter 1. If such a rollback operation is successfully executed. as shown in the diagram below: Figure 6. the database manager backs out uncommitted changes to restore the data consistency that it assumes existed when the unit of work was initiated.| | | the changes are available to activation groups that use different commitment definitions. Rolling back all changes The SQL ROLLBACK statement without the TO SAVEPOINT clause causes a full rollback operation. Concepts 19 . the database manager undoes the work. Unit of Work with a Commit Statement | | | | | | | | | | Rolling Back Work The database manager can back out all changes made in a unit of work or only selected changes. Only backing out all changes results in a point of consistency. Figure 5. That is.

Furthermore. 20 DB2 UDB for iSeries SQL Reference V5R2 . the thread would not want to share commitment definitions or lock with the other threads. each thread can operate on the same unit of work so that when one thread commits or rolls back.| | | | | | | | | | | | | Rolling back selected changes using savepoints A savepoint represents the state of data at some particular time during a unit of work. and the RELEASE SAVEPOINT statement to delete a savepoint. SQL server mode can be activated for a job by using one of the following mechanisms before data access occurs in the application: – Use the ODBC API. Figure 7. part of a reservation transaction might involve booking an airline flight and then a hotel room. This type of processing is useful if multiple threads are cooperating to perform a single task in parallel. a thread shares the same commitment definitions and locks as the other threads in the job. and then as logic dictates. QWTCHGJB(). SQL programs can use the SQL SAVEPOINT statement to set savepoints. the application process might want to undo the flight reservation without undoing any database changes made in the transaction prior to making the flight reservation. it can commit or rollback all changes performed by all threads. v Make sure that the job is running in SQL server mode before issuing the first SQL statement. SQLSetEnvAttr() and set the SQL_ATTR_SERVER_MODE attribute to SQL_TRUE before doing any data access. In this case. – Use the Change Job API. an application process can also consist of one or more threads. the SQL ROLLBACK statement with the TO SAVEPOINT clause to undo changes to a specific savepoint or the last savepoint that was set. roll back only the changes that were made after a savepoint was set. An application process can set savepoints within a unit of work. Thus. By default. In other cases. If a flight gets reserved but a hotel room cannot be reserved. There are several ways to accomplish this type of processing: v Make sure the programs running in the thread use a separate activation group (be careful not to use ACTGRP(*NEW)). Unit of Work with a Rollback Statement and a Savepoint Statement Threads In OS/400. it is useful for a thread to perform changes independent from other threads in the job. a job can use SQL server mode in order to take more fine grain control of multiple database connections and transaction information. and set the ’Server mode for Structured Query Language’ key before doing any data access. For example. A typical multi-threaded job may require this control.

when activation group P executes an SQL statement. Thus. or select-statement. Chapter 1. see the SQL Call Level Interface (ODBC) book. Concepts 21 . v For ODBC/CLI and JDBC. SELECT INTO. the isolation level determines: v The degree to which rows retrieved by P and database changes made by P are available to other concurrently executing activation groups. all SQL statements are passed to an independent server job that will handle the requests. When SQL server mode is established. The isolation level can be explicitly specified on a DELETE. If the isolation level is not explicitly specified. UPDATE.– Use JAVA to access the database via JDBC. v The degree to which database changes made by concurrently executing activation groups can affect P. the isolation level used when the SQL statement is executed is the default isolation level. JDBC automatically uses server mode to preserve required semantics of JDBC. each connection represents a stand-alone connection to the database and can be committed and used as a separate entity. The following SQL support is not threadsafe: v Remote access through DRDA v ALTER TABLE v COMMENT v CREATE ALIAS v CREATE DISTINCT TYPE v CREATE FUNCTION v CREATE INDEX v CREATE PROCEDURE v CREATE SCHEMA v CREATE TABLE v CREATE TRIGGER v CREATE VIEW v DECLARE GLOBAL TEMPORARY TABLE v DROP v GRANT v LABEL v RENAME v REVOKE For more information. | Isolation Level The isolation level used during the execution of SQL statements determines the degree to which the activation group is isolated from concurrently executing activation groups. Server mode behavior for SQL behavior includes: v For embedded SQL. see Multithreaded applications in the Programming topic of the iSeries Information Center. For more information. each thread in a job implicitly gets one and only one connection to the database (and thus its own commitable transaction). INSERT.

locking occurs at the base-table row level across all products. and RUNSQLSTM commands to specify the default isolation level. However. The isolation level is in effect only for the execution of the statement containing the isolation-clause and has no effect on any pending changes in the current unit of work. v Use the isolation-clause on the SELECT. For all isolation levels except No Commit. DB2 UDB for iSeries supports five isolation levels. Concurrent activation groups using different commitment definitions that are running COMMIT(*UR) or COMMIT(*NC) are allowed to read the data. the isolation level returns to the value it had at the beginning of the unit of work. the database manager places exclusive locks on every row that is inserted. This ensures that any row changed during a unit of work is not changed by any other activation group that uses a different commitment definition until the unit of work is complete. For read-only WITH HOLD cursors. and DECLARE CURSOR statements to override the default isolation level for a specific statement or cursor. Exclusive Prevents concurrent activation groups using different commitment definitions from updating or deleting the data.DB2 UDB for iSeries provides several ways to specify the default isolation level: v Use the COMMIT parameter on the CRTSQLxxx. Depending on the type of lock. 4. or COMMIT(*RR) from reading the data. These isolation levels are supported by automatically locking the appropriate data. 22 DB2 UDB for iSeries SQL Reference V5R2 . v Use the SET OPTION statement to specify the default isolation level within the source of a module or program that contains embedded SQL. Each database manager supports at least two types of locks: Share Limits concurrent activation groups that use different commitment definitions to read-only operations on the data.4 – Any row changed (or a row that is currently locked with an UPDATE row lock) by another activation group using a different commitment definition cannot be read until it is committed. SELECT INTO. updated. v Use the SET TRANSACTION statement to override the default isolation level within a unit of work. An activation group is guaranteed at least the minimum requested lock level. Similarly. UPDATE. STRSQL. this limits or prevents access to the data by concurrent activation groups that use different commitment definitions. The following descriptions of isolation levels refer to locking data in row units. or deleted. the rows may have actually been read in a prior unit of work. these rules apply to when the rows were actually read. logically. a database manager can escalate a lock to a higher level. Individual implementations can lock data in larger physical units than base table rows. INSERT. DELETE. COMMIT(*CS). The isolation levels are: v Repeatable Read (RR) Level RR ensures: – Any row read during a unit of work is not changed by other activation groups that use different commitment definitions until the unit of work is complete. When the unit of work ends. Prevents concurrent activation groups using different commitment definitions that are running COMMIT(*RS). For WITH HOLD cursors.

RS does not completely isolate the activation group from the effects of concurrent activation groups that use a different commitment definition. Unlike RR and RS. subquery. In addition to any exclusive locks. Unlike RR. In the ANS and ISO standards. DB2 UDB for iSeries supports read stability through COMMIT(*ALL) or COMMIT(*RS). These additional rows are called phantom rows. a phantom row can occur in the following situation: 1. activation groups that issue the same query more than once might see additional rows. Repeatable Read is called Serializable. In addition to any exclusive locks. In the ANS and ISO standards. Activation group P1 reads the set of rows n that satisfy some search condition. 3. 4 – Any row changed (or a row that is currently locked with an UPDATE row lock) by another activation group using a different commitment definition cannot be read until it is committed. the rows that were read during a unit of work can be changed by other activation groups that use a different commitment definition. v Cursor Stability (CS) Like levels RR and RS. In the ANS and ISO standards. For example. level CS only ensures that the current row of every updateable cursor is not changed by other activation groups using different commitment definitions. Concepts 23 . or subselect used in an INSERT statement.| | | | In addition to any exclusive locks. v Read Stability (RS) Like level RR. level UR allows: – Any row read during the unit of work to be changed by other activation groups that run under a different commitment definition. an activation group running at level RR acquires at least share locks on all the rows it reads. Activation group P2 then INSERTs one or more rows that satisfy the search condition and COMMITs those INSERTs. the locking is performed so that the activation group is completely isolated from the effects of concurrent activation groups that use different commitment definitions. an activation group running at level CS may acquire a share lock for the current row of every cursor. P1 reads the set of rows again with the same search condition and obtains both the original rows and the rows inserted by P2. level RS ensures that: – Any row read during a unit of work is not changed by other activation groups that use different commitment definitions until the unit of work is complete. At level RS. Cursor Stability is called Read Committed. Furthermore. v Uncommitted Read (UR) For a SELECT INTO. DB2 UDB for iSeries supports cursor stability through COMMIT(*CS). Read Stability is called Repeatable Read. an activation group running at level RS acquires at least share locks on all the rows it reads. DB2 UDB for iSeries supports repeatable-read through COMMIT(*RR). Thus. a FETCH with a read-only cursor. 2. level CS ensures that any row that was changed (or a row that is currently locked with an UPDATE row lock) by another activation group using a different commitment definition cannot be read until it is committed. Repeatable-read isolation level is supported by locking the tables containing any rows that are read or updated. Chapter 1.

For RR. v No Commit (NC) For all operations. the rules of level CS apply. See phenomenon P2 (nonrepeatable read) below. “accessed rows” typically means rows selected. – Any changes are effectively committed at the end of each successful change operation and can be immediately accessed or changed by other application groups using different commitment definitions.) When a requested isolation level is not supported by a server. NC Can the application see uncommitted changes made by other application processes? Can the application update uncommitted changes made by other application processes? Can the re-execution of a statement be affected by other application processes? See phenomenon P3 (phantom) below. Uncommitted Read is called Read Uncommitted. Can “updated” rows be updated by other application processes? Can “updated” rows be read by other application processes that are running at an isolation level other than UR and NC? Can “updated” rows be read by other application processes that are running at the UR or NC isolation level? Can “accessed” rows be updated by other application processes? For RS. In the ANS and ISO standards. see the discussion and table in the commitment control topic of the SQL Programming Concepts book. and LOCK TABLE locks are not released. For other operations. connections in the release-pending state are ended. Comparison of Isolation Levels The following table summarizes information about isolation levels.– Any row changed (or a row that is currently locked with an UPDATE row lock) by another activation group running under a different commitment definition to be read even if the change has not been committed. Yes UR Yes CS No RS No RR No No No No No No Yes Yes Yes Yes No Yes Yes No No No No No No No No Yes Yes Yes Yes Yes Yes Yes Yes No No 24 DB2 UDB for iSeries SQL Reference V5R2 . Cursors are not closed. if RS is not supported by a server. the RR isolation level is used. DB2 UDB for iSeries supports No Commit through COMMIT(*NONE) or COMMIT(*NC). DB2 UDB for iSeries supports uncommitted read through COMMIT(*CHG) or COMMIT(*UR). see the product-specific documentation. Note: (For distributed applications. For example. the isolation level is escalated to the next highest supported isolation level. For a detailed description of record lock durations. the rules of level UR apply except: – Commit and rollback operations have no effect on SQL statements. However.

Distributed relational databases are built on formal requester-server protocols and functions. 5. A simple distributed relational database environment is illustrated in Figure 8 on page 26. Yes See Note below Yes See Note below Yes See Note below Yes No Yes No Note: This depends on whether the cursor that is positioned on the “current” row is updatable: v If the cursor is updatable.Can “accessed” rows be read by other application processes? Can “current” row be updated or deleted by other application processes? See phenomenon P1 (dirty-read) below. Nonrepeatable Read. This is also known as a an application server. – For UR or NC. the application requester and server handle the communication and location considerations so that the application is isolated from these considerations and can operate as if it were accessing a local database. – For CS. Unit of work UW1 modifies a row. Unit of work UW2 modifies that row and performs a COMMIT. Each computer system has a relational database manager that manages the tables in its environment. Phantom. P2 P3 Distributed Relational Database A distributed relational database consists of a set of tables and other objects that are spread across different but interconnected computer systems or logical partitions on the same computer system. UW1 then re-reads the row and obtains the modified data value. UW1 then performs a ROLLBACK. the current row may be updatable in some circumstances. the current row can be updated or deleted by other application processes. These requests are received and processed by a server at the other end of the connection. UW1 then repeats the initial read with the same search condition and obtains the original rows plus the inserted rows. Unit of work UW2 then INSERTs one or more rows that satisfies the search condition. Examples of Phenomena: P1 Dirty Read. Unit of work UW1 reads the set of n rows that satisfies some search condition. Unit of work UW2 reads that row before UW1 performs a COMMIT. Chapter 1. An application requester supports the application end of a connection. Unit of work UW1 reads a row. Concepts 25 . the current row cannot be updated or deleted by other application processes v If the cursor is not updatable. UW2 has read a nonexistent row. It transforms a database request from the application into communication protocols suitable for use in the distributed database network.5 Working together. The database managers communicate and cooperate with each other in a way that allows a database manager to execute SQL statements on another computer system.

The CONNECT statement can be used to establish a connection to a server and make that server the current server of the activation group. A server can be local to. see the relational database folders in iSeries Navigator or the directory commands (ADDRDBDIRE.) This environment includes a local directory that describes the servers that can be identified in a CONNECT statement. A Distributed Relational Database Environment For more information about Distributed Relational Database Architecture (DRDA) communication protocols. This bound statement is taken from a package that the database manager previously created through a bind operation. the environment where the activation group is started.Figure 8. CHGRDBDIRE. DSPRDBDIRE. see Distributed Relational Database Architecture Reference Application Servers An activation group must be connected to the server of a database manager before SQL statements that reference tables or views can be executed. (A server is present. RMVRDBDIRE. 26 DB2 UDB for iSeries SQL Reference V5R2 . even when distributed relational databases are not used. a server uses the bound form of the statement. See the SQL Programming with Host Languages book for a description of the CRTSQLxxx commands. and WRKRDBDIRE) in the following iSeries Information Center topics: v SQL Programming Concepts v Distributed Database Programming v CL commands To execute a static SQL statement that references tables or views. For more information about the directory. The appropriate package is determined by the combination of: v The name of the package specified by the SQLPKG parameter on the CRTSQLxxx commands. A connection is an association between an activation group and a local or remote server. v The internal consistency token that makes certain the package and program were created from the same source at the same time. or remote from. Connections are managed by the application.

within one or more units of work. that activation group can execute any number of static or dynamic SQL statements that reference objects at B. Some of these features are product-specific.A DB2 relational database product may support a feature that is not supported by the version of the DB2 UDB product that is connecting to the application server. For the most part. the activation group can connect to a server at computer system C. See “CONNECT (Type 1) and CONNECT (Type 2) Differences” on page 845 for a summary of the differences. See “CONNECT (Type 1)” on page 417. CONNECT (Type 1) and CONNECT (Type 2) There are two types of CONNECT statements with the same syntax but different semantics: v CONNECT (Type 1) is used for remote unit of work. Most SQL statements can be remotely prepared and executed with the following restrictions: v All objects referenced in a single SQL statement must be managed by the same server. Concepts 27 . Restrictions are listed in Appendix C.” on page 835. “Characteristics of SQL Statements. an application can use the statements and clauses that are supported by the database manager of the server to which it is currently connected. Then. and so on. After ending a unit of work at B. v CONNECT (Type 2) is used for distributed unit of work. even though that application is running via the application requester of a database manager that does not support some of those statements and clauses. Remote Unit of Work The remote unit of work facility provides for the remote preparation and execution of SQL statements. See “CONNECT (Type 2)” on page 422. Remote Unit of Work Connection Management An activation group is in one of three states at any time: Connectable and connected Unconnectable and connected Connectable and unconnected The following diagram shows the state transitions: Chapter 1. v All of the SQL statements in a unit of work must be executed by the same server. and some are shared by more than one product. An activation group at computer system A can connect to a server at computer system B.

Remote Unit of Work Activation Group Connection State Transition The initial state of an activation group is connectable and connected. The server to which the activation group is connected is determined by the RDB parameter on the CRTSQLxxx and STRSQL commands and may involve an implicit CONNECT operation. or ROLLBACK. The activation group enters this state when: v The connection was previously released and a successful COMMIT is executed. The only SQL statement that can be executed is CONNECT. The unconnectable and connected state: An activation group is connected to a server. but a CONNECT statement cannot be successfully executed to change servers. The activation group enters this state from the connectable and connected state when it executes any SQL statement other than CONNECT.Figure 9. A CONNECT to the server to which the activation group is currently connected is executed like any other CONNECT statement. COMMIT. Thus. The connectable and unconnected state: An activation group is not connected to a server. Consecutive CONNECT statements can be executed successfully because CONNECT does not remove the activation group from the connectable state. an activation group cannot be implicitly connected to a server more than once. The connectable and connected state: An activation group is connected to a server and CONNECT statements can be executed. v The connection is disconnected using the SQL DISCONNECT statement. The activation group enters this state when it completes a rollback or successful commit from the unconnectable and connected state. 28 DB2 UDB for iSeries SQL Reference V5R2 . CONNECT cannot execute successfully when it is preceded by any SQL statement other than CONNECT. v The connection was in a connectable state. but the CONNECT statement was unsuccessful. An implicit CONNECT operation cannot occur if an implicit or explicit CONNECT operation has already successfully or unsuccessfully occurred. or a CONNECT statement is successfully executed from the connectable and unconnected state.

However. Each connection of an activation group is uniquely identified by the name of the server of the connection. any number of servers can participate in the same unit of work. The following diagram shows the state transitions: Chapter 1. Like remote unit of work. or ROLLBACK (unless running with COMMIT(*NC)). execute a commit or rollback operation before a CONNECT statement is executed. an activation group at computer system A can connect to a server at computer system B and execute any number of static or dynamic SQL statements that reference objects at B before ending the unit of work. v An SQL connection is always in one of the following states: – Current and held – Current and release-pending – Dormant and held – Dormant and release-pending Initial state of an activation group: An activation group is initially in the connected state and has exactly one connection. RELEASE. SET CONNECTION. unlike remote unit of work. Application-Directed Distributed Unit of Work Connection Management At any time: v An activation group is always in the connected or unconnected state and has a set of zero or more connections. To avoid an error. Concepts 29 . Distributed unit of work is fully supported for APPC and TCP/IP connections. A commit or rollback operation ends the unit of work.COMMIT. The initial state of a connection is current and held. All objects referenced in a single SQL statement must be managed by the same server. Application-Directed Distributed Unit of Work The application-directed distributed unit of work facility also provides for the remote preparation and execution of SQL statements in the same fashion as remote unit of work. DISCONNECT.

every release-pending 30 DB2 UDB for iSeries SQL Reference V5R2 .Figure 10. is placed in the dormant state. an error is returned. if any. When a connection is placed in the current state. the previous current connection. v The server name is added to the set of connections and the new connection is placed in the current and held state. Changing the state of a connection from current to dormant or from dormant to current has no effect on its held or release-pending state. Application-Directed Distributed Unit of Work Connection and Activation Group Connection State Transitions Connection States If an application process successfully executes a CONNECT statement: v The current connection is placed in the dormant state and held state. A connection in the dormant state is placed in the current state using the SET CONNECTION statement. A connection is placed in the release-pending state by the RELEASE statement. No more than one connection in the set of existing connections of an activation group can be current at any time. If the server name is already in the set of existing connections of the activation group. When an activation group executes a commit operation.

An activation group in the connected state enters the unconnected state when its current connection is intentionally ended or the execution of an SQL statement is unsuccessful because of a failure that causes a rollback operation at the current server and loss of the connection. Chapter 1. or when an application process successfully executes the DISCONNECT statement. The following rules apply: v An activation group cannot have more than one connection to the same server at the same time. COMMIT. SET CONNECTION. The only SQL statements that can be executed are CONNECT. all resources that were acquired by the activation group through the connection and all resources that were used to create and maintain the connection are deallocated. Changing the state of a connection from held to release-pending has no effect on its current or dormant state. Thus. a connection in the release-pending state can still be used until the next commit operation. There is no way to change the state of a connection from release-pending to held. The activation group can execute SQL statements that refer to objects managed by that server. the specified location name must be an existing connection in the set of connections of the activation group. if application process P has placed the connection to server X in the release-pending state. A connection can also be ended as a result of a communications failure in which case the activation group is placed in the unconnected state. RELEASE. the activation group is in the unconnected state. Activation Group Connection States A different server can be established by the explicit or implicit execution of a CONNECT statement. The CURRENT SERVER special register contains the name of the server of the current connection. When a Connection is Ended When a connection is ended. The CURRENT SERVER special register contents are equal to blanks. DISCONNECT. If an activation group has a current connection. v When an activation group executes a SET CONNECTION statement. Concepts 31 . and ROLLBACK. all cursors of P at X will be closed and deallocated when the connection is ended during the next commit operation. If an activation group does not have a current connection. Connections are intentionally ended when an activation group successfully executes a commit operation and the connection is in the release-pending state. v When an activation group executes a CONNECT statement.connection of the activation group is ended. the activation group is in the connected state. the specified server name must not be an existing connection in the set of connections of the activation group. For example. An activation group in the unconnected state enters the connected state when it successfully executes a CONNECT or SET CONNECTION statement. All connections of an activation group are ended when the activation group ends.

character set A defined set of characters. In either case. the string could have a different representation at the sending and receiving systems. For more information about character conversion. SC09-1390. refer to the book Character Data Representation Architecture Level 1 Reference. With character and graphic data. String conversions are done in accordance with the IBM Character Data Representation Architecture (CDRA). Conversion can also occur during string operations on the same system. : . the data type and the environment type of the sending system are not sufficient. these two cases: v The values of host variables sent from the application requester to the current server.6 Character conversion can occur when an SQL statement is executed remotely. Thus. for many readers. all the characters are represented by a common coding representation. In some cases. For example. Character conversion. for example. Character Conversion A string is a sequence of bytes that may represent characters. the information needed to perform the conversion is the data type and the sending system’s environment type. the following character set appears in several code pages: v 26 non-accented letters A through Z v 26 non-accented letters a through z v digits 0 through 9 v . the number is converted from IEEE format to System/370* format. When data is moved from one system to another. The following list defines some of the terms used when discussing character conversion. 32 DB2 UDB for iSeries SQL Reference V5R2 . therefore. For example.Data Representation Considerations Different systems represent data in different ways. Consider. A knowledge of conversion is. unnecessary when all the strings involved in a statement’s execution are represented in the same way._ (underscore) & + % * = < > A set of assignments of characters to code points. . when a floating-point variable from a DB2 UDB for iSeries application requester is assigned to a column of a table at an OS/390 server. String conversion depends on both the coded character set of the data and the operation to be done with that data. In EBCDIC. v The values of result columns sent from the current server to the application requester. Additional information is needed to convert character and graphic strings. for example. Products supporting DRDA will automatically perform any necessary conversions at the receiving system. data conversion must sometimes be performed. character conversion may be irrelevant. is automatic and is transparent to the application when it is successful. The process of conversion is known as character conversion. With numeric data. it might be necessary to convert these characters to a different coding representation. "A" is assigned code point code page 6. Within a string. ? ( ) ’ ″ / . when required.

Chapter 1. encoding scheme substitution character Character Sets and Code Pages The following example shows how a typical character set might map to different code points in two different code pages. each code point has only one specific meaning. The term ASCII is used throughout this book to refer to IBM-PC data or ISO 8 data. A set of unambiguous rules that establish a character set and the one-to-one relationships between the characters of the set and their coded representations.X'C1' and "B" is assigned code point X'C2'. code point coded character set A unique bit pattern that represents a character.and double-byte EBCDIC v Mixed single. For example: v Single-byte EBCDIC v Single-byte ASCII7 v Mixed single. A unique character that is substituted during character conversion for any characters in the source coding representation that do not have a match in the target coding representation.and double-byte ASCII v UCS-2 (universal coded character set). A set of rules used to represent character data. Concepts 33 . 7. Within a code page.

Furthermore. and the same code point can represent a different character in different coded character sets. A CCSID in a foreign encoding scheme is one of the coded character sets in which data cannot be stored at that site. A host variable containing data in a foreign encoding scheme is also effectively converted to a CCSID in the native encoding scheme when used in comparison or in an operation that combines strings. The Coded Character Set 34 DB2 UDB for iSeries SQL Reference V5R2 . This is not the case with graphic strings. DB2 UDB for iSeries can store data in a CCSID with an EBCDIC encoding scheme. a byte in a character string does not necessarily represent a character from a single-byte character set (SBCS). A host variable containing data in a foreign encoding scheme is always converted to a CCSID in the native encoding scheme when the host variable is used in a function or in the select-list. For example. the database manager assumes that every pair of bytes in every graphic string represents a character from a double-byte character set (DBCS) or universal coded character set (UCS-2). Coded Character Sets and CCSIDs IBM’s Character Data Representation Architecture (CDRA) deals with the differences in string representation and encoding. but not in an ASCII encoding scheme. A CCSID in a native encoding scheme is one of the coded character sets in which data may be stored at that site. Character strings are also used for mixed data (a mixture of single-byte characters and double-byte characters) and for data that is not associated with any character set (called bit data).Even with the same encoding scheme there are many different coded character sets. Which CCSID in the native encoding scheme the data is converted to is based on the foreign CCSID and the default CCSID.

A CCSID is an attribute of strings. Sort Sequence A sort sequence defines how characters in a character set relate to each other when they are compared and ordered. For example. the CCSID used will be the value of the DFTCCSID job attribute. the default CCSID of host variables is determined by the application requester.) Default CCSID Every server and application requester has a default CCSID (or default CCSIDs in installations that support DBCS data). This information includes an indication of whether conversion is required. a and A. All values of the same string column have the same CCSID. character conversion involves the use of a CCSID Conversion Selection Table. The Conversion Selection Table contains a list of valid source and target combinations. A CCSID is a 2-byte (unsigned) binary number that uniquely identifies an encoding scheme and one or more pairs of character sets and code pages. The CCSID of the following types of strings is determined at the current server: v String constants (including string constants that represent datetime values) when the CCSID of the source is in a foreign encoding scheme Special registers with string values (such as USER and CURRENT SERVER) CAST specifications where the result is a character or grahic string Results of CHAR. GRAPHIC. DIGITS. the default CCSID of host variables is determined by the server. for instance. Different sort sequences are useful for those who want their data ordered for a specific language. lists can be ordered as they are normally seen for a specific language. In a non-distributed SQL program. the CCSID used will be the value of the DFTCCSID job attribute. the character string columns will not use 65535. For each pair of CCSIDs. the default CCSID is determined by the CCSID job attribute. In each database manager. If the default CCSID is 65535. just as length is an attribute of strings. Instead. If the default CCSID is 65535. Chapter 1. For more information about CCSIDs. A sort sequence works on all comparisons that involve: v SBCS character data (including bit data) v the SBCS portion of mixed data 8.Identifier (CCSID) is a key element of this architecture. and VARGRAPHIC scalar functions when a CCSID is not specified as an argument v Results of the CLOB and DBCLOB scalar functions when a CCSID is not specified as an argument v String columns defined by the CREATE TABLE or ALTER TABLE statements when an explicit CCSID is not specified for the column9 v v v v In a distributed SQL program. A sort sequence can also be used to treat certain characters as equivalent. On OS/400. and the function is a CAST to a CLOB or DBCLOB. see the Work with CCSIDs topic in the Globalization section of the iSeries Information Center. no conversion is necessary even though the strings involved have different CCSIDs. Concepts 35 . 9. and HEX scalar functions8 Results of VARCHAR. (In some cases. the Conversion Selection Table contains information used to perform the conversion from one coded character set to the other.

For programs precompiled with a release of the product that is earlier than Version 2 Release 3. STRSQL. a user must be authorized to create tables. Authorization.and shared-weight sort sequences are shipped on the system as part of the operating system. The bytes in the sort sequence table are set based on how each code point is to compare to other code points in that code page. a CCSID must be associated with the table. Only a subset of the thousands of characters in UCS-2 are typically represented in the table. the sort sequence is a shared-weight sort sequence. a user must be authorized to alter the table. Privileges and Object Ownership Users can successfully execute SQL statements only if they have the authority to perform the specified function. a sort sequence is specified on the CRTSQLxxx. For example. see the Work with CCSIDs topic in the Globalization section of the iSeries Information Center. When two or more bytes (or pair of bytes for UCS-2) in a sort sequence table have the same value. if the characters a and A are to be treated as equivalents for comparisons. Because the sort sequence is applicable to character data. A weighted representation of the data is used for the comparison.v UCS-2 graphic data. UCS-2 sort sequence support is implemented using a multi-byte table. The sort sequence applies to all character comparisons performed in the SQL statements. or weight. the sort sequence is a unique-weight sort sequence. see the Sort Sequence tables topic in the iSeries Information Center. to alter a table. Each byte in the table corresponds to a code point or character in a SBCS code page. The bytes in the sort sequence table are set based on how each character is to compare with other characters in UCS-2. For more information about sort sequences and the sequences shipped with the system. you define them using the Create Table (CRTTBL) command. the bytes in the sort sequence table for their code points contain the same value. and so forth. Sort sequences do not apply to FOR BIT DATA or BLOB columns. unique. For more information about CCSIDs. For many languages. In SQL. The default sort sequence on the system is the internal sequence that occurs when the hexadecimal representation of characters are used. Only those characters that are to compare differently (and possibly other characters in the same ward) will be represented in the table. This is the sequence you get when the SRTSEQ(*HEX) is specified. A pair of bytes within the table corresponds to a character in the UCS-2 code page. The SET OPTION statement can be used to specify the sort sequence within the source of a program containing embedded SQL. the sort sequence is *HEX. SBCS sort sequence support is implemented using a 256-byte table. and RUNSQLSTM commands. To create a table. It is important to remember that the data itself is not altered by the sort sequence. If every byte (or pair of bytes for UCS-2) in a sort sequence table has a unique value. There are two forms of authorization: administrative authority The person or persons holding administrative authority are charged with the task of controlling the database manager and are responsible for the safety 36 DB2 UDB for iSeries SQL Reference V5R2 . If you need sort sequences for other languages or needs.

When an object is created. if a user profile with that name exists. the authorization ID of the statement must have the privilege to create objects in the implicitly or explicitly specified schema. Those with administrative authority implicitly have all privileges on all objects and control who will have access to the database manager and the extent of this access. he is always allowed to grant the privilege back to himself. including the privilege to drop the object. PUBLIC specifies that a privilege is granted to a set of users (authorization IDs).and integrity of the data. Concepts 37 . The security officer and all users with *ALLOBJ authority have administrative authority. If *SQL naming convention is used. the owner may temporarily be unable to perform an operation that requires that privilege. For example. When an object is created: v If SQL names were specified. Authority granted to *PUBLIC on SQL objects depends on the naming convention that is used at the time of object creation. The authorization ID of a statement has the privilege to create objects in the schema if: v it is the owner of the schema. Authorized users can create objects. A revoke of a privilege from an authorization ID revokes the privilege granted by all authorization IDs. Ownership gives the user complete control over the object. the owner of the object is the user profile or group user profile of the job executing the statement. When an object is created. Revoking a privilege from an authorization ID will not revoke that same privilege from any other authorization IDs that were granted the privilege by that authorization ID. the owner of the object is the user profile or group user profile of the job executing the statement. In this case. Because he is the owner. however. In the Authorization sections of this book. the owner of the object is the user profile with the same name as the schema into which the alias is created. *PUBLIC acquires *EXCLUDE authority. This affects private grants. If *SYS naming convention is used. or v it has *EXECUTE and *ADD to the schema. If the object is a view. Privileges may be granted to specific users or to PUBLIC. and UPDATE is then granted to HERNANDZ. *PUBLIC acquires the create authority (CRTAUT) of the library into which the object was created. The REVOKE statement can be used to REVOKE previously granted privileges. this private grant prevents HERNANDZ from having the SELECT privilege. privileges Privileges are those activities that a user is allowed to perform. The privileges on the object can be granted by the owner. it is assumed that the owner of an object has not had any privileges revoked from that object since it was initially created. and can pass on privileges on their own objects to other users by using the GRANT statement. one authorization ID is assigned ownership of the object. and can be revoked from the owner. v If system names were specified. Otherwise. it is also assumed that the owner of the view has not had the Chapter 1. The set consists of those users (including future users) that do not have privately granted privileges on the table or view. if SELECT has been granted to PUBLIC. have access to objects they own.

The DB2 File Manager on a file server works in conjunction with DB2 to provide the following optional functionality: v Referential integrity to ensure that files currently linked to DB2 are not deleted or renamed. The partitions included are determined by the nodegroup specified when the table is created or altered. Storage Structures The iSeries system is an object-based system. A DataLink value which is recorded in a regular table points to a file that is stored in an external file server. All database objects in DB2 UDB for iSeries (tables and indexes for example) are objects in OS/400. filters commands to ensure that proper access authority exists. 38 DB2 UDB for iSeries SQL Reference V5R2 . and if a view is referenced. For more information about authority and privileges. A partitioned or distributed table allows data to be spread across different database partitions. The single-level storage manager manages all storage of objects of the database. For more information about nodegroups and data partitioning see the DB2 Multisystem book. and so forth. all tables and views referenced in its definition. see the book iSeries Security Reference . The DataLinker comprises the following facilities: DataLinks File Manager Registers all the files in a particular file server that are linked to DB2. DataLinks Filter Filters file system commands to ensure that registered files are not deleted or renamed.system authority *READ revoked from any of the tables or views that this view is directly or indirectly dependent on. A partitioning map is associated with each nodegroup. Optionally. v Security to ensure that only those with suitable SQL privileges on the DataLink column can read the files linked to that column. The partitioning map is used by the database manager to determine which system from the nodegroup will store a given row of data. A nodegroup is a group of one or more iSeries systems. The owner has system authority *READ for all tables and views referenced in the view definition. table spaces) are unnecessary. so database specific storage structures (for example. The mechanism for this is the DataLink data type. A table can also include columns that register links to data that are stored in external files.

all characters of the statement except for string constants will be converted to single-byte characters prior to processing. These three code points should be avoided because they represent different characters depending on the CCSID. and $ in the United States). © Copyright IBM Corp. 11 A digit is any of the characters 0 through 9. 11.Chapter 2. see the following sections: v “Characters” v “Tokens” on page 41 v “Identifiers” on page 43 v “Naming Conventions” on page 45 v “SQL Path” on page 53 v “Aliases” on page 56 v “Authorization IDs and Authorization-Names” on page 57 v “Data Types” on page 59 v “Promotion of Data Types” on page 76 v “Casting Between Data Types” on page 78 v v v v v v v v v v v “Assignments and Comparisons” on page 81 “Rules for Result Data Types” on page 94 “Conversion Rules for Operations That Combine Strings” on page 98 “Constants” on page 100 “Special Registers” on page 106 “References to Variables” on page 115 “Host Structures” on page 121 “Host Structure Arrays” on page 123 “Functions” on page 124 “Expressions” on page 130 “Predicates” on page 148 Characters The basic symbols of keywords and operators in the SQL language are single-byte characters10 that are part of all character sets supported by the IBM relational database products. Tokens representing string constants may be processed as UCS-2 graphic strings without conversion to single-byte. Characters of the language are classified as letters. or special characters. digits. Letters also include three code points reserved as alphabetic extenders for national languages (#. Note that if the SQL statement is encoded as UCS-2 data. For details. A special character is any of the characters listed below: 12 10. A letter is any of the 26 uppercase (A through Z) and 26 lowercase (a through z) letters of the English alphabet. 1998. Language Elements This chapter defines the basic syntax of SQL and language elements that are common to many SQL statements. 2002 39 . @.

Characters space quotation mark or double-quote percent ampersand apostrophe or single quote left parenthesis right parenthesis asterisk plus sign comma vertical bar . | 13 12. / : . 13. The not symbol (¬) and the exclamation point symbol (!) are also special characters used by DB2 UDB for iSeries. Using the vertical bar (|) character might inhibit code portability between IBM relational database products. Use of the vertical bar should be avoided because it is a variant character. Avoid using them because they are variant characters. < = > ? _ minus sign period slash colon semicolon less than equals greater than question mark underline or underscore ″ % & ’ ( ) * + . 40 DB2 UDB for iSeries SQL Reference V5R2 . It is preferable to use the CONCAT operator instead of the concatenation operator (||).

an operator symbol. A question mark (?) is also a delimiter token when it serves as a parameter marker. Control Characters: A control character is a special character that is used for string alignment. other than string constants and certain delimited identifiers. control characters.) Tokens are classified as ordinary or delimiter tokens: v An ordinary token is a numeric constant. a delimited identifier. .1 +2 SELECT E 3 Here are some examples of combinations of the above ordinary tokens that.3 Chapter 2. then a control character or a space must follow that ordinary token. Language Elements 41 . The following table contains the control characters that are handled by the database manager: Table 1.1+2 SELECTE . The following examples illustrate the rule that is stated in this paragraph. Here are some examples of combinations of the above ordinary tokens and the above delimiter tokens that. (These terms are defined later. or a space must follow every ordinary token. Spaces: A space is a sequence of one or more blank characters. v A delimiter token is a string constant. change the tokens: 1. A control character or space can follow a token. as explained under “PREPARE” on page 692. Control Characters Control Character Tab Form Feed Carriage Return New Line Line Feed (New line) EBCDIC Hex Value 05 0C 0D 15 25 UCS-2 Hex Value 0009 000C 000D 0085 000A Tokens. A delimiter token. If the syntax does not allow a delimiter token to follow an ordinary token.Tokens Tokens The basic syntactical units of the language are called tokens. a host identifier. Here are some examples of delimiter tokens: . and characters within a string constant or delimited identifier. an ordinary identifier. a control character. excluding blanks. in effect. or a keyword. ’string’ "fld1" = . must not include a control character or space. A token consists of one or more characters. in effect. change the tokens: 1. or any of the special characters shown in the syntax diagrams.1E E3 SELECT1 This demonstrates why ordinary tokens must be followed by a delimiter token or a space.1 . Here are some examples of ordinary tokens: 1 .

Thus. A bracketed comment can continue past the end of the line.). the statement: select * from EMP where lastname = ’Smith’. both the ordinary token (1) and the delimiter token (. For more information. Delimiter tokens are never folded to uppercase. Therefore.2' and '1. is equivalent.e1 If '1.e1' are meant to be two items. bracketed comments Bracketed comments are introduced by /* and end with */. Simple comments cannot continue past the end of the line.2 . If the decimal point has been defined to be the comma. the syntax does not allow an ordinary token to be followed by a delimiter token.) must be followed by a space. Although the comma is usually a delimiter token. to: SELECT * FROM EMP WHERE LASTNAME = ’Smith’. 42 DB2 UDB for iSeries SQL Reference V5R2 . 1. Either type of comment can be specified wherever a space may be specified. see “SQL Comments” on page 370. as described in “Decimal Point” on page 103. Instead. Dynamic SQL statements can include SQL comments.Tokens The period (. the comma is part of the number when it is interpreted as a decimal point. to prevent the comma from being interpreted as a decimal point. Comments: Static SQL statements can include host language comments or SQL comments. the comma is interpreted as a decimal point in numeric constants. Thus. after folding. the ordinary token must be followed by a space. There are two types of SQL comments: simple comments Simple comments are introduced by two consecutive hyphens (--).) is a delimiter token when it is used as a separator in the qualification of names. Here the dot is used in combination with an ordinary token of a numeric constant. except within a delimiter token or between the keywords EXEC and SQL.1 1. For more information. the syntax does not allow an ordinary token (1) to be followed by a delimiter token (. an ordinary token must be followed by a space. Here are some examples of these numeric constants: 1. Instead. Uppercase and Lowercase: Lowercase letters used in an ordinary token other than a C host variable will be folded to uppercase. see “SQL Comments” on page 370.

See Appendix G. The sequence must consist of one or more characters. and all other variant characters should not be used in identifiers because the code points used to represent them vary depending on the CCSID of the string in which they are contained. see the Variant characters topic in the iSeries Information Center. a digit. There are two types of system identifiers: ordinary identifiers and delimited identifiers. Note that delimited identifiers are not converted to uppercase. @. Language Elements 43 . each of which is an uppercase letter. #. An ordinary identifier should not be a reserved word.Identifiers Identifiers An identifier is a token used to form a name. unpredictable results may occur. Note that ordinary identifiers are converted to uppercase. except: – The following special characters are not allowed in a delimited system identifier: . v The rules for forming a system delimited identifier are identical to those for forming SQL delimited identifiers. or the underscore character.A blank (X'40') Chapter 2. SQL Identifiers There are two types of SQL identifiers: ordinary identifiers and delimited identifiers. “Reserved Words. The length of a delimited identifier does not include the two SQL escape characters. An identifier in an SQL statement is one of the following types: v “SQL Identifiers” v “System identifiers” v “Host Identifiers” on page 44 Note: $.” on page 1009 for a list of reserved words. The escape character is the quotation mark (") except in the following cases where the escape character is the apostrophe ('): – Interactive SQL when the SQL string delimiter is set to the quotation mark in COBOL syntax checking statement mode – Dynamic SQL in a COBOL program when the CRTSQLCBL or CRTSQLCBLI parameter OPTION(*QUOTESQL) specifies that the string delimiter is the quotation mark (") – COBOL application program when the CRTSQLCBL or CRTSQLCBLI parameter OPTION(*QUOTESQL) specifies that the string delimiter is the quotation mark (") The following characters are not allowed within delimited identifiers: – X'00' through X'3F' and X'FF' | | | | | | | | | | | | | | | | | System identifiers A system identifier is used to form the name of system objects in OS/400. Leading blanks in the sequence are significant. If they are used. v The rules for forming a system ordinary identifier are identical to the rules for forming an SQL ordinary identifier. v A delimited identifier is a sequence of one or more characters enclosed within SQL escape characters. it should be specified in uppercase and enclosed within the SQL escape characters. Trailing blanks in the sequence are not significant. If a reserved word is used as an identifier in SQL. v An ordinary identifier is an uppercase letter followed by zero or more characters. For more information about variant characters.

An apostrophe (X'7D') . and is not a valid system name for a column because the bytes required for the delimiters must be included in the length of the identifier. or 'DSN' should not be used because precompilers generate host variables that begin with these characters.A question mark (X'6F') . “PRIVILEGES” is in uppercase and the characters within the delimiters form an ordinary identifier. COBOL. and PL/I. it should not be used in RPG. except that DBCS characters cannot be used.Identifiers . “privileges” is in lowercase. 44 DB2 UDB for iSeries SQL Reference V5R2 . 'RDI'. the rules for forming a host-identifier in a COBOL program are the same as the rules for forming a user-defined word in COBOL. therefore. it has a length of 10 bytes and is a valid system name for a column. 'sql'.A quotation mark (X'7F') – The bytes required for the escape characters are included in the length of the identifier unless the characters within the delimiters would form an ordinary identifier. 'SQ' is allowed in C. For example. 'SQL'. The rules for forming a host-identifier are the rules of the host language. Names beginning with the characters 'SQ'14. For example.An asterisk (X'5C') . has a length of 12 bytes. Examples WKLYSAL WKLY_SAL "WKLY_SAL" "UNION" "wkly_sal" Host Identifiers A host-identifier is a name declared in the host program. On the other hand. 14.

columnname. The SET OPTION statement can be used to specify the naming option within the source of a program containing embedded SQL.Naming Conventions Naming Conventions The rules for forming a name depend on the type of the object designated by the name and the naming option (*SQL or *SYS). RUNSQLSTM. Column names cannot be qualified with system names in the form schema-name/table-name. If column names need to be qualified. The unqualified form is an SQL identifier. except in the COMMENT and LABEL statements. For system naming. If a column name is delimited. A qualified or unqualified name that designates a column of a table or a view. The following list defines these terms. For SQL naming. and correlation names are allowed in the statement. For SQL naming. a view name. The qualified form of an alias-name depends on the naming option. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. or a correlation name. the qualified form is a schema-name followed by a period (. Language Elements column-name 45 . the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. The qualifier is a table name. the delimiters are considered to be part of the name when determining the length of the name. The qualified form of a constraint name depends on the naming option. An authorization name is a user profile name on the server. An alias-name can specify either the name of the alias or the system object name of the alias. See “Authorization IDs and Authorization-Names” on page 57 for the distinction between an authorization name and an authorization ID. alias-name A qualified or unqualified name that designates an alias. It must not be a delimited identifier that includes lowercase letters or special characters. The qualified form is a qualifier followed by a period and an SQL identifier.) and an SQL identifier. a correlation name must be used to qualify the column. The syntax diagrams use different terms for different types of names. and STRSQL commands. constraint-name A qualified or unqualified name that designates a constraint on a table. A column-name can specify either the column name or the system column name of a column of a table or view. The naming option is specified on the CRTSQLxxx. The unqualified form of a column name is an SQL identifier. the qualified form is a Chapter 2. authorization-name A system identifier that designates a user or group of users.

or individual rows of a table or view. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. SQL procedure. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. unqualified name. the qualified form is a schema-name followed by a period (. the qualified form is a schema-name followed by a slash (/) followed by a system identifier. For system naming. An SQL identifier that designates an SQL cursor. correlation-name cursor-name descriptor-name An SQL identifier that designates a table. the qualified form is a schema-name followed by a period (. external-program-name A qualified name. The unqualified form is an SQL identifier. distinct-type-name 46 DB2 UDB for iSeries SQL Reference V5R2 . distinct type names cannot be qualified when used in a parameter data type of an SQL routine or in an SQL variable declaration in an SQL function.Naming Conventions schema-name followed by a period (. The form :host-variable:indicator-variable is not allowed. For system naming. The qualified form of an external-program-name depends on the naming option.) and an SQL identifier. or a character string that designates an external program. A colon followed by a host-identifier that designates an SQL descriptor area (SQLDA). For SQL naming.) and a system identifier. A qualified or unqualified name that designates a distinct type. A host variable that designates an SQL descriptor area must not have an indicator variable. For SQL naming. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. For system naming.) and a system identifier. The unqualified form is an SQL identifier. For system naming. a view. The unqualified form is a system identifier. See “References to Host Variables” on page 115 for a description of a host identifier. The qualified form of a distinct-type-name depends upon the naming option. The format of the character string form is either: v An OS/400 qualified program name (’library-name/program-name’). or trigger. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53.

method-id’). a cast function that was generated when a distinct type was created. This form is only valid when calling a REXX procedure. It can be either a simple identifier. followed by a method identifier (’class-id!method-id’ or ’class-id. Examples are ’myJar’ and ’myCollection. For example. and a right parenthesis (’library-name/source-file-name(member-name)’). or a schema qualified identifier. v An OS/400 qualified service program name. The unqualified form is an SQL identifier. followed by an OS/400 entry-point-name. followed by a left parenthesis.StoredProcs’. followed by a right parenthesis (’library-name/service-programname(entry-point-name)’). For SQL naming. the qualified form is a schema-name followed by a period (. This form is only valid for functions. Language Elements 47 . The class-id identifies the class identifier of the Java object. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. If the class is part of a package. method-id The jar-id identifies the jar schema when it was installed in the database. if the class identifier is ’myPackage. This form is only valid for Java procedures and Java functions. followed by an OS/400 member name. function-name A qualified or unqualified name that designates a user-defined function. followed by a class identifier. the Java Virtual machine will look in the following directory for the StoredProcs class: ’/QIBM/UserData/OS400/SQLLib/ Function/myPackage/StoredProcs/’ The method-id identifies the method name of the Java object to be invoked. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. or a built-in function. The qualified form of a function-name depends upon the naming option. the class identifier must include the complete package prefix. followed by a left parenthesis. jar-id : class-id ! . followed by an exclamation point or period.Naming Conventions v An OS/400 qualified source file name. v An optional jar-id. For system naming. Chapter 2.) and an SQL identifier.myJar’.

) and a system identifier. For more information about distributed tables and nodegroups. package-name A qualified or unqualified name that designates a package.) and a system identifier. For SQL naming. The qualified form of an index-name depends upon the naming option. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. parameter-name An SQL identifier that designates a parameter for a index-name 48 DB2 UDB for iSeries SQL Reference V5R2 . For system naming. A sequence of tokens that designates a host variable. A host-variable includes at least one host-identifier.) and an SQL identifier. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. A qualified or unqualified name that designates an index. the qualified form is a schema-name followed by a slash (/) followed by a system identifier. DROP. The unqualified form is an SQL identifier. For system naming. COMMENT. For system naming. functions names can only be qualified in the form schema-name/function-name when the name is used in a CREATE. the qualified form is a schema-name followed by a period (. The unqualified form is a system identifier. see the DB2 Multisystem book. the qualified form is a schema-name followed by a period (. The qualified form of a package-name depends upon the naming option. or REVOKE statement. host-label host-variable A token that designates a label in a host program. the qualified form is a schema-name followed by a period (. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. the qualified form is a schema-name followed by a slash (/) followed by a system identifier. as explained in “References to Host Variables” on page 115. For SQL naming. For SQL naming. The unqualified form is a system identifier. nodegroup-name A qualified or unqualified name that designates a nodegroup. A nodegroup is a group of iSeries servers across which a table will be distributed. The qualified form of a nodegroup-name depends on the naming option. GRANT.Naming Conventions For system naming.

The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. the qualified form is a schema-name followed by a period (. A schema name is used as a qualifier of the name of a table. The unqualified form of a schema-name is a system identifier. index. alias. | | savepoint-name schema-name An unqualified identifier that designates a savepoint. The qualified form of a schema-name depends on the naming option. or package.) and a system identifier. A qualified or unqualified name that provides a logical grouping for SQL objects. constraint.) and an SQL identifier. The server-name must identify the current server. procedure. For system naming. The qualified form is a server-name followed by a slash (/) and a system identifier. The unqualified form is an SQL identifier. specific-name Chapter 2. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. the qualified form is a schema-name followed by a period (. The qualified form of a specific-name depends upon the naming option. the unqualified schema name in an SQL statement is implicitly qualified by the server-name. For SQL naming.Naming Conventions function or procedure. For SQL naming. server-name An SQL identifier that designates a server. If the parameter is for a procedure.) and an SQL identifier. A qualified or unqualified name that uniquely identifies a procedure or function. The server-name must identify the current server. Language Elements 49 . the unqualified schema name in an SQL statement is implicitly qualified by the server-name. The qualified form is a server-name followed by a (. For system naming. the identifier may be preceded by a colon. Note: Schema-name refers to either a schema created by the CREATE SCHEMA statement or to an OS/400 library. procedure-name A qualified or unqualified name that designates a procedure. For SQL names. function. The qualified form of a procedure-name depends upon the naming option. view. The identifier must not include lowercase letters or special characters. For system names. trigger. type.

A system-object-name is a system identifier.) and an SQL identifier. or alias is the unqualified name of the table.) and an SQL identifier. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. An unqualified name that designates the OS/400 column name of a table or a view. index. The unqualified form of an SQL parameter name is an SQL identifier.Naming Conventions The unqualified form is an SQL identifier.) and an SQL identifier. index. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. For SQL SQL-parameter-name SQL-variable-name statement-name system-column-name system-object-name 50 DB2 UDB for iSeries SQL Reference V5R2 . or alias. The qualified form of a table-name depends upon the naming option. The qualified form is a procedure-name followed by a period (. The unqualified form of an SQL variable name is an SQL identifier. view. A qualified or unqualified name that designates a parameter in an SQL routine body. If the unqualified name of the table. An SQL identifier that designates a prepared SQL statement. view. For SQL naming. or alias is a valid system identifier. table-name A qualified or unqualified name that designates a table. The unqualified form is an SQL identifier. the system-object-name of the table. For system naming. index. An SQL label name is an SQL identifier. the qualified form is a schema-name followed by a period (. System-column-names can be delimited identifiers. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. SQL function. A table-name can specify either the name of the table or the system object name of the table. SQL-label An unqualified name that designates a label in an SQL procedure. or alias. index. The qualified form of a trigger name depends on the naming option. A qualified or unqualified name that designates a variable in an SQL routine body. but the characters within the delimiters must not include lowercase letters or special characters. trigger-name A qualified or unqualified name that designates a trigger on a table. or trigger body. An unqualified name that designates the OS/400 name of a table. view. A system-column-name is a system identifier. view. The qualified form is an SQL label followed by a period (.

Naming Conventions naming. view-name A qualified or unqualified name that designates a view. A view-name can specify either the name of the view or the system object name of the view. Language Elements 51 . The qualified form of a view-name depends upon the naming option. Identifier Length Limits (in bytes) Identifier Type Longest authorization name Longest condition name Longest correlation name Longest cursor name Longest external program name (unqualified form) Longest external program name (string form) Longest host identifier Longest savepoint name Longest schema name Longest server name Longest SQL label Longest statement name Longest unqualified alias name Longest unqualified column name Longest unqualified constraint name Longest unqualified distinct type name Longest unqualified function name Longest unqualified index name Longest unqualified nodegroup name Longest unqualified package name Longest unqualified parameter name 15 Maximum Length 10 128 128 18 10 279 64 128 10 18 128 18 128 30 128 128 128 128 10 10 128 Chapter 2. For system naming. The unqualified form is an SQL identifier.) and an SQL identifier. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. For SQL naming. The unqualified form is implicitly qualified based on the rules specified in “Qualification of Unqualified Object Names” on page 53. The unqualified form is an SQL identifier. the qualified form is a schema-name followed by a period (.) and a system identifier. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. Table 2. the qualified form is a schema-name followed by a slash (/) followed by an SQL identifier. For system naming. the qualified form is a schema-name followed by a period (.

For REXX procedures. Identifier Length Limits (in bytes) (continued) Identifier Type Longest unqualified procedure name Longest unqualified specific name Longest unqualified SQL parameter name Longest unqualified SQL variable name Longest unqualified system column name Longest unqualified system object name Longest unqualified table and view name Longest unqualified trigger name Maximum Length 128 128 128 128 10 10 128 128 15. the limit is 33.Naming Conventions Table 2. 52 DB2 UDB for iSeries SQL Reference V5R2 .

Qualification of Unqualified Object Names Unqualified object names are implicitly qualified. . XGRAPHIC. QSYS. Searching through the path from left to right. The rules for qualifying a name differ depending on the type of object that the name identifies. CURRENT_PATH. the implicit qualifier is the schema-name that is specified for that parameter. For procedures. Trigger. and then QSYS and QSYS2. Index. or CURRENT FUNCTION PATH” on page 106. The SQLPATH can also be set using the SET OPTION statement. For more information on the SQL path. Table.SQL Path SQL Path The SQL path is an ordered list of schema names. For more information about the CURRENT PATH special register. nodegroup. COMMENT. the database manager selects a matching procedure name only if the number of parameters is also the same. Unqualified Alias.For system naming. and View Names Unqualified alias. see “CURRENT PATH. DROP. trigger. and procedure names that appear in any context other than as the main object of a CREATE. package. the database manager uses a process called function resolution in conjunction with the SQL path to determine which function to choose because several functions with the same name can reside in a schema. and view names are implicitly qualified as follows: v For static SQL statements: – If the DFTRDBCOL parameter is specified on the CRTSQLxxx command (or with the SET OPTION statement). if the SQL path is SMITH. constraint. CURRENT_PATH.For SQL naming. the database manager looks for MYTYPE first in schema SMITH. the database manager implicitly qualifies the object name with the first schema name in the path that contains the same object with the same unqualified name. Language Elements 53 . The path used is determined as follows: v For all static SQL statements (except for a CALL :host-variable statement). . see “Function resolution” on page 125. the implicit qualifier is based on the naming convention. For functions. then XGRAPHIC. Chapter 2. GRANT or REVOKE statement. or CURRENT FUNCTION PATH” on page 106. Nodegroup. Constraint. the implicit qualifier is the authorization identifier of the statement. function names. If the SQL path is not explicitly specified. index. (For details. the path used is the path specified in the CURRENT PATH special register. see “CURRENT PATH. The mechanism for explicitly specifying this depends on the interface used to dynamically prepare and execute SQL statements. v For dynamic SQL statements the implicit qualifier depends on whether or not a default schema name has been explicitly specified. the implicit qualifier is the job library list (*LIBL). the SQL path is SYSTEM followed by the authorization ID of the statement.) For example. – In all other cases. external program. table. The database manager uses the path to resolve the schema name for unqualified distinct type names (both built-in types and distinct types). the path used is the path specified in the SQLPATH parameter on the CRTSQLxxx command. External Program. Package. v For dynamic SQL statements (and for a CALL :host-variable statement). QSYS2 and an unqualified distinct type name MYTYPE was specified.

see the SQL Programming Concepts book. see the iSeries Access category in the iSeries Information Center. the implicit qualifier is the job library list (*LIBL).For SQL naming.SQL Path – If a default schema name is not explicitly specified: . and specific names depends on the SQL statement in which the unqualified name appears: v If an unqualified name is the main object of a CREATE.) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Run SQL Statements Call Level Interface (CLI) on the server JDBC or SQLJ on the server using Developer Kit for Java ODBC on a client using the iSeries Access ODBC Driver JDBC on a client using the IBM Toolbox for Java All interfaces Unqualified Function.) SET SCHEMA or QSQCHGDC (Change Dynamic Default Collection) API (For more information about QSQCHGDC.For system naming. procedure. see IBM Toolbox for Java topic in the iSeries Information Center . . GRANT. the name is implicitly qualified using the same 54 DB2 UDB for iSeries SQL Reference V5R2 . Specific. or REVOKE statement. Default Schema Interfaces SQL Interface Embedded SQL Specification DFTRDBCOL parameter and DYNDFTCOL(*YES) on the Create SQL Program (CRTSQLxxx) and Create SQL Package (CRTSQLPKG) commands. The SET OPTION statement can also be used to set the DFTRDBCOL and DYNDFTCOL values.) DFTRDBCOL parameter on the Run SQL Statements (RUNSQLSTM) command. and Distinct Type Names The qualification of data type (both built-in types and distinct types).) (For more information about the IBM Toolbox for Java.) SQL Default Library in ODBC Setup (For more information about ODBC. see the iSeries Access category in the iSeries Information Center. the implicit qualifier is the run-time authorization identifier. DROP. – If a default schema name is explicitly specified.) libraries property object (For more information about JDBC and SQLJ. (For more information about CRTSQLxxx commands. see the SQL Programming with Host Languages book. see the IBM Developer Kit for Java topic in the iSeries Information Center. see the File APIs category in the iSeries Information Center. function. COMMENT.) SQL Default Library in JDBC Setup (For more information about JDBC. (For more information about the RUNSQLSTM command. The default schema name can be specified through the following interfaces: Table 3. see the SQL Call Level Interfaces (ODBC) book.) SQL_ATTR_DEFAULT_LIB or SQL_ATTR_DBC_DEFAULT_LIB environment or connection variables (For more information about CLI. Procedure. the implicit qualifier is that default schema.

Constraint. Chapter 2. See the File Management book for more information about the override function. as described under “Function resolution” on page 125. Index. the implicit schema name is determined as follows: – For distinct type names. – For procedure names. Package. and View Names” on page 53). Trigger. the database manager uses the SQL path in conjunction with function resolution. the database manager searches the SQL path and selects the first schema in the path such that the schema contains a procedure with the same name and number of parameters. Language Elements 55 . Overrides are ignored for data definition SQL statements and data manipulation SQL statements executing at a remote relational database.SQL Path rules as for qualifying unqualified table names (See “Unqualified Alias. Nodegroup. – For function names and for specific names specified for sourced functions. Table. SQL Names and System Names: Special Considerations The CL command Override Database File (OVRDBF) can be specified to override an SQL or system name with another object name for local data manipulation SQL statements. the database manager searches the SQL path and selects the first schema in the path such that the data type exists in the schema. External Program. v Otherwise.

which must be defined before the SQL statement is executed. file. or VALUES INTO statement.DIST4_SALES_148 If an alias is dropped and recreated to refer to another table. the object must exist when a statement that references the alias is executed. The effect of using an alias in an SQL statement is similar to that of text substitution. if PBIRD. is replaced by the qualified base table. An alias can only refer to a table. However. For example. if an alias name of PERSONNEL is created. UPDATE. such as in the CREATE TABLE or CREATE VIEW statements. An alias can only refer to a table. For example. view. or database file member name. A table or view in an SQL statement can be referenced by its name or by an alias. then a subsequent statement such as CREATE TABLE PERSONNEL will cause an error. The option of referring to a table. DELETE. view. view. view. view. INSERT.Aliases Aliases An alias can be thought of as an alternative name for a table. except: v Do not use an alias name where a new table or view name is expected. The alias. dropping and re-creating the alias has no effect on the view or index. but an alias is also a permanent object that only need be created once. 56 DB2 UDB for iSeries SQL Reference V5R2 . view. or alias. An alias cannot refer to another alias. An alias can be used wherever a table or view name can be used. SET variable. Not only does an alias perform better than an override. index. or database file member within the same relational database.SALES is an alias for DSPN014. For syntax toleration of existing DB2 UDB for OS/390 and z/OS applications. Aliases can also help avoid using file overrides. any SQL statements that refer to that alias will be implicitly rebound when they are next run. or member of a database file. An alias can be created even though the object the alias refers to does not exist. A new alias cannot have the same fully-qualified name as an existing table. A warning is returned if the object does not exist when the alias is created. v An alias that refers to an individual member of a database file member can only be used in a select statement. If a CREATE VIEW or CREATE INDEX statement refers to an alias. SYNONYM can be used in place of ALIAS in the CREATE ALIAS and DROP ALIAS statements.SALES effectively becomes SELECT * FROM DSPN014.DIST4_SALES_148. SELECT INTO. then at statement run time: SELECT * FROM PBIRD. or database file member within the same relational database. or database file member by an alias name is not explicitly shown in the syntax diagrams or mentioned in the description of the SQL statements.

the authorization ID that applies is the ID of the owner of the non-distributed program. For distributed SQL programs. the authorization ID that applies is the ID of the owner of the SQL package at the current server. the authorization ID that applies is the ID of the user that issued the STRREXPRC command. – If the USRPRF value is *OWNER and the DYNUSRPRF value is *USER for the SQL package. the authorization ID that applies is the ID of the user running the SQL package at the current server. or if USRPRF(*NAMING) is specified and SQL naming mode is used. It designates a set of privileges. the authorization ID that applies is the ID of the user running the non-distributed program. v If the statement is executed from the RUNSQLSTM command. it is the owner of the SQL package. but this property is not controlled by the database manager. the authorization ID of the statement is the authorization ID of the user running the non-distributed SQL program. – If the USRPRF value is *OWNER and the DYNUSRPRF value is *OWNER for the program. it is the authorization ID of the user at the current server. v If the statement is executed from REXX. For distributed SQL programs. This is called the run-time authorization ID. Language Elements 57 . v If USRPRF(*USER) is specified.Authorization IDs and Names Authorization IDs and Authorization-Names An authorization ID is a character string that is obtained by the database manager when a connection is established between the database manager and either an application process or a program preparation process. The authorization ID that is used for authorization checking for a dynamic SQL statement also depends on where and how the statement is executed: v If the statement is prepared and executed from a non-distributed program: – If the USRPRF value is *USER and the DYNUSRPRF value is *USER for the program. the authorization ID that applies is the ID of the user running the SQL package at the current server. the authorization ID of the statement is the owner of the non-distributed SQL program. The authorization ID that is used for authorization checking for a static SQL statement depends on the USRPRF value specified on the precompiler command: v If USRPRF(*OWNER) is specified. the authorization ID that applies is the ID of the user running the non-distributed program. Authorization ID’s are used by the database manager to provide authorization checking of SQL statements. or if USRPRF(*NAMING) is specified and system naming mode is used. – If the USRPRF value is *OWNER and the DYNUSRPRF value is *USER for the program. – If the USRPRF value is *OWNER and the DYNUSRPRF value is *OWNER for the SQL package. v If the statement is issued interactively. An authorization ID applies to every SQL statement. the authorization ID that applies is the ID of the user that issued the RUNSQLSTM command. This is also called the run-time authorization ID. v If the statement is prepared and executed from a distributed program: – If the USRPRF value is *USER and the DYNUSRPRF value is *USER for the SQL package. Chapter 2. the authorization ID that applies is the ID of the user that issued the Start SQL (STRSQL) command. It may also designate a user or a group of users.

the authority to execute the statement is checked against SMITH.TDEPT. For information on group user profiles. Example Assume SMITH is your user ID. KEENE is given the SELECT privilege on SMITH. the run-time authorization ID is the user profile of the job. The premise of a grant of privileges to X is that X will subsequently be the authorization ID of statements which require those privileges. An authorization-name specified in an SQL statement should not be confused with the authorization ID of the statement. KEENE is an authorization-name specified in the statement. Thus. see the book iSeries Security Reference . A group user profile can also be used when checking authority for an SQL statement.Authorization IDs and Names On OS/400. An authorization-name is an identifier that is used in GRANT and REVOKE statements to designate a target of the grant or revoke. then SMITH is the authorization ID when you execute the following statement interactively: GRANT SELECT ON TDEPT TO KEENE SMITH is the authorization ID of the statement. 58 DB2 UDB for iSeries SQL Reference V5R2 .

parameter markers and parameters of routines) v Special registers The DB2 UDB relational database products support both both built-in data types and user-defined data types. How values are interpreted depends on the data type of their source. SQL variables. Language Elements 59 . see “User-Defined Types” on page 73. Chapter 2. The following figure illustrates the various built-in data types supported by the DB2 UDB for iSeries program.Data Types Data Types The smallest unit of data that can be manipulated in SQL is called a value. The sources of values are: v Columns v Constants v Expressions v Functions v Variables (such as host variables. For a description of distinct types. This section describes the built-in data types.

see the following topics: v “Binary Strings” on page 65 v “Character Strings” on page 62 v v v v v v “Character Encoding Schemes” on page 63 “Graphic Strings” on page 64 “Graphic Encoding Schemes” on page 65 “Large Objects (LOBs)” on page 65 “Numbers” on page 61 “Datetime Values” on page 67 60 DB2 UDB for iSeries SQL Reference V5R2 .Data Types For more details on data types.

For small integers.40282356 × 1038.Data Types | v “DataLink Values” on page 72 v “Row ID Values” on page 73 v “User-Defined Types” on page 73 For information about specifying the data types of columns. The position of the decimal point is determined by the precision Chapter 2. decimal precision and scale are supported by COBOL. RPG. Nulls All data types include the null value. The range of large integers is −2147483648 to +2147483647. A double-precision floating-point number is a IEEE 64-bit approximate representation of a real number. The sign is positive if the value is zero. columns that are defined as NOT NULL. For information concerning the precision and scale of binary integers. RPG.7976931348623158 × 10308. The range of big integers is −9223372036854775808 to +9223372036854775807.17549436 × 10−38 to 3. Decimal A decimal value is a packed-decimal or zoned-decimal number with an implicit decimal point. see the DDS Reference book. Although all data types include the null value. see “CREATE TABLE” on page 526. constants. The null value is a special value that is distinct from all nonnull values and thereby denotes the absence of a (nonnull) value. the COUNT and COUNT_BIG functions cannot return a null value. some sources of values cannot provide the null value. and special registers cannot contain null values. see the DDS Reference book. The precision is the total number of binary or decimal digits excluding the sign. Big Integer (BIGINT) A big integer is a binary number composed of 8 bytes (64 bits) with a precision of 19 digits. For information concerning the precision and scale of binary integers. For example. Large Integer A large integer is a binary number composed of 4 bytes (32 bits) with a precision of 10 digits.2250738585072014 × 10−308 to 1. The range of magnitude is approximately 1. Floating-Point A single-precision floating-point number is a 32-bit approximate representation of a real number. For large integers. The range of small integers is −32768 to +32767. and iSeries system files. The range of magnitude is approximately 2. Language Elements 61 . Small Integer A small integer is a binary number composed of 2 bytes (16 bits) with a precision of 5 digits. decimal precision and scale are supported by COBOL. and ROWID columns cannot store a null value although a null value can be returned for a ROWID column as the result of a query. and iSeries system files. Numbers All numbers have a sign and a precision.

ILE COBOL. The range of a decimal variable or the numbers in a decimal column is -n to +n. If the length is zero. The maximum range is negative 1031+1 to 1031 minus 1.Data Types and the scale of the number. using a CAST specification). (In C. using a CAST specification) the implicit decimal point is replaced by the default decimal separator character in effect when the statement was prepared. and RPG: 62 DB2 UDB for iSeries SQL Reference V5R2 . cannot be negative or greater than the precision. All values of a decimal column have the same precision and scale. see “Large Objects (LOBs)” on page 65. the length attribute must be between 1 through 32740 inclusive. Character-String Variables v Fixed-length character-string variables can be used in all host languages except REXX. REXX. which is the number of digits in the fractional part of the number. fixed-length character-string variables are limited to a length of 1. C++. where the absolute value of n is the largest number that can be represented with the applicable precision and scale. COBOL. Varying-Length Character Strings The types of varying-length character strings are: v VARCHAR (or synonyms CHAR VARYING and CHARACTER VARYING) v CLOB (or synonyms CHAR LARGE OBJECT and CHARACTER LARGE OBJECT) The values of a column with any one of these string types can have different lengths. the default decimal separator character in effect when the statement was prepared is used to interpret the string. The length attribute must be between 1 through 32766 inclusive. For a VARCHAR column. and ILE RPG. For a CLOB column. Numeric Host Variables Small and large binary integer variables can be used in all host languages. This is determined by the length attribute of the column. When a string is cast to a decimal or floating-point value (for example. String Representations of Numeric Values When a decimal or floating-point number is cast to a string (for example. The length of the string is the number of bytes in the sequence. Decimal variables can be used in all supported host languages. Floating-point variables can be used in all host languages except RPG/400 and COBOL/400. the value is called the empty string. the length attribute must be between 1 through 2 147 483 647 inclusive. The length attribute of the column determines the maximum length a value can have. The maximum precision is 31 digits. The scale. For more information about CLOBs. Fixed-Length Character Strings All values of a fixed-length character-string column have the same length. Character Strings A character string is a sequence of bytes.) v VARCHAR varying-length character-string variables can be used in C. Big integer variables can only be used in C. PL/I. The empty string should not be confused with the null value.

a CLOB varying-length character string is declared using the SQLTYPE keyword. a mixed data character string is converted before an operation with a character string that has a different CCSID. v CLOB varying-length character-string variables can be defined in all host languages except REXX. the “shift-out” character. Data that may contain a mixture of characters from a single-byte character set (SBCS) and a double-byte character set (DBCS). The CCSID for bit data is 65535. If necessary. The pairing is detected as the string is read from left to right. the double-byte characters must be enclosed between paired shift-out and shift-in characters. varying-length character strings are represented as structures. – In all other languages. In order for the database manager to recognize double-byte characters in a mixed data character string. Each SBCS data character string has an associated CCSID. However. and COBOL/400. an SBCS data character string is converted before it is used in an operation with a character string that has a different CCSID. Language Elements 63 . RPG/400. the following condition must be met: Within the string. The first X'0F' following the X'0E' that is on a double-byte boundary is the paired shift-in character. is used to mark the beginning of a sequence of double-byte codes. If necessary. – In RPG/400. there is a varying-length character-string data type. – In COBOL and C. Any X'0F' that is not on a double-byte boundary is not recognized. an SQL TYPE IS CLOB clause is used. Each mixed data character string has an associated CCSID. Chapter 2. The code X'0E' is recognized as a shift out character if X'0F' occurs later. and it does not assign any specific meaning to particular double-byte codes.Data Types – In PL/I. v X'0F'. – In ILE RPG. Data in which every character is represented by a single byte. There must be an even number of bytes between the paired characters. Character Encoding Schemes Each character string is further defined as one of: Bit data SBCS data Data that is not associated with a coded character set and is never converted. There can be more than one set of paired shift-out and shift-in characters in the string. If mixed data contains a DBCS character. REXX. is used to mark the end of a sequence of double-byte codes. varying-length character-string variables can only be represented by VARCHAR columns included as a result of an externally described data structure. otherwise. and each pair of bytes is considered to be a double-byte character. if you choose to use mixed data. the “shift-in” character. – In C. then two single-byte EBCDIC codes are given special meanings: v X'0E'. Mixed data The database manager does not recognize subclasses of double-byte characters. it cannot be converted to SBCS data. it is invalid. and ILE RPG. varying-length character-string variables can also be represented by NUL-terminated strings.

or an SBCS CCSID is specified. see “Large Objects (LOBs)” on page 65. FOR SBCS DATA. – In C. Like character strings. varying-length graphic-string variables can also be represented by NUL-terminated graphic strings.) Although fixed-length graphic-string host variables cannot be defined in PL/I. COBOL/400. Graphic-String Variables v Fixed-length graphic-string host variables can be defined in C. The length attribute must be between 1 through 16383 inclusive. v Varying-length graphic-string host variables can be defined in C. When the job CCSID indicates that DBCS is allowed. and RPG/400. a character-string host variable will be treated like a varying-length graphic-string host variable if it was generated in the source from a VARGRAPHIC column in the external definition of a file. ILE COBOL. For a definition of a DBCS-Open field. but the system database support will see them as DBCS-Open fields.Data Types The length of a mixed data character string is its total number of bytes. a character-string host variable will be treated like a fixed-length graphic-string host variable if it was generated in the source from a GRAPHIC column in the external definition of a file. unless FOR BIT DATA. The length attribute of the column determines the maximum length a value can have. For a VARGRAPHIC column. counting two bytes for each double-byte character and one byte for each shift-out or shift-in character. CREATE TABLE will create character columns as DBCS-Open fields. – In REXX and ILE RPG. which is determined by the length attribute of the column. Graphic Strings A graphic string is a sequence of two-byte characters. graphic strings can be empty. varying-length graphic strings are represented as structures. Fixed-Length Graphic Strings All values of a fixed-length graphic-string column have the same length. the length attribute must be between 1 through 1 073 741 823 inclusive. there is a varying-length graphic-string data type. ILE COBOL. – Although varying-length graphic-string host variables cannot be defined in PL/I. REXX. and ILE RPG. and ILE RPG/400. The length of the string is the number of its characters. and RPG/400. For a DBCLOB column. Varying-Length Graphic Strings | The types of varying-length graphic strings are: v VARGRAPHIC (or synonym GRAPHIC VARYING) v DBCLOB The values of a column with any one of these string types can have different lengths. see the Database Programming book. The SQL user will see these as character fields. fixed-length graphic-string host variables are limited to a length of 1. COBOL/400. – In C and ILE COBOL. For more information about DBCLOBs. the length attribute must be between 1 through 16370 inclusive. 64 DB2 UDB for iSeries SQL Reference V5R2 . (In C.

a DBCLOB varying-length character string is declared using the SQLTYPE keyword. The CCSID of a DBCLOB cannot be 65535. see “Large Objects (LOBs). the script of a play. For example. Every DBCS graphic string has a CCSID that identifies a double-byte coded character set. such as lengthy documents in UCS-2. For a BLOB column. A binary string has a CCSID of 65535. A CLOB is used to store large SBCS data or mixed data. RPG/400. or the text of novel in a CLOB. and COBOL/400. When graphic-string host variables are not explicitly tagged with a CCSID. the host variable is tagged with 65535. an SQL TYPE IS DBCLOB clause is used. Chapter 2. and COBOL/400. See the DECLARE VARIABLE statement for information on how to tag a graphic host variable with a CCSID. Binary Strings A binary string is a sequence of bytes. RPG/400.” A host variable with a BLOB string type can be defined in all host languages except REXX. A DBCLOB is designed to store large DBCS data. the associated DBCS CCSID for the job CCSID is used. a DBCS graphic string is converted before it is used in an operation with a DBCS graphic string that has a different DBCS CCSID. For more information about BLOBs. you can store information such as an employee resume. If no associated DBCS CCSID exists. – In all other languages. Graphic Encoding Schemes Each graphic string is further defined as DBCS data or UCS-2 data. the length attribute must be between 1 and 2 147 483 647 bytes inclusive. Language Elements 65 . Double-byte Character Large Object (DBCLOB) Strings A Double-Byte Character Large OBject (DBCLOB) is a varying-length graphic string with a maximum length of 1 073 741 823 double-byte characters. DBCS data Data in which every character is represented by a character from the double-byte character set (DBCS) that does not include the shift-out or shift-in characters. The length of a binary string (BLOB string) is the number of bytes in the sequence. A graphic-string host variable is never implicitly tagged with a UCS-2 CCSID. such as lengthy documents. The CCSID of a CLOB cannot be 65535.Data Types v DBCLOB varying-length character-string variables can be defined in all host languages except REXX. If necessary. Large Objects (LOBs) The term large object (LOB) refers to any of the following data types: Character Large Object (CLOB) Strings A Character Large OBject (CLOB) is a varying-length character string with a maximum length of 2 147 483 647. UCS-2 data Data in which every character is represented by a character from the Universal Coded Character Set (UCS-2). – In ILE RPG.

Since a locator host variable itself can never be null. the indicator variable is set to -1. or it could instead select the LOB value into a LOB locator. an application program could select the entire LOB value and place it into an equally large host variable (which is acceptable if the application program is going to process the entire LOB value at once). when a null value is selected into that host variable. LOB locators provide users with a mechanism by which very large objects can be manipulated in application programs without requiring the entire LOB value to be stored in a host variable or transferred to the application requester (client) where the application program may be running. or until the locator is explicitly freed. In the case of LOB locators. The value associated with a locator is valid until the transaction ends. the two data types are not compatible. not a row or location in the database. a negative indicator variable value indicates that the LOB value represented by the LOB locator is null. when selecting a LOB value. signifying that the value is null. 42.the server does not track null values with valid locators. there is no operation that one can perform on the original row or table that will affect the value which is referenced by the locator. The CCSID of a BLOB is 65535. VALUE. voice. for example the amount of data assigned to a client host variable. The null information is kept local to the client by virtue of the indicator variable value -. 66 DB2 UDB for iSeries SQL Reference V5R2 . the application can use a large object locator (LOB locator) to reference the LOB value. Once a value is selected into a locator. or applying UDFs against the LOB) by supplying the locator value as input. A BLOB is designed to store non-traditional data such as pictures. The resulting output of the locator operation. however. LOB locators may also represent more than just base values. searching the LOB with LIKE or POSSTR. For example. Then. whichever comes first. A LOB locator is a host variable with a value that represents a single LOB value in the database server. LENGTH. the meaning of indicator variables is slightly different. the application program can issue subsequent database operations on the LOB value (such as applying the scalar functions SUBSTR. CONCAT. Manipulating Large Objects (LOBs) With Locators When an application does not want an entire LOB value to be moved into a host variable. Although BLOB strings and FOR BIT DATA character strings might be used for similar purposes. A BLOB is considered to be a binary string. For example. It is important to understand that a LOB locator represents a value. they can also represent the value associated with a LOB expression. a LOB locator might represent the value associated with: SUBSTR(lob_value_1 CONCAT lob_value_2 CONCAT lob_value_3. BLOBs can also store structured data for use by distinct types and user-defined functions. would then typically be a small subset of the input LOB value.Data Types Binary Large Object (BLOB) Strings A Binary Large OBject (BLOB) is a varying-length string with a maximum length of 2 147 483 647. doing an assignment. 6000000) For normal host variables in an application program. and mixed media. using the LOB locator. The BLOB function can be used to change a FOR BIT DATA character string into a binary string.

DBCLOB. Note that historical dates do not always follow the Gregorian calendar. which is assumed to have been in effect from the year 1 A. as a result.” on page 165 for the data types that are allowed as input to each function. Datetime Values | | | | Although datetime values can be used in certain arithmetic and string operations and are compatible with certain strings. The range of the month part is 1 to 12. OPEN. See the description of the individual functions in Chapter 3. and day) designating a point in time under the Gregorian calendar16. *MDY. strings can represent datetime values. The range of the year part is 0001 to 9999. or both as input. depending on the month and year. it is not a database type. month. The range of the day part is 1 to x. “Built-In Functions. cannot participate in views or check constraints. Chapter 2. there are SQLTYPEs for LOB locators so that they can be described within an SQLDA structure that is used by FETCH. it is never stored in the database and. where x is 28.Data Types A LOB locator is only a mechanism used to refer to a LOB value during a transaction. or BLOB) Not allowed Not allowed Not allowed Not allowed Not allowed Not allowed Some functions that allow varying-length character strings. or both types of strings as input arguments do not support CLOB or DBCLOB strings. Dates between 1582-10-04 and 1582-10-15 are accepted as valid dates although they never existed in the Gregorian calendar. Limitations on Use of Strings The following varying-length string data types cannot be referenced in certain contexts: v for character strings. and *YMD can only represent dates in the range 1940 through 2039. CALL. and EXECUTE statements. Date A date is a three-part value (year. 30. it does not persist beyond the transaction in which it was created. However. varying-length graphic strings. any BLOB string. 29. Table 4. any CLOB string v for graphic strings. and foreign keys Parameters of built-in functions LOB (CLOB. since a locator is a representation of a LOB type. they are neither strings nor numbers. *DMY. However. or 31. Also. DBCLOB string v for binary strings. Contexts for limitations on use of varying-length strings Context of usage A GROUP BY clause An ORDER BY clause A CREATE INDEX statement A SELECT DISTINCT statement A subselect of a UNION without the ALL keyword The definition of primary. unique.D. The date formats *JUL. see “String Representations of Datetime Values” on page 68. 16. Language Elements 67 .

The integer (called the Scaliger number) represents the date. The length of a TIME column as described in the SQLDA is 8 bytes. time. The internal representation of a timestamp is a string of 10 bytes. However. and timestamp host variables can also be specified in Java as java. the string representation is converted to the internal form of the date. The length of a TIMESTAMP column as described in the SQLDA is 26 bytes.Data Types The internal representation of a date is a string of 4 bytes that contains an integer. or 10 bytes. To be retrieved. Timestamp A timestamp is a seven-part value (year. If the hour is 24. month. a datetime value can be assigned to a character-string variable. ASCII). The format of the resulting string will depend on the default date format and the default time format in effect when the statement was prepared. the next 3 bytes the time. TIME. If the CCSID of the string represents a foreign encoding scheme (for example. which is the appropriate length for the character-string representation of the value. The first 4 bytes represent the date. and the last 3 bytes the microseconds (the last 3 bytes contain 6 packed digits). and timestamp host variables can also be specified in ILE COBOL and ILE RPG. day.Time. time. TIME.sql. 8. or TIMESTAMP are represented in an internal form that is transparent to the user of SQL. while the range of the minute and second parts is 0 to 59. java. These representations directly concern the user of SQL since there are no constants whose data types are DATE. however. Each byte consists of two packed decimal digits. the minute and second specifications are both zero.Date. or timestamp before the operation is performed. Time A time is a three-part value (hour. it 68 DB2 UDB for iSeries SQL Reference V5R2 . which is the appropriate length for a character-string representation of the value. The default date and time formats is set based on the date format (DATFMT). Dates. The internal representation of a time is a string of 3 bytes. and the last byte the second. and timestamp values. Only ILE RPG and ILE COBOL support datetime variables. When a valid string representation of a datetime value is used in an operation with an internal datetime value. and timestamps. and microsecond) that designates a date and time as defined previously. The range of the hour part is 0 to 24. except that the time includes a fractional specification of microseconds. The first byte represents the hour. minute. and the time separator (TIMSEP) parameters. times. the time format (TIMFMT). time. hour. These are the appropriate lengths for character-string representations for the value. time. the date separator (DATSEP).sql.Timestamp respectively. depending on which format is used.sql. second. can also be represented by character or UCS-2 graphic strings. or TIMESTAMP. Date. minute. the second byte the minute. date. and second) designating a time of day using a 24-hour clock. | | | | | | Datetime Host Variables Character string host variables are normally used to contain date. and java. The length of a DATE column as described in the SQLDA is 6. String Representations of Datetime Values Values whose data types are DATE.

year (*MDY) Day.1987 1987-10-12 1987285 87/285 10/12/87 12/10/87 87/12/10 Japanese industrial standard JIS Christian era (*JIS) Unformatted Julian Julian (*JUL) Month. The SET OPTION statement can also be used to specify the DATFMT and DATSEP parameters within the source of a program containing embedded SQL. The database manager recognizes the string as a date when it is either: | v In the format specified by the default date format. month. day (*YMD) – – – – – | | | | | | | | | | | The default date format can be specified through the following interfaces: Table 6. Trailing blanks can be included. Other formats do not have an abbreviation to be used by the CHAR function. or v In one of the IBM SQL standard date formats. Each IBM SQL standard format is identified by name and includes an associated abbreviation (for use by the CHAR function).) Chapter 2. The separators for two-digit year formats are controlled by the date separator (DATSEP) parameter. or v In the unformatted Julian format Table 5. Language Elements 69 .10. see the SQL Programming with Host Languages book. Leading zeros can be omitted from the month and day portions when using the IBM SQL standard formats. Default Date Format Interfaces SQL Interface Embedded SQL Specification The DATFMT and DATSEP parameters are specified on the Create SQL Program (CRTSQLxxx) commands. day. year (*DMY) Year. The following sections define the valid string representations of datetime values.yyyy yyyy-mm-dd yyyyddd yy/ddd mm/dd/yy dd/mm/yy yy/mm/dd Example 1987-10-12 10/12/1987 12. month. Date Strings: A string representation of a date is a character string that starts with a digit and has a length of at least 6 characters.mm. Valid string formats for dates are listed in Table 5. (For more information about CRTSQLxxx commands.Data Types is first converted to the coded character set identified by the default CCSID before the string is converted to the internal form of the datetime value. Formats for String Representations of Dates Format Name International Standards Organization (*ISO) IBM USA standard (*USA) IBM European standard (*EUR) Abbreviation ISO USA EUR Date Format yyyy-mm-dd mm/dd/yyyy dd.

The other format (*HMS) does not have an abbreviation to be used by the CHAR function.) Date Format and Date Separator in the Advanced Server Options in ODBC Setup (For more information about ODBC. see the SQL Call Level Interfaces (ODBC) book. Table 7. a leading zero can be omitted from the hour part of the time and seconds can be omitted entirely. The database manager recognizes the string as a time when it is either: v In the format specified by the default time format.) SQL_ATTR_DATE_FMT and SQL_ATTR_DATE_SEP environment or connection variables (For more information about CLI. and STRSQL commands. see IBM Toolbox for Java topic in the iSeries Information Center .) Date Format and Date Separator connection property (For more information about JDBC and SQLJ.) (For more information about the IBM Toolbox for Java.Data Types | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 6.00. (For more information about STRSQL and RUNSQLSTM commands.) Format in JDBC Setup (For more information about ODBC.30. see the IBM Developer Kit for Java topic in the iSeries Information Center.05 70 DB2 UDB for iSeries SQL Reference V5R2 . RUNSQLSTM. see the iSeries Access category in the iSeries Information Center.ss 17 | Example 13. Each IBM SQL standard format is identified by name and includes an associated abbreviation (for use by the CHAR function). The DATFMT and DATSEP parameters on the Run SQL Statements (RUNSQLSTM) command. see the SQL Programming Concepts book. 13.mm. If you choose to omit seconds. The separator for the *HMS format is controlled by the time separator (TIMSEP) parameter.30 is equivalent to 13. an implicit specification of 0 seconds is assumed. or v In one of the IBM SQL standard time formats The TIMFMT and TIMSEP parameters are specified on the CRTSQLxxx. Formats for String Representations of Times Format Name International Standards Organization (*ISO) Abbreviation ISO Time Format hh. Default Date Format Interfaces (continued) SQL Interface Interactive SQL and Run SQL Statements Specification The DATFMT and DATSEP parameters on the Start SQL (STRSQL) command or by changing the session attributes.) Call Level Interface (CLI) on the server JDBC or SQLJ on the server using Developer Kit for Java ODBC on a client using the iSeries Access ODBC Driver JDBC on a client using the IBM Toolbox for Java Time Strings: A string representation of a time is a character string that starts with a digit and has a length of at least 4 characters. see the iSeries Access category in the iSeries Information Center. Thus. Trailing blanks can be included. The SET OPTION statement can be used to specify TIMFMT and TIMSEP within the source of a program containing embedded SQL.30. Valid string formats for times are listed in Table 7.

59.30. the hour must not be greater than 12 and cannot be 0 except for the special case of 00:00 AM.59.) SQL_ATTR_TIME_FMT and SQL_ATTR_TIME_SEP environment or connection variables (For more information about CLI.00 12:00. a single space character exists between the minutes portion of the time of day and the AM or PM. This is an earlier version of the ISO format.00 In the USA format. The TIMFMT and TIMSEP parameters on the Run SQL Statements (RUNSQLSTM) command.Data Types Table 7.01. (For more information about STRSQL and RUNSQLSTM commands. (For more information about CRTSQLxxx commands.mm. | | | | | | | | | | | | | | | | | | | | | | The default time format can be specified through the following interfaces: Table 9. Language Elements 71 . seconds (*HMS) – In the USA time format.05 13:30:05 13:30:05 Japanese industrial standard JIS Christian era (*JIS) Hours.) The TIMFMT and TIMSEP parameters on the Start SQL (STRSQL) command or by changing the session attributes. The SET OPTION statement can also be used to specify the TIMFMT and TIMSEP parameters within the source of a program containing embedded SQL.00 24. Formats for String Representations of Times (continued) Format Name IBM USA standard (*USA) IBM European standard (*EUR) Abbreviation USA EUR Time Format hh:mm AM or PM hh. Default Time Format Interfaces SQL Interface Embedded SQL Specification The TIMFMT and TIMSEP parameters are specified on the Create SQL Program (CRTSQLxxx) commands.) Interactive SQL and Run SQL Statements Call Level Interface (CLI) on the server 17.00.00 through 23. the correspondence between the USA format and the 24-hour clock is as follows: Table 8. minutes. JIS can be used to get the current ISO format.00.00 through 00. USA Time Format USA Format 12:01 AM through 11:59 AM 01:00 AM through 11:59 AM 12:00 PM (noon) through 11:59 PM 12:00 AM (midnight) 00:00 AM (midnight) 24-Hour Clock 00. Using the 24-hour clock.00 through 11:59.00 01:00. see the SQL Programming with Host Languages book.ss hh:mm:ss hh:mm:ss Example 1:30 PM 13. Chapter 2. see the SQL Call Level Interfaces (ODBC) book. see the SQL Programming Concepts book.00 00.

ss. DataLink Values A DataLink value is an encapsulated value that contains a logical reference from the database to a file stored outside the database.) Time Format and Time Separator in the Advanced Server Options in ODBC Setup (For more information about ODBC. this is a value such as HTTP or FILE. see IBM Toolbox for Java topic in the iSeries Information Center . It is generated dynamically and is not a permanent part of the DataLink value that is stored in the database.00. A timestamp whose time part is 24. and hour part of the timestamp when using the timestamp form with separators. no matter what case it is entered in. an implicit specification of 0 is assumed.100000.) Format in JDBC Setup (For more information about ODBC. Leading zeros can be omitted from the month. 1990-3-2-8. The attributes of this encapsulated value are as follows: link type The currently supported type of link is a URL (Uniform Resource Locator). see the IBM Developer Kit for Java topic in the iSeries Information Center. The value. is stored in the database in upper case. The value is case sensitive and therefore it is not converted to upper case when stored in the database.00.00.) (For more information about the IBM Toolbox for Java. access control token When appropriate. see the iSeries Access category in the iSeries Information Center. file path The identity of the file within the server.10 is equivalent to 1990-03-02-08.) ODBC on a client using the iSeries Access ODBC Driver JDBC on a client using the IBM Toolbox for Java Timestamp Strings: A string representation of a timestamp is a character string that starts with a digit and has a length of at least 16 characters. file server name The complete address of the file server.000000 is also accepted.00. The value. The complete string representation of a timestamp has the form yyyy-mm-dd-hh. the access token is embedded within the file path.30.Data Types | | | | | | | | | | | | | | | | | | | Table 9.mm. Trailing blanks can be included. 72 DB2 UDB for iSeries SQL Reference V5R2 . day. Thus. Trailing zeros can be truncated or omitted entirely from microseconds.30. is stored in the database in upper case. see the iSeries Access category in the iSeries Information Center. Default Time Format Interfaces (continued) SQL Interface JDBC or SQLJ on the server using Developer Kit for Java Specification Time Format and Time Separator connection property object (For more information about JDBC and SQLJ. If you choose to omit any digit of the microseconds portion. no matter what case it is entered in. scheme For URLs.nnnnnn or yyyymmddhhmmss.

″. #. :. The database manager maintains the values permanently. @. ’.Data Types comment Up to 254 bytes of descriptive information. The internal representation of a row ID value is transparent to the user. If a value is supplied. It is possible for a DataLink value to have only a comment attribute and no linkage attributes. The length attribute of a ROWID column is 40. A distinct type is created with the SQL statement CREATE DISTINCT TYPE. The first four attributes are collectively known as the linkage attributes. a text type. DLURLCOMPLETE. the database manager generates a value for the ROWID column unless one is supplied. but is considered to be a separate and incompatible type for most operations. | | | | | | | | | | | | Row ID Values A row ID is a value that uniquely identifies a row in a table. The similarity is that they both contain a representation of a file. DLURLPATH. DLURLSCHEME. space. However: v DataLinks are retained in the database and both the links and the data in the linked files can be considered as a natural extension of data in the database. /. These characters include the uppercase (A through Z) and lower case (a through z) letters. the semantics for a picture type. For example. *. For example. A ROWID column enables queries to be written that navigate directly to a row in the table. Built-in scalar functions are provided to build a DataLink value (DLVALUE) and to extract the encapsulated values from a DataLink value (DLCOMMENT. even across table reorganizations. and an audio type that all use the built-in data type BLOB for their internal representation are quite different. . DLLINKTYPE. When a row is inserted into the table. =. ). A column or a host variable can have a row ID data type. of course. &. the following statement creates a distinct type named AUDIO: CREATE DISTINCT TYPE AUDIO AS BLOB (1M) Chapter 2. DLURLPATHONLY. it must be a valid row ID value that was previously generated by either DB2 UDB for OS/390 and z/OS or DB2 UDB for iSeries.. Each value in a ROWID column must be unique. v File reference variables exist temporarily and they can be considered as an alternative to a host program buffer. Language Elements 73 . -.. no file will be linked to such a column. User-Defined Types Distinct Types A distinct type is a user-defined data type that shares its internal representation with a built-in data type (its ″source type″). !. The value is never subject to CCSID conversion because it is considered to contain BIT data. The characters used in a DataLink value are limited to the set defined for a URL. It is important to distinguish between these DataLink references to files and the LOB file reference variables described in “References to LOB File Reference Variables” on page 119. ?. (. +. . the digits (0 through 9) and a subset of special characters ($. Such a value may even be stored in a column but. DLURLSERVER). and comma). This is intended for application specific uses such as further or alternative identification of the location of the data. _.

a table with a ROWID column cannot also have a column with distinct type that is sourced on a row ID. COMMISSION) FROM SALARY_TABLE | | | A distinct type is subject to the same restrictions as its source type. Strong typing ensures that only the functions and operators that are explicitly defined for a distinct type can be applied to that distinct type. or REVOKE statement. The user-defined function must be sourced on the existing function that has the source type as a parameter. distinct types support strong typing. the database manager uses the SQL path to determine the schema name.2). except for distinct types that are sourced on a DataLink. COMMISSION MONEY) SELECT "+"(SALARY. for the AUDIO type created above.2)) CREATE TABLE SALARY_TABLE (SALARY MONEY. COMMENT. Specific. the database manager uses the normal process of qualification by authorization ID to determine the schema name. The comparison operators are automatically generated for distinct types. a table can only have one ROWID column. If an unqualified distinct type name is used: v In a CREATE DISTINCT TYPE or the object of DROP.2).2) WITH COMPARISONS CREATE FUNCTION "+"(MONEY. v In any other context. and how the operator might be applied to the distinct type: CREATE DISTINCT TYPE AUDIO AS BLOB (1M) CREATE DISTINCT TYPE MONEY AS DECIMAL(9. in sequence. For example. and Distinct Type Names” on page 54. GRANT. Therefore. these are the generated cast functions: Name of generated cast function schema-name. how to define the + operator for the distinct type.Data Types Although AUDIO has the same representation as the built-in data type BLOB. For a description of the SQL path.AUDIO Returns data type BLOB 74 DB2 UDB for iSeries SQL Reference V5R2 . CURRENT_PATH.MONEY) RETURNS MONEY SOURCE "+"(DECIMAL(9. the following series of SQL statements shows how to create a distinct type named MONEY based on data type DECIMAL(9. The database manager searches the schemas in the path.DECIMAL(9. Procedure. see “CURRENT PATH. since these may not be meaningful. However. The name of a distinct type is qualified with a schema name. The implicit schema name for an unqualified name depends upon the context in which the distinct type appears. the database manager automatically generates functions for a distinct type that support casting from the source type to the distinct type and from the distinct type to the source type. it is considered to be a separate type that is not comparable to a BLOB or to any other type. For example. For example. and selects the first schema that has a distinct type that matches. For more information about qualification rules. A distinct type does not automatically acquire the functions and operators of its source type. see “Unqualified Function. or CURRENT FUNCTION PATH” on page 106.BLOB Parameter list schema-name. the LENGTH function of the AUDIO type might return the length of its object in seconds rather than in bytes. a function or operator of the source type can be applied to the distinct type by creating an appropriate user-defined function.) Instead. (For example. In addition. This inability to compare AUDIO to other data types allows functions to be created specifically for AUDIO and assures that these functions cannot be applied to other data types.

Language Elements 75 .Data Types Name of generated cast function schema-name.AUDIO Chapter 2.AUDIO Parameter list BLOB Returns data type schema-name.

real. an order of precedence exists in which one data type is considered to precede another data type. CLOB or DBCLOB VARCHAR or VARGRAPHIC. Table 10. double decimal. The database manager considers the promotion of data types when: v Performing function resolution (see “Function resolution” on page 125) v Casting distinct types (see “Casting Between Data Types” on page 78) v Assigning distinct types to built-in data types (see “Distinct Type Assignments” on page 88) For each data type. double INTEGER. double double CHAR or GRAPHIC. decimal. decimal. BIGINT. This precedence enables the database manager to support the promotion of one data type to another data type that appears later in the precedence order. For example. CLOB or DBCLOB CLOB or DBCLOB BLOB DATE TIME TIMESTAMP DATALINK ROWID udt (same name) | ROWID udt 76 DB2 UDB for iSeries SQL Reference V5R2 . the database manager cannot promote a CLOB to a VARCHAR. Within such groups. The table indicates that the best choice is the same data type and not promotion to another data type. VARCHAR or VARGRAPHIC. decimal. Table 10 shows the precedence list (in order) that the database manager uses to determine the data types to which each data type can be promoted. Note that the table also shows data types that are considered equivalent during the promotion process. double real. real. Data Type Precedence Table Data Type SMALLINT INTEGER BIGINT decimal real double CHAR or GRAPHIC VARCHAR or VARGRAPHIC CLOB or DBCLOB BLOB DATE TIME TIMESTAMP DATALINK Data Type Precedence List (in best-to-worst order) SMALLINT. real. however. double BIGINT. BIGINT. For example. INTEGER.Promotion of Data Types Promotion of Data Types Data types can be classified into groups of related data types. CHARACTER and GRAPHIC are considered to be equivalent data types. the database manager can promote the data type CHAR to VARCHAR and the data type INTEGER to DOUBLE PRECISION. real.

Character and graphic strings are only compatible for Unicode data.s) real = REAL or FLOAT(n) where n is a specification for single precision floating point Data Type Precedence List (in best-to-worst order) double = DOUBLE. Language Elements 77 .Promotion of Data Types Table 10. Data Type Precedence Table (continued) Data Type Note: The lower case types above are defined as follows: decimal = DECIMAL(p. DOUBLE PRECISION.s) or NUMERIC(p. Chapter 2. FLOAT or FLOAT(n) where n is a specification for double precision floating point udt = a user-defined type Shorter and longer form synonyms of the data types listed are considered to be the same as the synonym listed.

Distinct type DT Source data type of distinct type DT Distinct type DT Data type A INTEGER DOUBLE VARCHAR VARGRAPHIC Is Castable to Data Type . in a CAST specification. The following table describes the supported casts between built-in data types.. the database manager resolves the schema name of the distinct type and then uses that schema name to locate the cast function. However. The database manager might implicitly cast data types during assignments that involve a distinct type (see “Distinct Type Assignments” on page 88). See the description preceding the table for information on supported casts involving user-defined types. a cast function that was generated when the distinct type was created is used. For details. precision. and “CAST Specification” on page 144. Source data type of distinct type DT Distinct type DT Distinct type DT Distinct type DT where A is promotable to the source data type of distinct type DT (see “Promotion of Data Types” on page 76) Distinct type DT if DT’s source type is SMALLINT Distinct type DT if DT’s source data type is REAL Distinct type DT if DT’s source data type is CHAR or GRAPHIC Distinct type DT if DT’s source data type is GRAPHIC or CHAR When a distinct type is involved in a cast. Supported Casts When a Distinct Type is Involved Data Type . You can use cast functions or CAST specifications to explicitly cast a data type. A data type that can be changed to another data type is castable from the source data type to the target data type. see “Function resolution” on page 125.. when an unqualified distinct type is specified as the target data type.. the data types of the parameters of the source function must be castable to the data types of the function that you are creating (see “CREATE FUNCTION (Sourced)” on page 470). In addition. 78 DB2 UDB for iSeries SQL Reference V5R2 . For casts between built-in data types. is one example of when a value with one data type needs to be cast to a new data type. Table 11. Data type promotion. The casting of one data type to another can occur implicitly or explicitly. as described in “Promotion of Data Types” on page 76.Casting Between Data Types Casting Between Data Types There are many occasions when a value with a given data type needs to be cast (changed) to a different data type or to the same data type with a different length. Function resolution is used for both. a warning occurs if any non-blank characters are truncated. when you create a sourced user-defined function. How the database manager chooses the function depends on whether function notation or the CAST specification syntax is used.. This truncation behavior is similar to retrieval assignment of character or graphic strings (see “Retrieval Assignment” on page 84). For casts that involve a distinct type as either the data type to be cast to or from. Table 11 shows the supported casts. Table 12 on page 79 shows the supported casts. or scale. If truncation occurs when a character or graphic string is cast to another data type.

Casting Between Data Types Table 12. Only a DATALINK can be cast to a DATALINK type. or ROWID to CLOB is not supported. The following table describes the rules for casting to a data type: Chapter 2. TIME. TIMESTAMP. Language Elements 79 . | ** Casting from DATE. Supported Casts Between Built-In Data Types | | Source Data Type SMALLINT INTEGER BIGINT DECIMAL NUMERIC REAL DOUBLE CHAR VARCHAR CLOB GRAPHIC SMALLINT CHAR GRAPHIC INTEGER DECIMAL REAL VARCHAR VARGRAPHIC TIME BIGINT NUMERIC DOUBLE CLOB DBCLOB BLOB DATE TIME STAMP Y Y Y Y Y Y Y Y Y Y — Y Y Y Y Y Y Y Y Y Y — — — — — — — — Y Y Y Y Y Y Y Y Y Y — — — — — — — — Y Y Y Y Y Y Y Y Y Y Y* Y* Y* — Y** Y** Y** Y — — — — — — — * * * Y Y Y — — — — — — — — — — — — Y Y Y Y Y Y Y — — — Y — — — — — — — Y Y — — — — — Y — Y — — — — — — — — Y Y — — — — — — Y Y — — — — — — — — Y Y — — — — — Y Y Y — ROW ID — — — — — — — Y Y — — — — — — — — Y VARGRAPHIC— DBCLOB BLOB DATE TIME — — — — TIMESTAMP — | ROWID — Notes: * Conversion is only supported for UCS-2 graphic.

See the ROWID scalar function. See the REAL scalar function.Casting Between Data Types Table 13. See the TIME scalar function. See the BIGINT scalar function. Rules for Casting to a Data Type Target Data Type SMALLINT INTEGER BIGINT DECIMAL NUMERIC REAL DOUBLE CHAR VARCHAR CLOB GRAPHIC VARGRAPHIC DBCLOB BLOB DATE TIME TIMESTAMP TIMESTAMP TIMESTAMP DATALINK Source Data Type Any Any Any Any Any Any Any Any Any Any Any Any Any Any Any Any CHAR DATE TIME DATALINK Any Rules See the SMALLINT scalar function. See the DECIMAL scalar function. See the INTEGER scalar function. See the CLOB scalar function. See the rules for DataLink assignments. See the DATE scalar function. where one operand is specified. The timestamp is composed of the CURRENT_DATE and the specified time. | ROWID 80 DB2 UDB for iSeries SQL Reference V5R2 . See the BLOB scalar function. The timestamp is composed of the specified date and a time of 00:00:00. See the rules for string assignment to a host variable. See the rules for string assignment to a host variable. See the ZONED scalar function. See the VARCHAR scalar function. See the TIMESTAMP scalar function. See the DBCLOB scalar function. See the CHAR scalar function. See the DOUBLE scalar function.

INSERT. and ORDER BY. and MAX scalar functions. UPDATE. concatenation. CASE expressions.Assignments and Comparisons Assignments and Comparisons The basic operations of SQL are assignment and comparison. VALUE. The basic rule for both operations is that the data type of the operands involved must be compatible. FETCH. and VALUES INTO statements. GROUP BY. MIN. Comparison operations are performed during the execution of statements that include predicates and other language elements such as MAX. The compatibility rule also applies to UNION. DISTINCT. IFNULL. Assignment operations are performed during the execution of CALL. SELECT. The compatibility matrix is as follows: Chapter 2. COALESCE. Language Elements 81 . MIN. SET variable. and the CONCAT.

For additional information. compared with a time.Assignments and Comparisons Table 14. COALESCE. 4. and MAX scalar functions. or used in a VALUE. COALESCE. compared with a timestamp. or MAX scalar function with a time. IFNULL. The DLCOMMENT. COALESCE. The compatibility of datetime values and character strings is limited to assignment. or MAX scalar function with a timestamp. or used in a VALUE. A DATALINK operand can only be assigned to another DATALINK operand. IFNULL. are not compatible with binary strings. v A valid string representation of a timestamp can be assigned to a timestamp column. Bit data and graphic strings are not compatible. v A valid string representation of a time can be assigned to a time column. DLURLSCHEME. Data Type Compatibility Binary Operands Integer Binary Integer Decimal Number Floating Point Character String Graphic String Binary String Date Time Timestamp Distinct Type Notes: 1. 82 DB2 UDB for iSeries SQL Reference V5R2 . IFNULL. A DATALINK operand can not be directly compared to any data type. and the VALUE. DLURLCOMPLETE. v Datetime values can be assigned to character-string columns and to character-string variables as explained in “Datetime Assignments” on page 86. v A valid string representation of a date can be assigned to a date column. A ROWID operand can only be assigned to another ROWID operand. DLLINKTYPE. The DATALINK value can only be assigned to a column if the column is defined with NO LINK CONTROL or the file exists and is not already under file link control. 2. DLURLPATHONLY. 5. All character strings. MIN. MIN. MIN. 3. comparison. A value with a distinct type is comparable only to a value that is defined with the same distinct type. Decimal refers to both packed and zoned decimal. IFNULL. nor to a host variable that does not have an associated indicator variable. or used in a VALUE. COALESCE. 6. See “References to Host Variables” on page 115 for a discussion of indicator variables. Yes Yes Yes No No No No No No 2 Decimal Floating Character Graphic Number4 Point String String Yes Yes Yes No No No No No No 2 Yes Yes Yes No No No No No No 2 No No No Yes Yes 5 No 3 1 1 1 2 No No No Yes 5 Yes No No No No 2 Binary String No No No No 3 No Yes No No No 2 Date No No No 1 No No Yes No No 2 Time Timestamp No No No 1 No No No Yes No 2 No No No 1 No No No No Yes 2 Distinct Type 2 2 2 2 2 2 2 2 2 2 | 7. or MAX scalar function with a date. MIN. even those with FOR BIT DATA. A basic rule for assignment operations is that a null value cannot be assigned to a column that cannot contain null values. and DLURLSERVER scalar functions can be used to extract character string values from a datalink which can then be compared to other strings. In general. see “Distinct Type Assignments” on page 88. compared with a date. the database manager supports assignments between a distinct type value and its source data type. DLURLPATH.

The necessary number of leading zeros is added or eliminated. if necessary. The necessary number of leading zeros is added or eliminated. Note: When fetching decimal data from a file that was not created by an SQL CREATE TABLE statement. in the fractional part of the number. Hence. In this case. the number is not assigned to the host variable and the indicator variable is set to negative 2. if necessary. the necessary number of trailing zeros is added.0 for a small integer. the precision of the temporary decimal number is 5. the number is converted first to a temporary decimal number and then. If the scale of the integer is zero. the fractional part of a decimal number is truncated. If the scale of the target is zero. a decimal field may contain data that is not valid. Language Elements 83 . or the necessary number of trailing digits is eliminated. the result may not be identical to the original number. to the precision and scale of the target. if necessary. in the fractional part of the number.Assignments and Comparisons Numeric Assignments The basic rule for numeric assignments is that the whole part of a decimal or integer number cannot be truncated. Floating-Point or Decimal to Integer When a decimal or floating-point number is assigned to a binary integer column or variable. Note: Decimal refers to both packed and zoned decimal. If necessary. In this case. to the precision and the scale of the target. An error occurs if: v Truncation of the whole part of the number occurs on assignment to a column v Truncation of the whole part of the number occurs on assignment to a host variable that does not have an indicator variable A warning occurs if: Truncation of the whole part of the number occurs on assignment to a host variable with an indicator variable. a positive value may be returned in the SQLCODE. and. the data will be returned as stored. the number is converted. In the case of the assignment to a host variable. A table that is created by the SQL CREATE TABLE statement does not allow decimal data that is not valid. Decimal to Decimal When a decimal number is assigned to a decimal column or variable. The approximation is more accurate if the receiving column or variable is defined as double precision (64 bits) rather than single precision (32 bits). or the necessary number of trailing digits is eliminated. to the precision and the scale of the target.0 for a large integer. the fractional part of the number is lost. 11. the necessary number of trailing zeros is added. the number is converted.0 for a big integer. and. Chapter 2. or 19. without any warning or error message being issued. when a decimal or integer number is assigned to a floating-point column or variable. Decimal or Integer to Floating-Point Floating-point numbers are approximations of real numbers. Integer to Decimal When an integer is assigned to a decimal column or variable.

the value placed in the COBOL data item or RPG field may be larger than the maximum precision specified for the host variable. String Assignments There are two types of string assignments: v Storage assignment is when a value is assigned to a column or a parameter of a function or stored procedure. “SQL Communication Area. When this occurs. As a result.” on page 825. result in the value 12345 being placed in A. In COBOL. When a string of length n is assigned to a varying-length string variable with a maximum length greater than n. results in 2345 being placed in A. Thus. assignment to integer host variables uses the full size of the integer.5*10─31 is reduced to 0. the number is rounded (using floating-point arithmetic) to a precision of 31 decimal digits. the statements: 01 A PIC S9999 BINARY. even though A has been defined with only 4 digits. 84 DB2 UDB for iSeries SQL Reference V5R2 . if necessary. the string is truncated on the right by the necessary number of characters. v Retrieval assignment is when a value is assigned to a host variable. Notice that the following COBOL statement: MOVE 12345 TO A. Retrieval Assignment: The length of a string assigned to a host variable can be greater than the length attribute of the host variable. the bytes after the nth byte of the variable are undefined. the value 'W' is assigned to the SQLWARN1 field of the SQLCA. for example. For a description of the SQLCA. In this conversion. truncated to the precision and scale of the target. if COL1 contains a value of 12345. Binary String Assignments Storage Assignment: The basic rule is that the length of a string assigned to a column or parameter of a function or procedure must not be greater than the length attribute of the column or parameter.Assignments and Comparisons Floating-Point to Decimal When a floating-point number is assigned to a decimal column or variable. When a string is assigned to a variable and the string is longer than the length attribute of the variable. However. To COBOL and RPG Integers Assignment to COBOL and RPG small or large integer host variables takes into account any scale specified for the host variable. the number is first converted to a temporary decimal number of precision 31 and then. The scale is given the largest possible value that allows the whole part of the number to be represented without loss of significance. a number less than 0. a negative SQLCODE is returned. EXEC SQL SELECT COL1 INTO :A FROM TABLEX END-EXEC. see Appendix B. If the string is longer than the length attribute of that column.

see “Distinct Type Assignments” on page 88. The database manager pads with the blank at code point X’0020’.Assignments and Comparisons Character and Graphic String Assignments The following rules apply when both the source and the target are strings. see “Datetime Assignments” on page 86. When a string of length n is assigned to a varying-length string variable with a maximum length greater than n. a negative SQLCODE is returned.18 The pad character is always a blank. even for bit data. Chapter 2. Retrieval Assignment: The length of a string assigned to a host variable can be greater than the length attribute of the host variable. it is set to the original length of the string. Assignments Involving C NUL-terminated Strings: When a string of length n is assigned to a C NUL-terminated string variable with a length greater than n+1: v If the *CNULRQD option was specified on the CRTSQLCI or CRTSQLCPPI command (or CNULRQD(*YES) on the SET OPTION statement). When a datetime data type is involved. If only the NUL-terminator is truncated for a C NUL-terminated host variable and the *NOCNULRQD option was specified on the CRTSQLCI or CRTSQLCPPI command (or CNULRQD(*NO) on the SET OPTION statement). For storage assignments. the value 'W' is assigned to the SQLWARN1 field of the SQLCA. When a string is assigned to a variable and the string is longer than the length attribute of the variable. there is always an even number of bytes between each shift-out character and its matching shift-in character. or UCS-2 blanks. the assignment rules may require truncation within a sequence of double-byte codes. To prevent the loss of the shift-in character that ends the double-byte sequence. see Appendix B. and a shift-in character added.” on page 825. “SQL Communication Area. double-byte. the string is padded on the right with the necessary number of single-byte. however. if an indicator variable is provided. the characters after the nth character of the variable are undefined. Assignments Involving Mixed Strings: If a string contains mixed data. When a string is assigned to a fixed-length string column or parameter and the length of the string is less than the length attribute of the target. the string is truncated on the right by the necessary number of characters. especially to a host variable.) For a description of the SQLCA. double-byte. even for bit data. the string is padded on the right with the necessary number of single-byte. the value of 'N' is assigned to the SQLWARN1 field of the SQLCA and a NUL is not placed in the variable. the string is 18. additional characters may be truncated from the end of the string. UCS-2 defines a blank character at code point X’0020’ and X’3000’. trailing blanks are not included in the length of the string.18 The pad character is always a blank. or UCS-2 blanks. Storage Assignment: The basic rule is that the length of a string assigned to a column or parameter of a function or procedure must not be greater than the length attribute of the column or parameter. In the truncated result. For the special considerations that apply when a distinct type is involved in an assignment. (Trailing blanks are normally included in the length of the string. Furthermore. Language Elements 85 . When this occurs. If the string is longer than the length attribute of that column. When a string is assigned to a fixed-length variable and the length of the string is less than the length attribute of the target.

A date can only be assigned to a DATE column. v If the target is a character-string column. a character-string variable or an ILE RPG/400 timestamp variable. a character-string variable or an ILE RPG/400 timestamp variable. a character-string column.Assignments and Comparisons padded on the right with x-n-1 blanks where x is the length of the variable. time. The required length of the target varies depending on the format of the string representation. Datetime Assignments A value assigned to a DATE column must be a date or a valid string representation of a date. a character-string column. Leading zeros are not omitted from any part of the date. When a datetime value is assigned to a character-string variable or column. v The string is neither null nor empty. The padded string is then assigned to the variable and the NUL-terminator is placed in the next character position. For example. A warning occurs if: v A character of the string is converted to the substitution character. the string is not assigned to the host variable and the indicator variable is set to −2. the string is not padded on the right. The following rules apply: DATE 86 DB2 UDB for iSeries SQL Reference V5R2 . v If the *NOCNULRQD precompiler option was specified on the CRTSQLCI or CRTSQLCPPI command (or CNULRQD(*NO) on the SET OPTION statement). it is converted to its string representation. A value assigned to a TIMESTAMP column must be a timestamp or a valid string representation of a timestamp. a double-byte character (DBCS) cannot be converted to a column or host variable with a single-byte character (SBCS) CCSID. and the operation is assignment to a column or assignment to a host variable without an indicator variable. Character conversion is necessary only if all of the following are true: v The CCSIDs are different. it is padded on the right with blanks. A value assigned to a TIME column must be a time or a valid string representation of a time. the result depends on the type of datetime value involved and on the type of target. v A character of the string cannot be converted. a character-string variable or an ILE RPG/400 timestamp variable. The string is assigned to the variable and the NUL-terminator is placed in the next character position. A time can only be assigned to a TIME column. or timestamp. a DBCS character cannot be converted to a host variable with an SBCS CCSID. if necessary. and the operation is assignment to a host variable with an indicator variable. For example. In this case. v A character of the string cannot be converted. If the length of the target is less than required. An error occurs if: v The CCSID Conversion Selection Table is used but does not contain any information about the pair of CCSIDs. a character-string column. If the length of the target is greater than required. v The CCSID Conversion Selection Table indicates that conversion is necessary. truncation is not allowed. A timestamp can only be assigned to a TIMESTAMP column. Conversion Rules for Assignments: A string assigned to a column or host variable is first converted. to the coded character set of the target. v Neither CCSID is 65535.

the seconds part of the time is omitted from the result. When assigning a value to a DataLink column. – If the *ISO. In this case. *JIS. TIMESTAMP The length of the host variable must not be less than 19. The DLVALUE scalar function creates a new DataLink value which can then be assigned a column. *MDY. or *JIS. the length of the host variable must be at least 8. There are two reasons that this might be done: v the comment is being changed v if the table is placed in link pending state. blank padding occurs so that the value is a valid string representation of a time. or *DMY. v When the target is a host variable. the length of the host variable must not be less than 8. If the length is 5. the length of the host variable must be at least 6. USA. If the date format is *YMD. Assigning a null value where a linked value already exists also unlinks the file associated with the old value. 6. If the date format is *JUL. If the date format is *YMD. the seconds part of the time is assigned to the indicator variable if one is provided. or *HMS time format is used. *EUR. Language Elements 87 . or 7. In cases where a linked value already exists in the column. TIMESTAMP The length attribute of the column must be at least 26. If the date format is *JUL. *USA. the length of the host variable must be at least 6. TIME The length attribute of the column must be at least 8. the link is retained. and. the act of assignment will link the file. *EUR. DataLink Assignments The assignment of a value to a DataLink column results in the establishment of a link to a file unless the linkage attributes of the value are empty or the column is defined with NO LINK CONTROL. Unless the value contains only a comment or the URL is exactly the same. the trailing decimal point is replaced by a blank so that the value is a valid string representation of a timestamp. the links in the table can be reinstated by providing linkage attributes identical to the ones in the column. A DataLink value may be assigned to a column by using the DLVALUE scalar function. TIME – If the *USA format is used. or *DMY.Assignments and Comparisons The length attribute of the column must be at least 10 if the date format is *ISO. that file is unlinked. and SQLWARN1 is set to 'W'. if the length is 6 or 7. the following rules apply: DATE The length of the host variable must be at least 10 if the date format is *ISO. *EUR. If the length is 20. or *JIS. the timestamp is truncated like a string. If the length is between 19 and 25. the length of the host variable must not be less than 5. the following error conditions can occur: v Data Location (URL) format is invalid v File server is not registered with this database Chapter 2. *MDY. the length attribute of the column must be at least 8. If the application provides the same data location as already exists in the column. This format does not include seconds. causing the omission of one or more digits of the microsecond part.

the column must be defined as GENERATED BY DEFAULT or OVERRIDING SYSTEM VALUE must be specified. For the value of the ROWID column. 19. Row ID Assignments A row ID value can only be assigned to a column. When the assignment is also creating a link. However. parameter. Note that usually no attempt is made to access the file server at retrieval time. The results of these scalar functions can then be assigned to host variables. the actual length of the comment and URL in its fully expanded form provided on input should be restricted to accommodate the output storage space. A unique constraint is implicitly added to every table that has a ROWID column that guarantees that every ROWID value is unique. v Referenced file cannot be accessed for linking. The value that is specified for the column must be a valid row ID value that was previously generated by DB2 UDB for OS/390 and z/OS or DB2 UDB for iSeries. A warning may be returned when retrieving a DataLink value because the table is in link pending state. v File with referential integrity control is not in a correct state according to the DB2 DataLinks File Manager. 88 DB2 UDB for iSeries SQL Reference V5R2 . In situations where this is possible. this error is raised. In addition. Hence. when the assignment removes an existing link. v File does not exist. in some cases the URL value returned has an access token attached. First access of a file on a server will cause the required values to be retrieved from the file server and cached at the database server for the subsequent retrieval of DataLink values for that file server. A DataLink value may be retrieved from the database through the use of scalar functions (such as DLLINKTYPE and DLURLPATH). the following errors can occur: v File server not currently available. If the restricted length is exceeded. v File already linked to another column. Distinct Type Assignments The rules that apply to the assignments of distinct types to host variables are different than the rules for all other assignments that involve distinct types. or host variable with a row ID data type. the output location must have sufficient storage space for the access token and the length of the DataLink column. It may be necessary to access the file server to determine the prefix name associated with a path.Assignments and Comparisons v Invalid link type specified v Invalid length of comment or URL Note that the size of a URL parameter or function result is the same on both input or output and is bound by the length of the DataLink column. the following errors can occur: v File server not currently available. This can be changed at the file server when the mount point of a file system is moved. An error is returned if the file server cannot be accessed. Note that this error will be raised even if the link is to a different relational database. 19It is therefore possible that subsequent attempts to access the file server through file system commands might fail.

Example: Assume that distinct type AGE was created with the following SQL statement and column STU_AGE in table STUDENTS was defined with that distinct type.2) Using the following SQL statement and substituting various values for X and Y to insert values into various columns of TABLE1 from TABLE2. a distinct type value can be assigned to any target other than a host variable when: v The target of the assignment has the same distinct type. SELECT STU_AGE INTO :HV_AGE FROM STUDENTS WHERE STU_NUMBER = 200 The distinct type value is assignable to the host variable HV_AGE because the source data type of the distinct type (SMALLINT) is assignable to the host variable (INTEGER). Language Elements 89 . Assignments Other Than to Host Variables A distinct type can be either the source or target of an assignment. Today’s classes have a value of 3 in the DAY column. If distinct type AGE had been sourced on a character data type such as CHAR(5). INSERT INTO TABLE1 (Y) SELECT X FROM TABLE2 Chapter 2.Assignments and Comparisons Assignments to Host Variables The assignment of a distinct type to a host variable is based on the source data type of the distinct type. or v The distinct type is castable to the data type of the target Any value can be assigned to a distinct type when: v The value to be assigned has the same distinct type as the target. Therefore. assume that two tables TABLE1 and TABLE2 were created with four identical column descriptions: AGECOL SMINTCOL INTCOL DECCOL AGE SMALLINT INTEGER DEC(6. Table 15 on page 90 shows whether the assignments are valid. the value of a distinct type is assignable to a host variable only if the source data type of the distinct type is assignable to the host variable. Using the CL_SCHED table. or v The data type of the assigned value is castable to the target distinct type Example: Assume that the source data type for distinct type AGE is SMALLINT: CREATE DISTINCT TYPE AGE AS SMALLINT WITH COMPARISONS Next. consider this valid assignment of a student’s age to host variable HV_AGE. Assignment is based on whether the data type of the value to be assigned is castable to the data type of the target. “Casting Between Data Types” on page 78 shows which casts are supported when a distinct type is involved. select all the classes (CLASS_CODE) that start (STARTING) later today. CREATE DISTINCT TYPE AGE AS SMALLINT WITH COMPARISONS Next. the above assignment would be invalid because a character type cannot be assigned to an integer type. Therefore. which has an INTEGER data type.

If one number is an integer and the other number is decimal. that is. When decimal or nonzero scale binary numbers with different scales are compared. two binary strings are equal only if the length of the two strings is identical. 90 DB2 UDB for iSeries SQL Reference V5R2 . with regard to sign. Character and Graphic String Comparisons Character and UCS-2 graphic string comparisons use the sort sequence in effect when the statement is executed for all SBCS data and the single-byte portion of mixed data. the comparison is made with a single-precision form of the constant. However. If the sort sequence is *HEX. String Comparisons Binary String Comparisons Binary string comparisons always use a sort sequence of *HEX and the corresponding bytes of each string are compared. decimal. For example. If one number is floating point and the other number is integer.X AGECOL SMINTCOL TABLE1. the corresponding bytes of the weighted value of each string are compared. the corresponding bytes of each string are compared. negative 2 is less than +1.Y AGECOL AGECOL Valid Yes Yes Reason Source and target are same distinct type SMALLINT can be cast to AGE (because AGE’s source type is SMALLINT) INTEGER can be cast to AGE (because AGE’s source type is SMALLINT) DECIMAL cannot be cast to AGE AGE can be cast to its source type SMALLINT AGE cannot be cast to INTEGER AGE cannot be cast to DECIMAL INTCOL AGECOL Yes DECCOL AGECOL AGECOL AGECOL AGECOL SMINTCOL INTCOL DECCOL No Yes No No Numeric Comparisons Numbers are compared algebraically. Additionally. if a single-precision floating-point column is compared to a constant and the constant can be represented by a single-precision floating-point number. the comparison is made with a temporary copy of the integer. which has been converted to decimal. the comparison is made with a temporary copy of one of the numbers that has been extended with trailing zeros so that its fractional part has the same number of digits as the other number. For all other sort sequences. Assessment of various assignments (for example on INSERT) TABLE2. the comparison is made with a temporary copy of the second number converted to a double-precision floating-point number. Two floating-point numbers are equal only if the bit configurations of their normalized forms are identical. or single-precision floating point.Assignments and Comparisons Table 15.

v The CCSID Conversion Selection Table indicates that conversion is necessary. Chapter 2. In operations that select one value from a set of such values. An empty string is equal to a blank string. v A sort sequence other than *HEX is used and all corresponding bytes of the weighted value are equal. one of the strings is first converted. See the description of GROUP BY for further information about the arbitrary selection involved in references to a grouping column. the pad character is a DBCS blank (x’4040’). UCS-2 defines a blank character at code point X’0020’ and X’3000’. The operations that can involve such an arbitrary selection are DISTINCT. The following table shows which operand is selected for conversion. Selecting the Encoding Scheme for Character Conversion Second Operand First Operand SBCS Data DBCS Data Mixed Data UCS-2 Data SBCS Data See below First First First DBCS Data Second See below First First Mixed Data Second Second See below First UCS-2 Data Second Second Second See below Otherwise. v Neither CCSID is 65535. the pad character is also a blank. The database manager pads with the blank at code point X’0020’. For UCS-2 graphic data. to the coded character set of the other string.Assignments and Comparisons If the strings have different lengths. The relationship between two unequal strings is determined by a comparison of the first pair of unequal bytes (or bytes of the weighted value) from the left end of the string. v A *HEX sort sequence is used and all corresponding bytes are equal. The padding makes each string the same length. the value selected is arbitrary. Language Elements 91 . the string selected for conversion depends on the type of each operand. This comparison is made according to the sort sequence in effect when the statement is executed. For bit data. MAX. if necessary. given the operand types: 20. The pad character is always a blank. 20 Two strings are equal if any of the following are true: v Both strings are empty. MIN. v The string selected for conversion is neither null nor empty. a temporary copy of the shorter string is padded on the right with blanks before comparison. Two varying-length strings with different lengths are equal if they differ only in the number of trailing blanks. UNION and references to a grouping column. Conversion Rules for Comparison: When two strings are compared. If two strings with different encoding schemes are compared and the operands are the same type. any necessary conversion applies to the string as follows: Table 16. the pad character is a UCS-2 blank. regardless of the sort sequence. Character conversion is necessary only if all of the following are true: v The CCSIDs of the two strings are different. For DBCS graphic data.

All comparisons are chronological. An error occurs if a character of the string cannot be converted or the CCSID Conversion Selection Table is used but does not contain any information about the pair of CCSIDs. the following predicate is true: TIMESTAMP(’1990-02-23-00.00’ Distinct Type Comparisons A value with a distinct type can be compared only to another value with exactly the same distinct type. 0001. TIME. Thus. A warning occurs if a character of the string is converted to the substitution character. ATTENDEE_NUMBER INTEGER NOT NULL. Comparisons involving TIMESTAMP values are chronological without regard to representations that might be considered equivalent.Assignments and Comparisons Table 17. zero seconds are implied. HIGH_SCHOOL_LEVEL YOUTH) The following comparison is valid because AGE and HIGH_SCHOOL_LEVEL have the same distinct type: 92 DB2 UDB for iSeries SQL Reference V5R2 .00.00’) > ’1990-02-22-24. If the string representation omits seconds. Comparisons involving TIME values and string representations of time values always include seconds. For example. The time 24:00:00 compares greater than the time 00:00:00. Selecting the Operand for Character Conversion Second Operand First Operand Column Value Derived Value Special Register Constant Column Value Second First First First Derived Value Second Second First First First Special Register Second Second Second First First Constant Second Second Second Second First Host Variable Second Second Second Second Second Host Variable First A host variable containing data in a foreign encoding scheme is always effectively converted to the native encoding scheme before it is used in any operation. the greater the value of that point in time. assume that distinct type YOUTH and table CAMP_DB2_ROSTER table were created with the following SQL statements: CREATE DISTINCT TYPE YOUTH AS INTEGER WITH COMPARISONS CREATE TABLE CAMP_DB2_ROSTER ( NAME VARCHAR(20). or TIMESTAMP value can be compared either with another value of the same data type or with a string representation of that data type. Datetime Comparisons A DATE. AGE YOUTH. which means the farther a point in time is from January 1. The above rules are based on the assumption that this conversion has already occurred.00.

All of the following comparisons are valid: SELECT * FROM CAMP_DB2_ROSTER WHERE AGE > YOUTH(ATTENDEE_NUMBER) SELECT * FROM CAMP_DB2_ROSTER WHERE AGE > CAST( ATTENDEE_NUMBER AS YOUTH) SELECT * FROM CAMP_DB2_ROSTER WHERE INTEGER(AGE) > ATTENDEE_NUMBER SELECT * FROM CAMP_DB2_ROSTER WHERE CAST(AGE AS INTEGER) > ATTENDEE_NUMBER Chapter 2.Assignments and Comparisons SELECT * FROM CAMP_DB2_ROSTER WHERE AGE > HIGH_SCHOOL_LEVEL The following comparison is not valid: SELECT * FROM CAMP_DB2_ROSTER WHERE AGE > ATTENDEE_NUMBER However. Language Elements 93 . AGE can be compared to ATTENDEE_NUMBER by using a cast function or CAST specification to cast between the distinct type and the source type.

x+max(w-x.. The conversion operation is exactly the same as if the values were assigned to the result. this data type and the data type of the next operand determine a new intermediate result data type. the result does not allow nulls.. This section explains those rules.x) DECIMAL(w.Rules for Result Data Types Rules for Result Data Types The data types of a result are determined by rules which are applied to the operands in an operation. the result allows nulls. SMALLINT SMALLINT INTEGER SMALLINT INTEGER BIGINT SMALLINT INTEGER BIGINT The data type of the result column is. the operand column values are converted to conform to the data type and attributes of the result. Numeric Operands Numeric types are compatible only with other numeric types. MAX. the result data type is determined by the sequential application of the rules summarized in the tables that follow. IFNULL.. MIN.x) where p = min(31. and VALUE v Expression values of the IN list of an IN predicate The data type of the result is determined by the data type of the operands.. If neither operand column allows nulls..x) where p = min(31.x) And the other operand is. These rules apply to: v Corresponding columns in UNION or UNION ALL operations v Result expressions of a CASE expression v Arguments of the scalar functions COALESCE. For example. The data types of the first two operands determine an intermediate result data type. For each pair of data types. SMALLINT INTEGER INTEGER BIGINT BIGINT BIGINT DECIMAL(w. The last intermediate result data type and the data type of the last operand determine the data type of the result.x) where p = min(31. v If the whole part of a number cannot be preserved then an error is returned.5)) DECIMAL(p.. and the values derived from the CHAR(5) column are padded on the right with five blanks. If one operand column is. x+max(w-x. SMALLINT INTEGER INTEGER BIGINT BIGINT BIGINT DECIMAL(p. v If one operand column is CHAR(10). If the data type and attributes of any operand column are not the same as those of the result. the result is CHAR(10). Otherwise. and so on. x+max(w-x.11)) DECIMAL(p.19)) 94 DB2 UDB for iSeries SQL Reference V5R2 .x) DECIMAL(w. and the other operand column is CHAR(5).

19)) NUMERIC(p..z) + max(w-x. both operands must be binary with the same scale. y-z)) s = max(x.11)) NUMERIC(p. DECIMAL(p.s) where p = min(31. x + max(w-x. x + max(w-x. x + max(w-x. Chapter 2. BIGINT.z)+max(w-x..x) where p = min(31. DECIMAL(w. NUMERIC. max(x.x) NUMERIC(w..z) or NUMERIC(y..x) NONZERO SCALE BINARY NONZERO SCALE BINARY REAL REAL REAL DECIMAL.z. Language Elements 95 .5)) NUMERIC(p.x) NUMERIC(w.. DECIMAL(y. or SMALLINT any numeric type DOUBLE DOUBLE Character and Graphic String Operands Character and graphic strings are compatible with other character and graphic strings when there is a defined conversion between their corresponding CCSIDs.x) NUMERIC(w.) SMALLINT INTEGER BIGINT NUMERIC(y.z) NONZERO SCALE BINARY (If either operand is nonzero scale binary.y-z)) s = max(x..x) where p = min(31.z) The data type of the result column is.x) where p = min(31.z) NUMERIC(p.s) where p = min(31.x) And the other operand is.) REAL DOUBLE NUMERIC(w. max(x.Rules for Result Data Types If one operand column is. INTEGER.

or any CHAR or VARCHAR expression that contains a valid string representation of a time. A TIME type is compatible with another TIME type.y) The CCSID of the result graphic string will be derived based on the “Conversion Rules for Operations That Combine Strings” on page 98.y) Datetime Operands A DATE type is compatible with another DATE type... If one operand column is.y) VARGRAPHIC(z) where z = max(x.... Binary String Operands Binary strings (BLOBs) are compatible only with other binary strings (BLOBs).y) VARCHAR(z) where z = max(x. The data type of the result is TIMESTAMP. Other data types can be treated as a BLOB data type by using the BLOB scalar function to cast the data type to a BLOB.Rules for Result Data Types If one operand column is..y) VARGRAPHIC(z) where z = max(x. BLOB(y) The data type of the result column is. The length of the result BLOB is the largest length of all the data types. or any CHAR or VARCHAR expression that contains a valid string representation of a date. 96 DB2 UDB for iSeries SQL Reference V5R2 .y) CLOB(x) DBCLOB(x) DBCLOB(z) where z = max(x.y) CLOB(x) CLOB(z) where z = max(x... CHAR(y) GRAPHIC(y) or CHAR(y) VARCHAR(y) or CHAR(y) GRAPHIC(y) VARGRAPHIC(y) or GRAPHIC(y) or VARCHAR(y) or CHAR(y) CLOB(y) or VARCHAR(y) or CHAR(y) GRAPHIC(y) or VARGRAPHIC(y) CHAR(y) or VARCHAR(y) or CLOB(y) or GRAPHIC(y) or VARGRAPHIC(y) or DBCLOB(y) The data type of the result column is. CHAR(x) GRAPHIC(x) VARCHAR(x) VARCHAR(x) VARGRAPHIC(x) And the other operand is.. BLOB(x) And the other operand is... A TIMESTAMP type is compatible with another TIMESTAMP type. BLOB(z) where z = max(x.y) GRAPHIC(z) where z = max(x. or any CHAR or VARCHAR expression that contains a valid string representation of a timestamp.. The data type of the result is DATE.y) DBCLOB(z) where z = max(x. CHAR(z) where z = max(x. The data type of the result is a BLOB. The data type of the result is TIME.

. DATALINK(y) The data type of the result column is.... DATE TIME TIMESTAMP The data type of the result column is... If one operand column is.. If one operand column is. The length of the result DATALINK is the largest length of all the data types. DATALINK(x) And the other operand is. DATE TIME TIMESTAMP And the other operand is. DATE TIME TIMESTAMP Distinct Type Operands A distinct type is compatible only with itself.. The data type of the result is DATALINK.... DataLinks with NO LINK CONTROL are only compatible with other DataLinks with NO LINK CONTROL. However.... Distinct Type DataLink Operands A DataLink is compatible with another DataLink. Distinct Type The data type of the result column is... Distinct Type And the other operand is. DataLinks with FILE LINK CONTROL READ PERMISSION FS are only compatible with other DataLinks with FILE LINK CONTROL READ PERMISSION FS. DATALINK(z) where z = max(x.y) Chapter 2.. and DataLinks with FILE LINK CONTROL READ PERMISSION DB are only compatible with other DataLinks with FILE LINK CONTROL READ PERMISSION DB.Rules for Result Data Types If one operand column is. The data type of the result is the distinct type. Language Elements 97 ..

and UNION ALL. and so on. the resulting CCSID is the job default CCSID. a host variable containing data in a foreign encoding scheme is effectively converted to the native encoding scheme before it is used in any operation. and CONCAT scalar functions and CASE expressions. VALUE. the result is determined by the following table: Table 18.21 v If one CCSID denotes data in an encoding scheme different from the other CCSID. Selecting the CCSID of the Intermediate Result Second Operand First Operand Column Value Derived Value Constant Special Register Host Variable Column Value First Second Second Second Second Derived Value First First Second Second Second Constant First First First First Second Special Register First First First First Second Host Variable First First First First First However. the result is that CCSID. and 500. this CCSID and the CCSID of the next operand determine a new intermediate result CCSID. IFNULL. 278. and COLC are columns with CCSIDs 37. For each pair of CCSIDs. (These rules also apply to the MAX. COALESCE. assume COLA. The last intermediate result CCSID and the CCSID of the last operand determine the CCSID of the result string or column. the result CCSID is determined by the sequential application of the following rules: v If the CCSIDs are equal. and the execution of the operation may involve conversion of strings to the coded character set identified by that CCSID. If either operand is a CLOB or DBCLOB. v If either CCSID is 65535. Selecting the Encoding Scheme of the Intermediate Result Second Operand First Operand SBCS Data DBCS Data Mixed Data UCS-2 Data SBCS Data See below First First First DBCS Data Second See below First First Mixed Data Second Second See below First UCS-2 Data Second Second Second See below v Otherwise. The above rules are based on the assumption that this conversion has already occurred. respectively. The result CCSID of COLA CONCAT COLB CONCAT COLC is determined as follows: 21. The CCSIDs of the first two operands determine an intermediate result CCSID. The CCSID of the result is determined by the CCSIDs of the operands. COLB. MIN. 98 DB2 UDB for iSeries SQL Reference V5R2 .Conversion Rules for Operations That Combine Strings Conversion Rules for Operations That Combine Strings The operations that combine strings are concatenation. For example. UNION. the result is 65535. Note that an intermediate result is considered to be a derived value operand. the CCSID of the result is determined at bind time.) In each case. the resulting CCSID is determined by the following table: Table 19.

so the CCSID of the first operand is chosen. The result CCSID of COLA CONCAT COLB is first determined to be 37 because both operands are columns. MIN. to the coded character set of the result column. An operand of concatenation or the selected argument of the MAX. v The string is neither null nor empty. The result CCSID of 500 is determined because the first operand is a derived value and the second operand is a column. to the coded character set of the result string. v Neither CCSID is 65535.Conversion Rules for Operations That Combine Strings 1. A warning occurs if a character of a string is converted to the substitution character. VALUE. and CONCAT scalar function is converted. Chapter 2. so the CCSID of the second operand is chosen. COALESCE. if necessary. Each string of an operand of UNION or UNION ALL is converted. An error occurs if a character of a string cannot be converted or if the CCSID Conversion Selection Table is used but does not contain any information about the CCSID pair. v The CCSID Conversion Selection Table indicates that conversion is necessary. Character conversion is necessary only if all of the following are true: v The CCSIDs are different. IFNULL. if necessary. 2. Language Elements 99 . The result CCSID of the concatenation of the result from step 1 and COLC is determined to be 500.

The data type of an integer constant is large integer if its value is within the range of a large integer. Integer Constants An integer constant specifies an integer as a signed or unsigned number with a maximum of 19 digits that does not include a decimal point. Examples 25. Examples 15E1 2. +37589. The first number can include a sign and a decimal point. or v Be larger than 2147483647 or smaller than -2147483647 The precision is the total number of digits (including leading and trailing zeros).3333333333 12345678901 Character-String Constants A character-string constant specifies a varying-length character string. Constants are classified as string constants or numeric constants.E5 2. the term integer is used for a large integer constant that must not include a sign. the number of digits in the first number must not exceed 17 and the number of digits in the second must not exceed 3.2E-1 +5.E+2 Decimal Constants A decimal constant specifies a decimal number as a signed or unsigned number that includes at most 31 digits. The value of the constant is the product of the first number and the power of 10 specified by the second number. Examples 64 -15 +100 32767 720176 12345678901 Floating-Point Constants A floating-point constant specifies a double-precision floating-point number as two numbers separated by an E. In syntax diagrams. All constants have the attribute NOT NULL. or decimal. The two forms of character-string constant follow: 100 DB2 UDB for iSeries SQL Reference V5R2 . floating point. -15. The number of characters in the constant must not exceed 24. A constant that is defined outside the range of big integer values is considered a decimal constant. A negative sign in a numeric constant with a value of zero is ignored.Constants Constants A constant (sometimes called a literal) specifies a value. but within the range of a big integer. String constants are further classified as character or graphic. The constant must either: v Include a decimal point. the second number can include a sign but not a decimal point.5 1000. Numeric constants are further classified as integer. it must be within the range of floating-point numbers. Excluding leading zeros. the scale is the number of digits to the right of the decimal point (including trailing zeros). The data type of an integer constant is big integer if its value is outside the range of a large integer.

Constants v A sequence of characters that starts and ends with a string delimiter.1990’ ’32’ ’DON’’T CHANGE’ ’’ X’FFFF’ Graphic-String Constants DBCS Graphic-String Constants A graphic-string constant is a varying-length graphic string. In all other cases. the default CCSID of the current server. In this case. The data in the host variable is converted from the foreign encoding scheme to the default CCSID of the current server. the CCSID of the specified source file v For CRTSQLxxx: – For static SQL. the CCSID assigned to the constant is the default CCSID of the current server. The number of bytes between the string delimiters cannot be greater than 32740. Two consecutive string delimiters that are not contained within a string represent the empty string. The number of hexadecimal digits must not exceed 65480. Character-string constants can contain mixed data. each pair of hexadecimal digits represents a character. The characters between the string delimiters must be an even number of hexadecimal digits. The length of the specified string cannot be greater than 16370. or if a string constant is specified on the PREPARE statement. v An X followed by a sequence of characters that starts and ends with a string delimiter. The CCSID assigned to the constant is the CCSID of the source containing the constant unless the source is encoded in a foreign encoding scheme (such as ASCII). This form of string constant allows you to specify characters that do not have a keyboard representation. the CCSID of the source is the CCSID of the host variable specified on the PREPARE statement.12. The CCSID of the source is: v For STRSQL. Examples ’Peggy’ ’14. Two consecutive string delimiters are used to represent one string delimiter within the character string. Under the conventions of hexadecimal notation. A hexadecimal digit is a digit or any of the letters A through F (uppercase or lowercase). Language Elements 101 . If the job CCSID supports mixed data. a character-string constant is classified as mixed data if it includes a DBCS substring. The CCSID of the source is determined by the application requester. The three forms of DBCS graphic-string constants are: Chapter 2. – For dynamic SQL. the CCSID of the source is the CCSID of the source file used on the CRTSQLxxx command. a character-string constant is classified as SBCS data. the default CCSID of the application requester v For the RUNSQLSTM or STRREXPRC commands.

Each group of 4 digits represents a single DBCS graphic character. The hexadecimal for shift-in and shift-out (’0E’X and ’0F’X) are not included in the string. the CCSID is 65535. The SBCS ’ is the EBCDIC apostrophe. the SQL delimiters and the G or the N are SBCS characters.Constants In the normal form. The form of the hexadecimal UCS-2 graphic constant is: 102 DB2 UDB for iSeries SQL Reference V5R2 . For information on the CCSID of the source. The number of characters between the string delimiters must be an even multiple of 4. the CCSID assigned to the constant is the DBCS CCSID associated with the default CCSID of the current server when the SQL statement containing the constant is prepared. For information on associated DBCS CCSIDs. see the Globalization DBCS CCSIDs topic in the iSeries Information Center. UCS-2 Graphic-String Constants A hexadecimal UCS-2 graphic constant is supported. The form of the hexadecimal DBCS graphic constant is: GX’ssss’ In the constant. In this case. the apostrophes and the G are DBCS characters. ssss represents a string from 0 to 32766 hexadecimal digits. Note that this PL/I form is only valid for static statements embedded in PL/I programs. X’7D’. see Character String Constants. Two consecutive DBCS string delimiters are used to represent one string delimiter within the string. If there is no DBCS CCSID associated with the CCSID of the source. The CCSID assigned to constants is the DBCS CCSID associated with the CCSID of the source unless the source is encoded in a foreign encoding scheme (such as ASCII). A hexadecimal DBCS graphic constant is also supported. In the PL/I form.

The number of characters between the string delimiters must be an even multiple of 4. The SET OPTION statement can also be used to specify the DECMPT parameter within the source of a program containing embedded SQL. The number of hexadecimal digits must not exceed 32740. Language Elements 103 . FLOAT. Each group of 4 digits represents a single UCS-2 graphic character. Note that the syntax of a binary string constant is identical to the second form of a character constant. in the CHAR. CLOB. A constant of this form is only treated as a binary string constant if the SET OPTION statement was specified with the binary string option (SQLCURRULE = *STD) or the SQLCURRULE(*STD) parameter on the CRTSQLxxx command.Constants UX’ssss’ In the constant. Default Decimal Point Interfaces SQL Interface Embedded SQL Specification The *JOB. The characters between the string delimiters must be an even number of hexadecimal digits. ssss represents a string from 0 to 32766 hexadecimal digits. The form of a binary-string constant follows: v An X followed by a sequence of characters that starts and ends with a string delimiter. or *SYSVAL value in the OPTION parameter is specified on the Create SQL Program (CRTSQLxxx) commands. and VARGRAPHIC scalar functions and the CAST expression) The default decimal point can be specified through the following interfaces: Table 20. and REAL scalar functions and the CAST expression) v to determine the decimal point character to use in the result when casting a number to a string (for example. Binary-String Constants A binary-string constant specifies a varying-length binary string. in the DECIMAL. A hexadecimal digit is a digit or any of the letters A through F (uppercase or lowercase). Example X’FFFF’ | | | | | | | | | | | | | | | | | | | | | Decimal Point The default decimal point can be specified: v To interpret numeric constants v To determine the decimal point character to use when casting a character string to a number (for example. *COMMA. DOUBLE_PRECISION. | The CCSID of a UCS-2 constant is 13488. (For more information about CRTSQLxxx commands.) Chapter 2. see the SQL Programming with Host Languages book. *PERIOD. The CCSID assigned to the constant is 65535.

with this option. *APOST names the apostrophe (') as the string delimiter. the trailing comma must be followed by a non-blank character. 111) Delimiters *APOST and *QUOTE are mutually exclusive COBOL precompiler options that name the string delimiter within COBOL statements. to specify a decimal constant without a fractional part. Default Decimal Point Interfaces (continued) SQL Interface Interactive SQL and Run SQL Statements Specification The DECPNT parameter on the Start SQL (STRSQL) command or by changing the session attributes. *APOSTSQL and *QUOTESQL are mutually exclusive COBOL precompiler options that play a similar role for SQL statements embedded in COBOL programs. see the iSeries Access category in the iSeries Information Center.) Decimal Separator conneciton property (For more information about JDBC and SQLJ. The DECMPT parameter on the Run SQL Statements (RUNSQLSTM) command.. see the IBM Developer Kit for Java topic in the iSeries Information Center. Thus. the quotation mark (") is the SQL escape character. the apostrophe is the SQL escape character. see the iSeries Access category in the iSeries Information Center.) Format in JDBC Setup (For more information about ODBC. The non-blank character can be a separator comma. the usages are fixed. The values of *APOSTSQL and *QUOTESQL are respectively the same as the values of *APOST and *QUOTE.) Call Level Interface (CLI) on the server JDBC or SQLJ on the server using Developer Kit for Java ODBC on a client using the iSeries Access ODBC Driver JDBC on a client using the IBM Toolbox for Java If the comma is the decimal point. *QUOTESQL names the quotation mark as the SQL string delimiter. see the SQL Programming Concepts book.) (For more information about the IBM Toolbox for Java. v A comma intended as a decimal point must not be followed by a space. (For more information about STRSQL and RUNSQLSTM commands. the SQL 104 DB2 UDB for iSeries SQL Reference V5R2 .) Decimal Separator in the Advanced Server Options in ODBC Setup (For more information about ODBC. v A comma intended as a separator of numeric constants in a list must be followed by a space. In host languages other than COBOL. The string delimiter for the host language and for static SQL statements is the apostrophe (').) SQL_ATTR_DATE_FMT and SQL_ATTR_DATE_SEP environment or connection variables (For more information about CLI. see IBM Toolbox for Java topic in the iSeries Information Center .Constants | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 20. *APOSTSQL names the apostrophe (') as the SQL string delimiter. as in: VALUES(9999999999. see the SQL Call Level Interfaces (ODBC) book. *QUOTE names the quotation mark ("). the following rules apply: v A period will also be allowed as a decimal point. with this option.

Chapter 2. Language Elements 105 .Constants escape character is the quotation mark (").

where each schema name is enclosed in delimiters and separated from the following schema by a comma. CURRENT_PATH. procedure names. all values are based on a single clock reading. its CCSID is a default CCSID of the current server. UPDATE PROJECT SET PRENDATE = CURRENT DATE WHERE PROJNO = ’MA2111’ CURRENT PATH. For information on when the SQL path is used to resolve unqualified names in both dynamic and static SQL statements and the effect of its value. The SQLPATH value can also be specified using the SET OPTION statement. You can change the value of the register by executing the statement SET PATH. and function names in dynamically prepared SQL statements. ″the value of the authorization ID of the statement″ . or NOW scalar functions within a single statement. A reference to a special register is a reference to a value provided by the current server. or the CURDATE. For details about this statement. If this special register is used more than once within a single SQL statement. The CURRENT PATH special register contains a list of one or more schema names. the path is the value specified in the SQLPATH parameter. 106 DB2 UDB for iSeries SQL Reference V5R2 .Special Registers Special Registers A special register is a storage area that is defined for an application process by the database manager and is used to store information that can be referenced in SQL statements. The maximum number of schema names in the path is 268. ″QSYS2″. CURTIME. ″QSYS″. It is also used to resolve unqualified procedure names that are specified as host variables in SQL CALL statements (CALL host-variable). The initial value of the CURRENT PATH special register in an activation group is established by the first SQL statement that is executed. – For system naming. v Otherwise. ″*LIBL″. If the value is a string. or used with CURRENT TIME. CURRENT TIMESTAMP. The data type is VARCHAR(3483). set the project end date (PRENDATE) of the MA2111 project (PROJNO) to the current date. v If the first SQL statement in an activation group is executed from an SQL program or SQL package and the SQLPATH parameter was specified on the CRTSQLxxx command. Example Using the PROJECT table. CURRENT DATE or CURRENT_DATE The CURRENT DATE special register specifies a date that is based on a reading of the time-of-day clock when the SQL statement is executed at the current server. or CURRENT FUNCTION PATH The CURRENT PATH special register specifies the SQL path used to resolve unqualified distinct type names (both built-in types and distinct types). – For SQL naming. DB2 UDB for iSeries includes the following special registers. see “SQL Path” on page 53. see “SET PATH” on page 748. The delimiters and commas are included in the 3483 character length.

its schema name is used instead of the CURRENT SCHEMA schema name. If this special register is used more than once within a single SQL statement. CURRENT SERVER can be changed by the CONNECT (Type 1). Example Set the schema for object qualification to ’D123’. CURRENT TIMESTAMP. Example Set the host variable APPL_SERVE (VARCHAR(18)) to the name of the current server. all values are based on a single clock reading. or used with CURRENT DATE. SET CURRENT SCHEMA = ’D123’ CURRENT SERVER or CURRENT_SERVER The CURRENT SERVER special register specifies a VARCHAR(18) value that identifies the current server. or the CURDATE. 22. SELECT CURRENT SERVER INTO :APPL_SERVE FROM SYSDUMMY1 CURRENT TIME or CURRENT_TIME The CURRENT TIME special register specifies a time that is based on a reading of the time-of-day clock when the SQL statement is executed at the current server. Language Elements 107 . but only under certain conditions. SYSTEM PATH | | | | | | | | | | | | | | | CURRENT SCHEMA The CURRENT SCHEMA special register specifies a VARCHAR(128) value that identifies the schema name used to qualify unqualified database object references where applicable in dynamically prepared SQL statements. Chapter 2. For compatibility with DB2 UDB for OS/390 and z/OS. and “SET CONNECTION” on page 731.Special Registers Example Set the special register so that schema SMITH is searched before schemas QSYS and QSYS2 (SYSTEM PATH). or NOW scalar functions within a single statement. CURTIME. If DYNDFTCOL is specified in a program. or SET CONNECTION statements. The initial value of CURRENT SCHEMA is the authorization ID of the current session user. SET CURRENT PATH SMITH. “CONNECT (Type 2)” on page 422. CURRENT SERVER cannot be specified unless the local relational database is named by adding the entry to the relational database directory using the ADDRDBDIRE or WRKRDBDIRE command. CONNECT (Type 2). The DFTRDBCOL keyword controls the schema name used to qualify unqualified database object references where applicable for static SQL statements.22 CURRENT SCHEMA is not used to qualify names in programs where the DYNDFTCOL has been specified. See the description in “CONNECT (Type 1)” on page 417. the special register CURRENT SQLID is treated as a synonym for CURRENT SCHEMA.

Subtracting CURRENT TIMEZONE from a local time converts that local time to UTC. :SRC. or used with CURRENT DATE. select all the classes (CLASS_CODE) that start (STARTING) later today. and TXT (VARCHAR(200)). SUBJECT. CURRENT TIME. The difference is represented by a time duration (a decimal number in which the first two digits are the number of hours. SOURCE. SELECT * FROM IN_TRAY WHERE SOURCE = USER 23. Coordinated Universal Time. SELECT RECEIVED . The data type of the special register is VARCHAR(18). the next two digits are the number of minutes. or the CURDATE. NOTE_TEXT FROM IN_TRAY USER The USER special register specifies the run-time authorization ID at the current server. formerly known as GMT. If this special register is used more than once within a single SQL statement. INSERT INTO IN_TRAY VALUES (CURRENT TIMESTAMP. or NOW scalar functions within a single statement. The values for the other three columns come from the host variables SRC (CHAR(8)). SUB (CHAR(64)). 108 DB2 UDB for iSeries SQL Reference V5R2 . CURTIME. :SUB.CURRENT TIMEZONE. The number of hours is between -24 and 24 exclusive.Special Registers Example Using the CL_SCHED table. Example Insert a row into the IN_TRAY sample table. The value of the RECEIVED column should be a timestamp that indicates when the row was inserted. and the last two digits are the number of seconds). all values are based on a single clock reading. SELECT CLASS_CODE FROM CL_SCHED WHERE STARTING > CURRENT TIME AND DAY = 3 CURRENT TIMESTAMP or CURRENT_TIMESTAMP The CURRENT TIMESTAMP special register specifies a timestamp that is based on a reading of the time-of-day clock when the SQL statement is executed at the current server. Today’s classes have a value of 3 in the DAY column. Example Using the IN_TRAY table. :TXT) CURRENT TIMEZONE or CURRENT_TIMEZONE The CURRENT TIMEZONE special register specifies the difference between UTC 23 and local time at the current server. Example Select all notes from the IN_TRAY table that the user placed there himself. select all the rows from the table and adjust the value to UTC.

the value specified by the column name CODE is the value of the column CODE in that row. In the example that is shown above.” on page 331. A column name can be used to: v Declare the name of a column. For example. a view name.Column Names Column Names The meaning of a column name depends on its context. v In all other contexts. Correlation Names A correlation name can be defined in the FROM clause of a query and in the first clause of an UPDATE or DELETE statement. Z might have been used merely to avoid having to enter X. an alias name. See “Column Name Qualifiers to Avoid Ambiguity” on page 111 and “Column Name Qualifiers in Correlated References” on page 112 for details. For example. Chapter 2. or in different clauses of the same statement. “Queries. when the search condition CODE = 20 is applied to some row. a column name must not be qualified.MYTABLE more than once. a column name specifies all values in the intermediate result table to which the clause is applied. a correlation name can be used to avoid ambiguity or to establish a correlated reference. v Identify a column. or alias. or alias only within the context in which it is defined. as in a CREATE INDEX statement. as in a CREATE TABLE statement. or a correlation name. the clause shown below establishes Z as a correlation name for X. Where a qualifier is optional it can serve two purposes. – In a GROUP BY or ORDER BY clause. Language Elements 109 . – In an expression. the same correlation name can be defined for different purposes in different statements. a column name can be qualified at the user’s option. view. the column name must be qualified. a search condition. as in the following contexts: – In a column function a column name specifies all values of the column in the group or intermediate result table to which the function is applied. Qualified Column Names A qualifier for a column name can be a table name. Whether a column name can be qualified depends on its context: v In the COMMENT and LABEL statements. or a scalar function. v Where the column name specifies values of the column. v Specify values of the column. Hence. A correlation name can also be used as a shorter name for a table. a column name specifies a value for each row or group to which the construct is applied. For example. Groups and intermediate result tables are explained under Chapter 4. view. For example. MAX(SALARY) applies the function MAX to all values of the column SALARY in a group.MYTABLE Z A correlation name is associated with a table. As a qualifier.MYTABLE: FROM X. ORDER BY DEPT orders an intermediate result table by the values of the column DEPT.

Given the FROM clause: FROM EMPLOYEE E1. The names are compared after qualifying any unqualified table or view names. any qualified reference to a column of that instance of the table. Given the FROM clause: FROM EMPLOYEE. because both instances of EMPLOYEE in the FROM clause have correlation names. “E”.PROJECT denotes a column of the second instance of EMPLOYEE in the FROM clause. or alias name is said to be exposed in that FROM clause if a correlation name is not specified. Given the following statement: SELECT * FROM EMPLOYEE E1. view or alias must use the correlation name. A qualified reference to the second instance of EMPLOYEE must use the correlation name “E2” (E2. A table name. view name.PROJECT=’ABC’ ***INCORRECT*** the qualified reference EMPLOYEE. 2. 3. EMPLOYEE a qualified reference such as EMPLOYEE. DEPARTMENT A table name. view name. view or alias. For example. or alias name that is exposed in a FROM clause must not be the same as any other table name or view name exposed in that FROM clause or any correlation name in the FROM clause. in the following FROM clause. view name. The first two FROM clauses shown below are correct. as shown below: FROM EMPLOYEE E WHERE E. A correlation name is always an exposed name. a correlation name is specified for EMPLOYEE but not for DEPARTMENT. references to PROJECT must be qualified with either correlation name (E1. Given the FROM clause: FROM EMPLOYEE. Instead. EMPLOYEE E2 a qualified reference such as EMPLOYEE.PROJECT denotes a column of the first instance of EMPLOYEE in the FROM clause. For example.PROJECT). the reference to EMPLOYEE. 110 DB2 UDB for iSeries SQL Reference V5R2 . EMPLOYEE E2 WHERE EMPLOYEE.PROJECT=’ABC’ ***INCORRECT*** The qualified reference to PROJECT should instead use the correlation name. or alias name.PROJECT). 4. rather than the table name.PROJECT in the following example is incorrect. because a correlation name has been specified for EMPLOYEE: FROM EMPLOYEE E WHERE EMPLOYEE.PROJECT).PROJECT is incorrect. and this is not allowed.Column Names If a correlation name is specified for a table.PROJECT='ABC' Names specified in a FROM clause are either exposed or non-exposed. so DEPARTMENT is an exposed name. EMPLOYEE ***INCORRECT*** the two exposed table names included in this clause (EMPLOYEE and EMPLOYEE) are the same.PROJECT or E2. and EMPLOYEE is not: FROM EMPLOYEE E. A qualified reference to the first instance of EMPLOYEE must use the correlation name “E1” (E1. because each one contains no more than one reference to EMPLOYEE that is exposed: 1.

OWNY.MYTABLE CORZ.ANUM. Given the FROM clause: FROM DEPARTMENT D (NUM. The tables and views that might contain the column are called the object tables of the context. Given the FROM clause: FROM EMPLOYEE. a column name refers to values of a column in some table or view. the object tables of an expression in a SELECT clause are named in the FROM clause that follows it: SELECT CORZ. Each column name must be unique and unqualified.EMPLOYEE a reference to a column in the second instance of EMPLOYEE must use X. it must consist of as many names as there are columns in the table-reference. though potentially confusing: FROM EMPLOYEE DEPARTMENT.Column Names 5. For example. X. A reference to D.DEPTNO using this FROM clause is incorrect since the column name DEPTNO is a non-exposed column name. One reason for qualifying a column name is to designate the object from which the column comes. or a search condition. Column Name Qualifiers to Avoid Ambiguity In the context of a function. EMPLOYEE T1 ***INCORRECT*** The following FROM clause is technically correct. A correlation name specified in a FROM clause must not be the same as: v Any other correlation name in that FROM clause v Any unqualified table name or view name exposed in the FROM clause For example. This FROM clause is only valid if the authorization ID of the statement is not X. If a list of columns is specified. an expression.PROJECT).COLA.T1. DEPARTMENT EMPLOYEE The use of a correlation name in the FROM clause also allows the option of specifying a list of column names to be associated with the columns of the result table. Language Elements 111 . The clause that identifies the object tables also establishes the table designators for them.LOC) a qualified reference such as D.MYTABLE Table designators in the FROM clause are established as follows: Chapter 2.NAME. then the column names of the underlying table become non-exposed. Two or more object tables might contain columns with the same name.EMPLOYEE (X.NUM denotes the first column of the DEPARTMENT table that is defined in the table as DEPTNO. DEPARTMENT FROM X.COLA FROM OWNX. Table Designators A qualifier that designates a specific object table is called a table designator. If a column name list is specified. As with a correlation name. ORDER BY clause. EMPLOYEE E FROM EMPLOYEE DEPARTMENT. OWNY.EMPLOYEE. a GROUP BY clause.MGR. these listed column names become the exposed names of the columns that must be used for references to the columns throughout the query.MYTABLE. the following FROM clauses are incorrect: FROM EMPLOYEE E.

If the authorization ID of the statement is REGION. then: SELECT CORPDATA.EMPLOYEE X. MYTABLE. CORZ is used to qualify the first column name in the select list. The reference is ambiguous. then: SELECT CORPDATA.WORKDEPT FROM EMPLOYEE is a valid statement.Column Names v A name that follows a table or view name is both a correlation name and a table designator. either the qualified or unqualified form of the exposed table name may be used. CORPDATA. In the following example MYTABLE is the table designator for OWNY/MYTABLE. because EMPLOYEE represents the table REGION.WORKDEPT FROM EMPLOYEE ***INCORRECT*** is invalid. but the table designated does not include a column with the specified name. The reference is undefined. In the following FROM clause. Thus. an exposed table or view name is a table designator. OWNY. If the column is contained in several object tables with different names. the object table names can be used as designators. X and Y are defined to refer.MYTABLE is used to qualify the second column name in the select list.EMPLOYEE. v The column name is qualified by a table designator. Two or more object tables can be instances of the same table. 1.COLA. to the first and second instances of the table CORPDATA. Avoid ambiguous references by qualifying a column name with a uniquely defined table designator. v In system naming. distinct correlation names must be used to unambiguously designate the particular instances of the table. The following situations are considered errors: v No object table contains a column with the specified name. CORPDATA. “Queries.” on page 331 for more information about 112 DB2 UDB for iSeries SQL Reference V5R2 .EMPLOYEE Y When qualifying a column with the exposed table name form of a table designator. SELECT CORZ.EMPLOYEE. v The name is unqualified and more than one object table includes a column with that name.MYTABLE is a table designator.EMPLOYEE. OWNY/MYTABLE Avoiding undefined or ambiguous references When a column name refers to values of a column.EMPLOYEE. Again the reference is undefined.EMPLOYEE: FROM CORPDATA.COLA FROM OWNX/MYTABLE CORZ. Thus. the qualifier used and the table used must be the same after fully qualifying the table name or view name and the table designator. CORZ is a table designator. OWNY. If the authorization ID of the statement is CORPDATA. Column Name Qualifiers in Correlated References | | A subselect is a form of a query that can be used as a component of various SQL statements. 2. the table designator for an exposed table or view name is the unqualified table or view name. but the qualifier for WORKDEPT represents a different table. However. v In SQL naming. In this case. exactly one object table must include a column with that name. Refer to Chapter 4. respectively.

v Q does designate a table used at some higher level.C. Q. This is the FROM clause. Those elements of the hierarchy that contain subqueries are said to be at a higher level than the subqueries they contain. The following explanation is based on the assumption that a correlated reference is always in the form of a qualified column name and that the qualifier is a correlation name. if Q is a correlation name defined for T. If Q is used to designate a table at more than one level. because it is the lowest level that contains the subquery that includes Q. but Q. join clause. or an argument of a table function in a subquery can reference not only columns of the tables identified by the FROM clause of its own element of the hierarchy.C refers to the lowest level that contains the subquery that includes Q. For example. SELECT * FROM T1 Q WHERE A < ALL (SELECT B FROM T2 Q WHERE B < ANY (SELECT D FROM T3 WHERE D = Q. Language Elements 113 . In the following statement. Q.C is used in a search condition. the join clause. Because the same table or view can be identified at many levels. join clause. T. A subquery is a form of a fullselect that is enclosed within parenthesis.C. Q. Therefore.C refers to column C of the table or view at the level where Q is used as the table designator of that table or view. in turn.C is a correlated reference only if these three conditions are met: v Q.C.C. However.Column Names | | subselects. or Q. | | | | | | | | Every element of the hierarchy has a clause that establishes one or more table designators. include subqueries. A reference to a column of a table identified at a higher level is called a correlated reference. but also columns of tables identified at any level along the path from its own element to the highest level of the hierarchy. except in the highest level of an UPDATE or DELETE statement.C refers to the correlation name associated with T2. select list. or an argument of a table function in a subquery. and these search conditions can. or an argument of a table function in a subquery. A search condition. the select list. a subquery can be used in a search condition. an SQL statement can contain a hierarchy of subqueries. The column will be implicitly qualified when the statement is prepared depending on which table the column was found in. A correlated reference to column C of table T can be of the form C. Once Chapter 2. a correlated reference in the form of an unqualified column name is not good practice. v Q does not designate a table used in the FROM clause of that subquery. unique correlation names are recommended as table designators.C)) | | Unqualified Column Names An unqualified column name can also be a correlated reference if the column: v Is used in a search condition of a subquery v Is not contained in a table used in the FROM clause of that subquery v Is contained in a table used at some higher level Unqualified correlated references are not recommended because it makes the SQL statement difficult to understand. A subquery can include search conditions of its own. Q is used as a correlation name for T1 and T2. select list.

114 DB2 UDB for iSeries SQL Reference V5R2 . An SQL precompiler issues a warning message in the precompile listing and the database manager issues a positive SQLCODE (+12) and SQLSTATE (01545) when an SQL statement that has an unqualified correlated reference is prepared or executed.Column Names this implicit qualification is determined it will not change until the statement is re-prepared.

or a PLI. In Java and RPG. an RPG field. REXX. or C variable that is referenced in an SQL statement. or parameter marker can be used. or CREATE PROCEDURE (SQL) statement. unless otherwise noted. An SQL declare section begins with BEGIN DECLARE SECTION and ends with END DECLARE SECTION. see “Parameter Markers” on page 695. Chapter 2. For more information about how to refer to host structures in C. For more information about host variables in REXX. see the SQL Programming with Host Languages book. C++. Language Elements 115 . parameter marker Variables cannot be referenced in dynamic SQL statements. For more information about how to refer to transition variables see “CREATE TRIGGER” on page 557. transition variable Transition variables are defined in a trigger and refer to either the old or new values of columns. For more information about SQL variables.References to Variables References to Variables | | | | | | | | | | | | | | | | | | | | | | | | | | A variable in an SQL statement specifies a value that can be changed when the SQL statement is executed. the term host variable in syntax diagrams is used to describe where a host variable. A host-variable in an SQL statement must identify a host variable described in the program according to the rules for declaring host variables. see “References to SQL Parameters and Variables” on page 781. see “References to SQL Parameters and Variables” on page 781. SQL variable SQL variables are defined by an SQL compound statement in an SQL function. REXX. For more information about SQL variables. and host variables may be declared throughout the program. transition variable. In this book. COBOL. For more information about parameter markers. There are several types of variables used in SQL statements: host variable Host variables are defined by statements of a host language. CREATE FUNCTION (SQL Table). SQL variable. SQL parameter. SQL parameter SQL parameters are defined in an CREATE FUNCTION (SQL Scalar). Parameter markers are defined in an SQLDA and used instead. For more information about how to refer to host variables see “References to Host Variables” on page 115. (Variables do not have to be declared in REXX. there is no declare section. PL/I. and RPG. or trigger. Host variables are defined by statements of the host language. References to Host Variables A host variable is a COBOL data item. C++. see the SQL Programming Concepts book. see “Host Structures” on page 121. SQL procedure. For further information about using host variables.) No variables may be declared outside an SQL declare section with names identical to variables declared inside an SQL declare section. and RPG. All host variables used in an SQL statement should be declared in an SQL declare section in all host languages other than Java.

the value specified is the null value. shows a reference to a host variable. The purposes of the indicator variable are to: v Specify the null value. 116 DB2 UDB for iSeries SQL Reference V5R2 . or v -2 if the null value was returned due to data mapping errors in the select list of an outer subselect. Similarly. if :V1:V2 is used to specify an insert or update value. V1 is undefined. and V2 is set to a negative value. For example. and if V2 is negative. SET variable. The variable designated by the second host-identifier is called an indicator variable and must have a data type of small integer. v Record the seconds portion of a time if the time is truncated on assignment to a host variable. It should be noted that although the null value returned for data mapping errors can be returned on certain scalar functions and for arithmetic expressions. SELECT INTO. A host variable in a CALL statement or in an EXECUTE statement identifies either or both a host variable to which an output parameter value is assigned. A host-variable in the INTO clause of a FETCH. if :V1:V2 is specified in a CALL. In all other contexts a host-variable specifies a value to be passed to DB2 UDB for iSeries from the application program.References to Host Variables The term host-variable. FETCH. SELECT INTO. A negative value of the indicator variable specifies the null value. or VALUES INTO statement and the value returned is null. v Indicate one of the following data mapping errors: – Characters could not be converted – Numeric conversion error (underflow or overflow) – Arithmetic expression error (division by 0) – Date or timestamp conversion error (a date or timestamp that is not within the valid range of the dates for the specified format) – String representation of the datetime value is not valid – Mixed data not properly formed – A numeric value that is not valid – Argument of SUBSTR scalar function is out of range v Record the original length of a truncated string. and a host variable that specifies an input argument value to be passed to the database manager from the application program. or VALUES INTO statement identifies a host variable to which a value from a column of a row is assigned. as used in the syntax diagrams. the result column is not considered null capable unless an argument of the arithmetic expression or scalar function is null capable. The general form of a host-variable reference in all languages other than Java is: :host-identifier INDICATOR :host-identifier Each host-identifier must be declared in the source program. 24 24. The negative value is: v -1 if the value selected was the null value. If V2 is not negative the value specified is the value of V1.

Example Using the PROJECT table. instances of a Java class can be set to a null value. The value specified by the host-variable :V1 is always the value of V1. For host variables referenced in the SELECT statement of a cursor. so provide indicator variables STAFF_IND (SMALLINT) and MAJPROJ_IND (SMALLINT). and null values cannot be assigned to the variable. :STAFF :STAFF_IND. Otherwise. Columns PRSTAFF and MAJPROJ may contain null values. OUT is the default. set the host variable PNAME (VARCHAR(26)) to the project name (PROJNAME). If your data is truncated and there is no indicator variable. the database manager returns a negative value (-407) in the SQLCODE field of the SQLCA. | | | | In C. and the host variable MAJPROJ (CHAR(6)) to the major project (MAJPROJ) for project (PROJNO) ‘IF1000’. Variables defined as Java primitive types can not be set to a null value. the host variable does not have an indicator variable. V2 is set to the number of seconds. see Developer Kit for Java. If IN. or INOUT is not specified. If this form is used and the column contains nulls. the default depends on the context in which the variable is used. V2 is set to the original length of the string). indicator variables are not used. the host variable STAFF (DECIMAL(5. In this case. Thus. ILE RPG. MAJPROJ INTO :PNAME. Instead. IN is the default. C++. the default CCSID of the application requester at the time the SQL statement that contains the host variable is executed unless the CCSID is for a foreign encoding scheme (such as ASCII). The CCSID of a string host variable is either: v The CCSID specified in the DECLARE VARIABLE statement. PRSTAFF. For more information on Java variables. that rule applies to the OPEN statement rather than to the DECLARE CURSOR statement. in which case.2)) to the mean staffing level (PRSTAFF). an SQL statement that references host variables must be within the scope of the declaration of those host variables. no error condition results. this form should not be used unless the corresponding result column cannot contain null values. If the second host-identifier is omitted. If the Java variable is used in an INTO clause. or v If a DECLARE VARIABLE with a CCSID clause is not specified for the host variable. Language Elements 117 . :MAJPROJ :MAJPROJ_IND FROM PROJECT WHERE PROJNO = ’IF1000’ Chapter 2. OUT. the host variable is converted to the default CCSID of the current server. SELECT PROJNAME.References to Host Variables If the value returned is not null. If an assignment requires truncation of the seconds part of time. that value is assigned to V1 and V2 is set to zero (unless the assignment to V1 requires string truncation. and PL/I. The general form of a host-variable reference in Java is: : IN OUT INOUT Java-identifier ( Java-expression ) In Java.

can be defined in the following host languages: v C v v v v C++ ILE RPG ILE COBOL PL/I Where LOBs are allowed. :HV_DEPTNAME. a LOB locator is not needed. that is. the term host-variable in a syntax diagram can refer to a regular host variable. When it is possible to define a host variable that is large enough to hold an entire LOB value and the performance benefit of delaying the transfer of data from the server is not required. or a file reference variable. :HV_MGRNO:IND_MGRNO. a LOB locator variable or LOB file reference variable can have an associated indicator variable. the indicator variable is set and the host variable is unchanged. When a null value is returned from the database. Since these variables are not native data types in host programming languages. The following examples shows a static SQL that uses host variables and a dynamic statement that uses parameter markers: INSERT INTO DEPT VALUES( :HV_DEPTNO. :HV_ADMRDEPT) INSERT INTO DEPT VALUES( ?.References to Host Variables Host Variables in Dynamic SQL In dynamic SQL statements. ?. Like all other host variables. or performance requirements. storage restrictions. ? ) For more information about parameter markers. A parameter marker is a question mark (?) that represents a position in a dynamic SQL statement where the application will provide a value. it is often not acceptable to store an entire LOB value in temporary storage due to host language restrictions. a locator variable. This means that a locator can never point to a null value. see “Parameter Markers” on page 695. LOB locator variables (see “References to LOB Locator Variables”) and LOB file reference variables (see “References to LOB File Reference Variables” on page 119). parameter markers are used instead of host variables. References to LOB Locator Variables A LOB locator variable is a host variable that contains the locator representing a LOB value on the server. which can be defined in the following host languages: v C v C++ v ILE RPG 118 DB2 UDB for iSeries SQL Reference V5R2 . SQL extensions are used and the precompilers generate the host language constructs necessary to represent each variable. a LOB value can be referred to by a LOB locator and portions of the LOB value can be accessed. When storing a entire LOB value at one time is not acceptable. References to LOB Host Variables Regular LOB variables. However. where a host variable would be found if the statement string were a static SQL statement. ?. Indicator variables for LOB locator variables and LOB file reference variables behave in the same way as indicator variables for other data types.

References to Host Variables v ILE COBOL v PL/I See “Manipulating Large Objects (LOBs) With Locators” on page 66 for information on how locators can be used to manipulate LOB values. in C: static volatile SQL TYPE IS CLOB_LOCATOR *loc1. The file referenced must exist at the application requester. updates. the LOB data. SQL extensions are used and the precompilers generate the host language constructs necessary to represent each variable. The term locator-variable. which can be defined in the following host languages: v C v C++ v ILE RPG v ILE COBOL v PL/I Since these are not native data types. A file reference variable represents (rather than contains) the file. and inserts may use file reference variables to store or to retrieve single column values. A locator variable in an SQL statement must identify a LOB locator variable described in the program according to the rules for declaring locator variables. The meta-variable locator-variable can be expanded to include a host-identifier the same as that for host-variable. an error occurs when the locator variable is referenced. just as a LOB locator represents. The length attribute of a file reference variable is assumed to be the maximum length of a LOB. all LOB locators that were acquired by the transaction are released. unpredictable results will occur. As with all other host variables. Database queries. Chapter 2. as used in the syntax diagrams. For example. If a locator variable does not currently represent any value. References to LOB File Reference Variables A LOB file reference variable is used for direct file input and output for a LOB. a file reference variable may have an associated indicator variable. rather than contains. This is always indirectly through an SQL statement. It is the application programmer’s responsibility to guarantee that any LOB locator is only used in SQL statements that are executed at the same server that originally generated the LOB locator. the value of the referenced LOB is null. assume that a LOB locator is returned from one server and assigned to a LOB locator variable. If that LOB locator variable is subsequently used in an SQL statement that is executed at a different server. At transaction commit or any transaction termination. Language Elements 119 . shows a reference to a LOB locator variable. When the indicator variable associated with a LOB locator is null. For example.

120 DB2 UDB for iSeries SQL Reference V5R2 . and UDFS file systems. For more information about file reference variables. When a file is created. it is given the CCSID of the data that is being written to the file. QOpenSys. see the SQL Programming Concepts book.References to Host Variables File reference variables are currently supported in the root (/). To use a file created with a file reference variable. mixed CCSIDs are not supported. the file should be opened in binary mode. Currently.

and V3 are declared as variables within the structure S1. as explained in the SQL Programming with Host Languages book. if V1. is equivalent to: EXEC SQL FETCH CURSOR1 INTO :V1. These rules also apply if a reference to a host structure includes an indicator variable or if a reference to a host variable includes an indicator array. C. The general form of a host variable or host structure reference is: : host-identifier. The first host identifier must name a host structure. If the host structure has m more variables than the indicator array. no variable of the host structure has an indicator variable. host-identifier A host-variable in an expression must identify a host variable (not a structure) described in the program according to the rules for declaring host variables. The reference :S1:S2 is a host structure reference if S1 names a host structure. for example. In C. S1 is the host structure and S2 is its indicator array. The form of a host structure reference is identical to the form of a host variable reference. or C++ structure. If an indicator array or indicator variable is not specified. PL/I. the last m variables of the indicator array are ignored. and the second host identifier must name a host variable within that host structure. The following C example shows a references to host structure. S2 must be either a small integer variable. A host structure reference is equivalent to a reference to each of the host variables contained within the structure in the order which they are defined in the host language structure declaration. host indicator array. or RPG data structure that is referenced in an SQL statement. A host structure can be referenced in any context where a list of host variables can be referenced. If the host structure has m fewer variables than the indicator array. the last m variables of the host structure do not have indicator variables. As used here.Host Structures Host Structures A host structure is a COBOL group. the term host structure does not include an SQLCA or SQLDA. If S1 designates a host structure. :V2. V2. The nth variable of the indicator array is the indicator variable for the nth variable of the host structure. :V3. Language Elements 121 . The qualified form is a host identifier followed by a period and another host identifier. and a host variable: Chapter 2. In addition to structure references. host-identifier INDICATOR : host-identifier. or an array of small integer variables. Host structures are defined by statements of the host language. individual host variables in the host structure or indicator variables in the indicator array can be referenced by qualified names. the statement: EXEC SQL FETCH CURSOR1 INTO :S1.

empno..empno:indstr. char firstname_text[12]. { short int lastname_len.. struct char midint. char lastname_text[15].pemp1. } indstr. } firstname...employee WHERE empno=:pemp1.empno). EXEC SQL SELECT * INTO :pemp1:ind FROM corpdata. short eind struct { short ind1. short ind[14]..empno:eind :pemp1. . strcpy("000220".ind1 122 DB2 UDB for iSeries SQL Reference V5R2 . } pemp1.Host Structures struct { char empno[7]. struct { short int firstname_len. the following references to host variables and host structures are valid: :pemp1 :pemp1..empno :pemp1.. short ind2. char workdept[4]. . } lastname.. In the example above.

Host Structure Arrays Host Structure Arrays In PL/I. it is an occurrence data structure. the last m variables of the indicator array are ignored. If the host structure has m fewer variables than the indicator array. as explained in the SQL Programming with Host Languages book. and C. no variable of the host structure array has an indicator variable. Chapter 2. The form of a host structure array is identical to the form of a host variable reference. If the host structure has m more variables than the indicator array. A host structure array can only be referenced in the FETCH statement when using a multiple-row fetch. If an indicator array or variable is not specified. or in an INSERT statement when using a blocked insert. If S1 designates a host structure. The dimension of the host structure and the indicator array must be equal. or a two dimensional array of small integer host variables. In RPG. it is a one-dimensional table. In COBOL. S2 must be either a small integer host variable. S1 is the host structure array and S2 is its indicator array. the last m variables of the host structure do not have indicator variables. Host structure arrays are defined by statements of the host language. a host structure array is a structure name having a dimension attribute. an array of small integer host variables. The reference :S1:S2 is a reference to host structure array if S1 names a host structure array. Language Elements 123 . EXEC SQL FETCH CURSOR1 FOR 5 ROWS INTO :S1:S2. C++. In the following example. The following diagram specifies the syntax of references to an array of host structures: : host-identifier INDICATOR : host-identifier Arrays of host structures are not supported in REXX.

The schema cannot be QSYS. “Built-In Functions. so an associated program or service program object does not exist for a built-in function. Built-in functions and user-defined sourced functions can be column functions. One way to classify functions is as built-in.Functions Functions A function is an operation denoted by a function name followed by one or more operands that are enclosed in parentheses. | | Another way to classify functions is as column. see “CREATE DISTINCT TYPE” on page 429.” on page 165. These functions allow users to extend the function of the database manager by adding their own or third party vendor function definitions.SYSFUNCS. v Built-in functions are IBM-supplied functions that come with the database manager. An SQL function is defined to the database using only SQL statements. external. The ability to cast between the data types is important because a distinct type is compatible only with itself.25 v User-defined functions are functions that are created using the CREATE FUNCTION statement and registered to the database manager in catalog table QSYS2. A user-defined function resides in the schema in which it was created. The schema cannot be QSYS. and scalar functions such as SUBSTR. A column function receives a set of values for each argument (such as the values of a column) and returns a single-value result for the set of input values. Built-in functions include operator functions such as ″+″. QSYS2. Furthermore. An external function is defined to the database with a reference to an external program or service program that is executed when the function is invoked. The input values to a function are called arguments. or generated user-defined functions for distinct types. scalar. v The database manager automatically generates some user-defined functions when a distinct type is created using the CREATE DISTINCT TYPE statement. 124 DB2 UDB for iSeries SQL Reference V5R2 . For a list of the built-in column and scalar functions and information on these functions. These functions support casting from the distinct type to the source type and from the source type to the distinct type. QSYS2. For example. However. depending on the input data values and result values. user-defined. A user-defined function is either SQL. or sourced. Column functions are sometimes called aggregating functions. column functions such as AVG. The generated cast functions reside in the same schema as the distinct type for which they were created.SYSROUTINES and catalog view QSYS2. see Chapter 3. the catalog does not contain information about built-in functions. A sourced function is defined to the database with a reference to a built-in function or another user-defined function. It represents a relationship between a set of input values and a set of result values. For more information about the functions that are generated for a distinct type. Sourced functions can be used to extend built-in column and scalar functions for use on distinct types. Types of Functions There are several ways to classify functions. These functions provide a single-value result. Built-in functions are implemented internally by the database manager. a function can be passed two input arguments that have date and time data types and return a value with a timestamp data type as the result. 25. built-in functions can be treated as if they exist in QSYS2 and a built-in function name can be qualified with QSYS2. or table functions. or QTEMP. or QTEMP.

Qualified function resolution: When a function is invoked with a function name and a schema name. which is implicitly or explicitly qualified with a schema name. and the data types of the parameters. number of parameters. This process is called function resolution. the database manager only searches the specified schema to Chapter 2. followed by parentheses that enclose the arguments to the function. Language Elements 125 . When any function is invoked. Thus. each function is uniquely identified by its function signature. Each reference to a scalar or column function (either built-in or user-defined) conforms to the following syntax: function-name ( ALL DISTINCT . the number of parameters. function name.Functions A scalar function receives a single value for each argument and returns a single-value result. Function resolution is similar for functions that are invoked with a qualified or unqualified function name with the exception that for an unqualified name. expression is the same as it is for a scalar or column function. see the description of the FROM clause on “from-clause” on page 337. Within the database. the database manager must determine which function to execute. which is its schema name. Built-in functions and user-defined functions can be scalar functions. and types of parameters can exist in multiple schemas. Each argument is a single value.). The functions that are created for distinct types are also scalar functions. a table function can take a file and convert it to a table. or parameters with different data types. Or. expression ) The ALL or DISTINCT keyword can only be specified for a column function or a user-defined function that is sourced on a column function. the database manager needs to search more than one schema. get data from the World Wide Web and tabularize it. Table functions can be used to apply SQL language processing power to data that is not DB2 data or to convert such data into a DB2 table. a function with the same name. For example. or access a Lotus Notes database and return information about mail messages. | Each reference to a table function conforms to the following syntax: TABLE ( function-name ( . a schema can contain several functions that have the same name but each of which have a different number of parameters. | | | | | | | | | A table function returns a table for the set of arguments it receives. A table function can be defined as an external function or as an SQL function (a table function cannot be a sourced function. For more details on referencing a table function. expression ) ) correlation-clause In the above syntax. Function resolution A function is invoked by its function name. A table function can only be referenced in the FROM clause of a subselect.

If more than one schema contains the function instance with the best fit (the function signatures are identical except for the schema name). For information on the promotion of data types. the database manager determines which function is the best fit for the invocation by comparing the argument and parameter data types. Note that neither the data type of the result of the function nor the type of function (column or scalar) under consideration enters into this determination. v The number of input parameters in the function instance matches the number of arguments in the function invocation. ensure that the path is specified so that the intended function is selected. If no function in the schema meets these criteria.Functions resolve which function to execute. For information on the promotion of data types. the database manager needs to search more than one schema to resolve the function instance to execute. If the data types of all the parameters for a given function are the same as those of the arguments in the function invocation. that function is the best fit. Determining the Best Fit There might be more than one function with the same name that is a candidate for execution. the schema is implicitly assumed at the front of the path. v The data type of each input argument of the function invocation matches or is promotable to the data type of the corresponding parameter of the function instance. v The data type of each input argument of the function invocation matches or is promotable to the data type of the corresponding parameter of the function instance. This comparison of data types results in one best fit. The database manager finds the appropriate function instance when all of the following conditions are true: v The name of the function instance matches the name in the function invocation. Built-in functions logically exist in schema QSYS2. If there is no 126 DB2 UDB for iSeries SQL Reference V5R2 . see “Promotion of Data Types” on page 76. when an unqualified function name is specified. If no function in the schema meets these criteria. For each schema in the path (for information on paths see “SQL Path” on page 53). an error occurs. v The number of input parameters in the function instance matches the number of function arguments in the function invocation. an error occurs. This comparison of data types results in one best fit. which is the choice for execution (see “Determining the Best Fit”). The SQL path contains the list of schemas to search. the database manager selects the function whose schema is earliest in the SQL path. In that case. Unqualified function resolution: When a function is invoked with only a function name. Therefore. which is the choice for execution (see “Determining the Best Fit”). the database manager selects a candidate function based on the following criteria: v The name of the function instance matches the name in the function invocation. If schema QSYS2 is not explicitly specified in the SQL path. Function resolution applies to all functions. see “Promotion of Data Types” on page 76. After the database manager identifies the candidate functions. it selects the candidate with the best fit as the function instance to execute (see “Determining the Best Fit”). A candidate function is not selected for a schema if one or more of the criteria is not met. including built-in functions.

. which is VARCHAR.. if one function has a data type that fits the function invocation better than the data types in the other functions.. Function 5 is chosen as the function instance to execute based on the following evaluation: v Function 6 is eliminated as a candidate because schema TODD is not in the SQL path.) 2. Chapter 2. If the data type of the first parameter for more than one candidate function fits the function invocation equally well. (Any length. INT. ADDIT(INTCOL1. fit the data type of the first argument of the function invocation.. DOUBLE. for the second parameter. ″SMITH″... both named FUNA. Example 2: Assume that functions were created with these partial CREATE FUNCTION statements: 1.. JOHNSON. Language Elements 127 . DOUBLE) . DOUBLE) .. Therefore. 3. Both MYSCHEMA.ADDIT (INT. TAYLOR. TODD. DECIMALCOL ) . DOUBLE) .ADDIT (INT. equally well. DECIMALCOL) . DOUBLE.SUBIT (INT.. 4. Also assume that a function with three arguments of data types VARCHAR(10).. REAL.FUNA (VARCHAR(10).ADDIT (REAL) . JOHNSON. DECIMAL) .. SMITH. However.. scale. INT.FUNA functions are candidates for this function invocation because they meet the criteria specified in “Function resolution” on page 125. 3. repeat this process for the next argument of the function invocation... using the following method: 1.Functions exact match. INT.. DECIMAL) as follows: SELECT .FUNA (VARCHAR(10). DOUBLE) .. The data types of the first parameter for the two function instances in the schema. CREATE FUNCTION MYSCHEMA. DOUBLE) . the data type of the first function (INT) fits the data type of the second argument (SMALLINT) better than the data type of second function (REAL). 6.. The following examples illustrate function resolution. SMITH. which are both VARCHAR.ADDIT (INT. 5. Continue for each argument until a best fit is found.FUNA( VARCHARCOL. Example 1: Assume that MYSCHEMA contains two functions. and CCSID attributes of the data types are not considered in the comparison. 7. For this argument. INT) . and DECIMAL is invoked with a qualified name: MYSCHEMA. 2. INT.. CREATE CREATE CREATE CREATE CREATE CREATE CREATE FUNCTION FUNCTION FUNCTION FUNCTION FUNCTION FUNCTION FUNCTION SMITH. The function is invoked with three data types (INT.. Compare the data type of the first argument in the function invocation to the data type of the first parameter in each function..ADDIT (INT. that were created with these partial CREATE FUNCTION statements. INT. precision. INT. the database manager selects the first MYSCHEMA. that function is the best fit... ″JOHNSON″. the database manager compares the data types in the parameter lists from left to right. Also assume that the SQL path at the time an application invokes a function is ″TAYLOR″. DOUBLE) ..ADDIT (CHAR(5). The precedence list for the promotion of data types in “Promotion of Data Types” on page 76 shows the data types that fit each data type in best-to-worst order. CREATE FUNCTION MYSCHEMA. SMALLINTCOL.FUNA function as the function instance to execute. INT. INTCOL2.. SMALLINT.

.. Function Invocation Once the function is selected. The function is invoked with two data types (SMALLINT. Function 2 is chosen as the function instance to execute based on the following evaluation: v All three functions are candidates for this function invocation because they meet the criteria specified in “Function resolution” on page 125. If this result data type is not compatible within the context in which the function is invoked.Functions v Function 7 in schema TAYLOR is eliminated as a candidate because it does not have the correct function name. MYFUNC(SINTCOL1..0)). 3.. DECIMAL(9.MYFUNC (INT. v Of the remaining candidates.. FLOAT) . DECIMAL) as follows: SELECT .MYFUNC (INT. an error will occur.. Example 3: Assume that functions were created with these partial CREATE FUNCTION statements: 1. NUMERIC(8. For example. given functions named STEP defined with different data types as the result: STEP(SMALLINT) RETURNS CHAR(5) STEP(DOUBLE) RETURNS INTEGER and the following function reference (where S is a SMALLINT column): 128 DB2 UDB for iSeries SQL Reference V5R2 . v Function 1 in schema SMITH is eliminated as a candidate because the INT data type is not promotable to the CHAR data type of the first parameter of Function 1. v Function 2 is a candidate because the data types of its parameters match or are promotable to the data types of the arguments. CREATE FUNCTION KNAPP. CREATE FUNCTION BESTGEN.0)) . DECIMALCOL) . ″BESTGEN″. the database manager selects Function 5 because schema JOHNSON comes before schema SMITH in the SQL path. v Both Function 4 and 5 in schema JOHNSON are candidates because the data types of their parameters match or are promotable to the data types of the arguments. 2.. the data type of the second parameter of Function 5 (INT) is a better match of the second argument (INT) than the data type of Function 4 (DOUBLE).. v The second parameters of Function 1 (DECIMAL) and Function 2 (NUMERIC) are equally good fits for the second argument (DECIMAL). Function 5 is chosen as the better candidate because although the data types of the first parameter of both functions (INT) match the first argument (INT). v Function 2 is finally chosen because ″KNAPP″ precedes ″BESTGEN″ in the SQL path. v Function 3 in schema ROMANO is eliminated because the second parameter (FLOAT) is not as good a fit for the second argument (DECIMAL) as the second parameter of either Function 1 (DECIMAL) or Function 2 (NUMERIC). Each function is defined to return a result with a specific data type. v Function 3 in schema SMITH is eliminated as a candidate because it has the wrong number of parameters. ″KNAPP″. Also assume that the SQL path at the time an application invokes a function is ″ROMANO″.MYFUNC (INT. Function 2 and 5.. However.. CREATE FUNCTION ROMANO. there are still possible reasons why the use of the function may not be permitted.

This includes the case where precision. or CCSID differs between the argument and the parameter. length. the arguments are converted to the data type of the parameter at execution using the same rules as assignment to columns (see “Assignments and Comparisons” on page 81). Language Elements 129 . Chapter 2. 3 +STEP(S) then. In cases where the arguments of the function invocation were not an exact match to the data types of the parameters of the selected function. the first STEP is chosen. because there is an exact match on argument type.Functions SELECT . An error occurs on the statement because the result type is CHAR(5) instead of a numeric type as required for an argument of the addition operator.. scale..

operator function (expression) constant column-name host-variable special-register (scalar-subselect) labeled-duration cast-specification case-expression + − operator: CONCAT \ / * ** + − labeled-duration: function (expression) constant column-name host-variable YEAR YEARS MONTH MONTHS DAY DAYS HOUR HOURS MINUTE MINUTES SECOND SECONDS MICROSECOND MICROSECONDS Without Operators If no operators are used. 130 DB2 UDB for iSeries SQL Reference V5R2 .Expressions Expressions An expression specifies a value. the result of the expression is the specified value. Example SALARY :SALARY ’SALARY’ MAX(SALARY) With Arithmetic Operators If arithmetic operators are used. the result of the expression is a number derived from the application of the operators to the values of the operands.

The first character of the token following a prefix operator must not be a plus or minus sign. The infix operators. subtraction. If any operand has the null value. Two Decimal Operands If both operands are decimal. and the result is a large integer unless either (or both) operand is a big integer. The value of the second operand of division must not be zero. /. Language Elements 131 . the operation is performed with a temporary copy of one of the operands. If the operation is addition or subtraction and the operands do not have the same scale. division. *. the result can be null. The result of an exponentiation (**) operator is a double-precision floating-point number. Chapter 2. and exponentiation. The copy of the shorter operand is extended with trailing zeros so that its fractional part has the same number of digits as the longer operand. blanks must precede and follow a minus sign to avoid any ambiguity with COBOL host variable names (which allow use of a dash). Two Integer Operands If both operands of an arithmetic operator are integers with zero scale.A is large integer. Arithmetic operators must not be applied to character strings. The prefix operator . The result of any decimal arithmetic operation is a decimal number with a precision and scale that are dependent on the operation and the precision and scale of the operands. For example.Expressions If any operand can be null. in which case the result is a big integer.(unary minus) reverses the sign of a nonzero operand. and **. USER+2 is invalid. respectively. the operation is performed in decimal using a temporary copy of the integer that has been converted to a decimal number with precision and scale 0 as defined in the following table: Operand Column or variable: big integer Column or variable: large integer Column or variable: small integer Constant (including leading zeros) Precision of Decimal Copy 19 11 5 Same as the number of digits in the constant If one operand is an integer with nonzero scale. Integer and Decimal Operands If one operand is an integer with zero scale and the other is decimal. the operation is performed in decimal. In COBOL. multiplication. it is first converted to a decimal operand with the same precision and scale. Any remainder of division is lost. +. If either integer operand has nonzero scale. If the data type of A is small integer. it is converted to a decimal operand with the same precision and scale. the result of the expression is the null value. The result of an integer arithmetic operation (including unary minus) must be within the range of large integers. specify addition. The result of the other operators depends on the type of the operand. -. the data type of . The prefix operator + (unary plus) does not change its operand. the operation is performed in binary.

create a function with the arithmetic operator as its source. if any element of an expression is a floating-point number. if there were distinct types INCOME and EXPENSES.s+s’).2) data types. EXPENSES ) RETURNS DECIMAL(8. then the following user-defined function. The result of a floating-point operation must be within the range of floating-point numbers. The symbols p and s denote the precision and scale of the first operand and the symbols p' and s' denote the precision and scale of the second operand. The operands are first converted to double-precision floating-point numbers.2) SOURCE "-" ( DECIMAL.p’-s’) +max(s. CREATE FUNCTION REVENUE ( INCOME. Decimal Arithmetic in SQL The following formulas define the precision and scale of the result of decimal operations in SQL. Distinct Types as Operands A distinct type cannot be used with arithmetic operators even if its source data type is numeric.Expressions Unless specified otherwise. Since the order in which operands are processed may be implicitly modified by the optimizer (for example.s’). an application should not depend on the results being precisely the same each time an SQL statement is executed that uses floating-point operands. The precision is min(31. all functions and operations that accept decimal numbers allow a precision of up to 31 digits.2) SOURCE "-" ( DECIMAL. CREATE FUNCTION "-" ( INCOME. The result of a decimal operation must not have a precision greater than 31. An operation involving a floating-point number and a decimal number is performed with a temporary copy of the decimal number that has been converted to double-precision floating point.s’)+1). DECIMAL) Alternately. Floating-Point Operands If either operand of an arithmetic operator is floating point.(minus) operator could be overloaded using a user-defined function to subtract the new data types. the operation is performed in floating point. DECIMAL) 132 DB2 UDB for iSeries SQL Reference V5R2 . Division: The precision of the result of division is 31. Addition and Subtraction: The scale of the result of addition and subtraction is max (s. Thus. both of which had DECIMAL(8. An operation involving a floating-point number and an integer is performed with a temporary copy of the integer converted to double-precision floating point. EXPENSES ) RETURNS DECIMAL(8. | | | | | | | The order in which floating-point operands (or arguments to functions) are processed can slightly affect results because floating-point operands are approximate representations of real numbers. To perform an arithmetic operation. could be used to subtract one from the other. the result of the expression is a double-precision floating-point number. The scale is 31-p+s-s'. The scale must not be negative. For example.max(p-s. Multiplication: The precision of the result of multiplication is min (31. the .p+p’) and the scale is min(31. if necessary. REVENUE. the optimizer may decide what degree of parallelism to use and what access plan to use).

maximum length of a CHAR) BLOB(z) where z = MIN(x + y. Chapter 2..... And the other operand is . Note that a binary string cannot be concatenated with a character string. CHAR(y)* or VARCHAR(y)* or CLOB(y)* or GRAPHIC(y) or VARGRAPHIC(y) or DBCLOB(y) CHAR(y)* or VARCHAR(y)* or GRAPHIC(y) or VARGRAPHIC(y) The data type of the result column is . maximum length of a DBCLOB) | | DBCLOB(x) | | VARGRAPHIC(x) VARGRAPHIC(z) where z = MIN(x + y. maximum length of a DBCLOB) VARGRAPHIC(z) where z = MIN(x + y. including character strings defined as FOR BIT DATA. The result of the expression is a string. maximum length of a VARCHAR) CHAR(z) where z = MIN(x + y. The data type of the result is determined by the data types of the operands. maximum length of a VARGRAPHIC) CLOB(z) where z = MIN(x + y... maximum length of a CLOB) VARCHAR(z) where z = MIN(x + y. maximum length of a VARGRAPHIC) CHAR(y)* SBCS data or GRAPHIC(y) GRAPHIC(y) or VARGRAPHIC(y) GRAPHIC(y) CHAR(y) or VARCHAR(y) or CLOB(y) CHAR(y) or VARCHAR(y) CHAR(y) CHAR(y) BLOB(y) GRAPHIC(z) where z = MIN(x + y. maximum length of a VARCHAR) VARCHAR(z) where z = MIN(x + y. DBCLOB(z) where z = MIN(x + y. maximum length of a GRAPHIC) DBCLOB(z) where z = MIN(x + y. Language Elements 133 . maximum length of a BLOB) VARCHAR(x) CHAR(x) mixed data CHAR(x) SBCS data BLOB(x) Note: * Character strings are only allowed when the other operand is a graphic string if the graphic string is Unicode. Result Data Types With Concatenation If one operand column is . The data type of the result is summarized in the following table: Table 21. The operands of concatenation must be compatible strings that are not distinct types. maximum length of a VARGRAPHIC) | | | | | | | | | | | | | | | | | | GRAPHIC(x) GRAPHIC(x) CLOB(x)* VARCHAR(x)* CLOB(x) CHAR(y)* mixed data VARGRAPHIC(z) where z = MIN(x + y.Expressions With the Concatenation Operator The concatenation operator (CONCAT or ||) combines two strings.

while the second operand is a character string beginning with a “shift-out” character (X'0E'). The actual length of the result is the sum of the lengths of the operands unless redundant shifts are eliminated. the result consists of the first operand string followed by the second.. in which case. the result can be null. Otherwise. For more information. Unicode data DBCS data bit data mixed data SBCS data And the other operand is .. v If non-blanks are truncated.. v If one operand is mixed data and the other is SBCS data. the result is the null value. Unicode or DBCS or mixed or SBCS data DBCS data mixed or SBCS or bit data mixed or SBCS data SBCS data The data type of the result column is . The CCSID of the result is determined by the CCSID of the operands as explained under “Conversion Rules for Operations That Combine Strings” on page 98. The code point for the | character varies. depending on the CCSID. Thus.Expressions Table 22.. the result is bit data... see “Maximum row sizes” on page 551. an error occurs. Example Concatenate the column FIRSTNME with a blank and the column LASTNAME. and if either is null. Result Encoding Schemes With Concatenation If one operand column is . this does not necessarily mean that the result is well-formed mixed data. If the expression is in the select-list. However. the result is mixed data. the actual length is two less than the sum of the lengths of the operands. these two bytes are eliminated from the result. If either operand can be null. The CONCAT operator should be used instead of the || operator. the length attribute may be further reduced in order to fit within the maximum record size. With mixed data this result will not have redundant shift codes “at the seam”.26 v If only blanks are truncated no warning or error occurs. 134 DB2 UDB for iSeries SQL Reference V5R2 . FIRSTNME CONCAT ’ ’ CONCAT LASTNAME 26. Note that as a result of these rules: v If any operand is bit data. Unicode data DBCS data bit data mixed data SBCS data | | | | | | If the sum of the lengths of the operands exceeds the maximum length attribute of the resulting data type: v The length atttribute of the result is the maximum length of the resulting data type. if the first operand is a string ending with a “shift-in” character (X'0F').

To be properly interpreted.6) number. TIME. the result of the expression is the null value. and dd the number of days. days. To be properly interpreted. as in the expression HIREDATE BRTHDATE. The result of subtracting one time value from another is a time duration. or TIMESTAMP. MONTHS. and MICROSECOND. and subtracted. HOURS. and ss the number of seconds. SECONDS.Expressions | | | | | | | Scalar Subselect A scalar subselect as supported in an expression is a subselect. ss. 27. Timestamp duration A timestamp duration represents a number of years. mm. A labeled duration can only be used as an operand of an arithmetic operator in which the other operand is a value of data type DATE. The result of subtracting one date value from another. expressed as a DECIMAL(6. The result of subtracting one timestamp value from another is a timestamp duration. the expression HIREDATE + 2 MONTHS + 14 DAYS is valid whereas the expression HIREDATE + (2 MONTHS + 14 DAYS) is not. expressed as a DECIMAL(20. hours. mm. To be properly interpreted. MINUTES. See “subselect” on page 332 for more information. respectively.0) number. seconds. SECOND. months. and microseconds. Datetime Operands and Durations Datetime values can be incremented. minutes. where yyyy. mm the number of months. Chapter 2. DAYS.0) number. Thus. seconds. dd. MONTH. and microseconds. the number of years. or MICROSECONDS27. and seconds. the number must have the format yyyymmddhhmmsszzzzzz. These operations may involve decimal numbers called durations. There are four types of durations: Labeled Durations (see diagram on page 125) A labeled duration represents a specific unit of time as expressed by a number (which can be the result of an expression) followed by one of the seven duration keywords: YEARS. where yyyy represents the number of years. enclosed in parentheses. hh. hours. Language Elements 135 . The number specified is converted as if it were assigned to a DECIMAL(15. the number must have the format hhmmss where hh represents the number of hours. DAY. and zzzzzz represent. HOUR. is a date duration. the number must have the format yyyymmdd. If the select list element is an expression that is simply a column name. expressed as a DECIMAL(8. days. the labeled durations are 2 MONTHS and 14 DAYS. MINUTE. Note that the singular form of these keywords is also acceptable: YEAR. mm the number of minutes. months. If the subselect does not return a row. A duration is a positive or negative number representing an interval of time. and days. months. In both of these expressions. decremented. that returns a single row consisting of a single column value.0) number. the result column name is based on the name of the column. Date Duration A date duration represents a number of years. minutes. Time Duration A time duration represents a number of hours. minutes.

DATE1 is subtracted from DATE2. v If the second operand is a timestamp. a string representation of a timestamp. v If one operand is a timestamp. or seconds. Date Arithmetic Dates can be subtracted. If a datetime value is the operand of addition. The specific rules governing the use of the subtraction operator with datetime values follow: v If the first operand is a date. a time duration. The rules for the use of the subtraction operator on datetime values are not the same as those for addition because a datetime value cannot be subtracted from a duration. v If the first operand is a timestamp. Subtracting Dates: The result of subtracting one date (DATE2) from another (DATE1) is a date duration that specifies the number of years. months. a string representation of a date. the second operand must be a timestamp. the other operand must be a duration. the other operand must be a date duration or labeled duration of years. v Neither operand of the subtraction operator can be a parameter marker. the second operand must be a date.DAY(DATE2) where N = the last day of MONTH(DATE2). or a string representation of a date. incremented.DAY(DATE2). The specific rules governing the use of the addition operator with datetime values follow: v If one operand is a date. The following procedural description clarifies the steps involved in the operation RESULT = DATE1 . The data type of the result is DECIMAL(8. or a duration. or string representation of a time. the other operand must be a time duration or a labeled duration of hours. or days. a string representation of a time. or a labeled duration of hours. If DAY(DATE2) > DAY(DATE1) then DAY(RESULT) = N + DAY(DATE1) . Any type of duration is valid. and days between the two dates. the other operand must be a duration. minutes. v If the second operand is a date. MONTH(DATE2) is then incremented by 1.DATE2. If DATE1 is greater than or equal to DATE2. or decremented. or days. v If one operand is a time. the first operand must be a date. the first operand must be a time. months. or a labeled duration of years. and because the operation of subtracting two datetime values is not the same as the operation of subtracting a duration from a datetime value. v If the first operand is a time. the first operand must be a timestamp or a string representation of a timestamp. minutes. and the sign of the result is made negative. a date duration.0). v Neither operand of the addition operator can be a parameter marker. v If the second operand is a time. the second operand must be a time. or seconds. DATE2 is subtracted from DATE1.Expressions Datetime Arithmetic in SQL The only arithmetic operations that can be performed on datetime values are addition and subtraction. months. 136 DB2 UDB for iSeries SQL Reference V5R2 . however. If DATE1 is less than DATE2. If DAY(DATE2) <= DAY(DATE1) then DAY(RESULT) = DAY(DATE1) .

Thus.MONTH(DATE2).MONTH(X) MONTHS . Adding or subtracting a duration of days will. Similarly. adding one month to a given date gives the same date one month later unless that date does not exist in the later month. the date is decremented by the specified number of days. a duration of 0 years. When a positive date duration is added to a date.'12/31/1999' is 215 (or. 0001 and December 31. whether positive or negative. and a warning indicator is set in the SQLCA whenever an end-of-month adjustment is necessary.YEAR(DATE2).0) number. 9999 inclusive. in that order. (For the purposes of this operation. as is the day unless the result would be February 29 of a non-leap-year.X. months. For example. For example. and potentially the month and year.) The result must fall between the dates January 1.YEAR(X) YEARS When adding durations to dates.MONTH(DATE2). years are affected. The day portion of the date is unchanged unless the result would be invalid (September 31. YEAR(DATE2) is then incremented by 1. If MONTH(DATE2) > MONTH(DATE1) then MONTH(RESULT) = 12 + MONTH(DATE1) . in that order. If a duration of years is added or subtracted. the day is changed to 28. then. only months and. The month is unchanged. and SQLWARN6 in the SQLCA is set to ’W’ to indicate the end-of-month adjustment. January 28 plus one month gives February 28. where X is a positive DECIMAL(8. where X is a positive DECIMAL(8. if necessary.Expressions If MONTH(DATE2) <= MONTH(DATE1) then MONTH(RESULT) = MONTH(DATE1) . Date durations. months. Adding months to a date. the date is incremented by the specified number of years. As with labeled durations. YEAR(RESULT) = YEAR(DATE1) . a month denotes the equivalent of a calendar page.DAY(X) DAYS . only the year portion of the date is affected. and one month added to January 29. and SQLWARN6 in the SQLCA is set to ’W’ to indicate the end-of-month adjustment. February 29. the date is set to that of the last day of the later month. starting with the page on which the date appears. and 15 days). In that case. affect the day portion of the date. In this case. or a negative date duration is added to a date. Chapter 2. is like turning the pages of a calendar. Language Elements 137 . or 31 results in either February 28 or. for example). 30. DATE1 . of course.0) number. is equivalent to the expression: DATE1 + YEAR(X) YEARS + MONTH(X) MONTHS + DAY(X) DAYS When a positive date duration is subtracted from a date. for a leap year. the result of DATE('3/15/2000') . or a negative date duration is subtracted from a date. Adding a labeled duration of DAYS will not cause an end-of-month adjustment. the result is a valid date. and days. Incrementing and Decrementing Dates: The result of adding a duration to a date. and years. the day is set to the last day of the month. or of subtracting a duration from a date. Thus DATE1 + X. In this case. 2 months. if a duration of months is added or subtracted. may also be added to and subtracted from dates. is itself a date. is equivalent to the expression: DATE1 .

If TIME1 is less than TIME2. the result of TIME('11:02:26') . or of subtracting a duration from a time. For example.TIME2. For example. The data type of the result is DECIMAL(6. TIME2 is subtracted from TIME1. 29 minutes. and the sign of the result is made negative. one month. When labeled date durations are added to a date.HOUR(TIME2). however. If SECOND(TIME2) > SECOND(TIME1) then SECOND(RESULT) = 60 + SECOND(TIME1) . If TIME1 is greater than or equal to TIME2. and seconds between the two times.MONTHS .Expressions Note: If one or more months is added to a given date and then the same number of months is subtracted from the result.MINUTE(TIME2). and one day from a date. The order in which labeled date durations are added to and subtracted from dates can affect the results. a specific order must be used. Incrementing and Decrementing Times: The result of adding a duration to a time.MINUTE(TIME2). TIME1 is subtracted from TIME2. If SECOND(TIME2) <= SECOND(TIME1) then SECOND(RESULT) = SECOND(TIME1) . Subtracting Times: The result of subtracting one time (TIME2) from another (TIME1) is a time duration that specifies the number of hours.1 DAY . does not produce the same result as DATE(’2002–01–31’) + 2 MONTHS will result in a date of 2002–03–31. Also note that logically equivalent expressions may not produce the same result. HOUR(RESULT) = HOUR(TIME1) .1 MONTH .YEARS. When labeled date durations are subtracted from a date. For compatibility with the results of adding or subtracting date durations. specify: DATE1 . specify: DATE1 + 1 YEAR + 1 DAY To subtract one year.SECOND(TIME2). and 30 seconds). The following procedural description clarifies the steps involved in the operation RESULT = TIME1 . minutes. If MINUTE(TIME2) <= MINUTE(TIME1) then MINUTE(RESULT) = MINUTE(TIME1) . incremented. to add one year and one day to a date. Any overflow or 138 DB2 UDB for iSeries SQL Reference V5R2 . HOUR(TIME2) is then incremented by 1. the final date is not necessarily the same as the original date.SECOND(TIME2).1 YEAR Time Arithmetic Times can be subtracted. or decremented.'00:32:56' is 102930 (a duration of 10 hours.0). For example: (DATE(’2002–01–31’) + 1 MONTH) + 1 MONTH will result in a date of 2002–03–28. specify them in the order of DAYS . If MINUTE(TIME2) > MINUTE(TIME1) then MINUTE(RESULT) = 60 + MINUTE(TIME1) . is itself a time. specify them in the order of YEARS + MONTHS + DAYS. MINUTE(TIME2) is then incremented by 1.

minutes. which must be within the range of valid dates. If MICROSECOND(TS2) <= MICROSECOND(TS1) then MICROSECOND(RESULT) = MICROSECOND(TS1) MICROSECOND(TS2). Similarly. If MICROSECOND(TS2) >MICROSECOND(TS1) then MICROSECOND(RESULT) = 1000000 + MICROSECOND(TS1) . TS1 is subtracted from TS2 and the sign of the result is made negative. Chapter 2. The result is a time that has been incremented or decremented by the specified number of hours. TIME1 + X. or decremented. days. Time durations. Date and time arithmetic is performed as previously defined. seconds. of course. If TS1 is greater than or equal to TS2. months. Subtracting Timestamps: The result of subtracting one timestamp (TS2) from another (TS1) is a timestamp duration that specifies the number of years. in that order. and potentially the minutes and hours. The minutes and seconds are unchanged. The date part of the timestamps is subtracted as specified in the rules for subtracting dates. and seconds. Microseconds overflow into seconds. only minutes and. or of subtracting a duration from a timestamp.HOUR(TS2). is itself a timestamp. If a duration of hours is added or subtracted. minutes.6). hours. except that an overflow or underflow of hours is carried into the date part of the result. The seconds portion of the time is unchanged. The data type of the result is DECIMAL(20. incremented. Incrementing and Decrementing Timestamps: The result of adding a duration to a timestamp. The seconds and minutes part of the timestamps are subtracted as specified in the rules for subtracting times.MICROSECOND(TS2) and SECOND(TS2) is incremented by 1. If TS1 is less than TS2. TS2 is subtracted from TS1. also can be added to and subtracted from times. and microseconds between the two timestamps.Expressions underflow of hours is discarded.HOUR(TS2) and DAY(TS2) is incremented by 1. Language Elements 139 . if a duration of minutes is added or subtracted. if necessary.0) number. whether positive or negative. Adding or subtracting a duration of seconds will.TS2. however. hours are affected. thereby ensuring that the result is always a time. is equivalent to the expression: TIME1 + HOUR(X) HOURS + MINUTE(X) MINUTES + SECOND(X) SECONDS Timestamp Arithmetic Timestamps can be subtracted. only the hours portion of the time is affected. If HOUR(TS2) > HOUR(TS1) then HOUR(RESULT) = 24 + HOUR(TS1) . The following procedural description clarifies the steps involved in the operation RESULT = TS1 . If HOUR(TS2) <= HOUR(TS1) then HOUR(RESULT) = HOUR(TS1) . where “X” is a DECIMAL(6. affect the seconds portion of the time.

exponentiation is applied after prefix operators (such as -. the first operation (CONCAT) combines the character strings in the variables YYYYMM and DD into a string representing a date. The second operation is multiplication because it is at a higher precedence level than the second addition operator and it is to the left of the division operator. Operators at the same precedence level are applied from left to right. Finally.(when used for signed numeric values) ** *. the remaining addition is performed. || +. DATECOL .:YYYYMM CONCAT :DD ┌┴┐ │2│ └─┘ ┌┴┐ │1│ └─ 140 DB2 UDB for iSeries SQL Reference V5R2 . When the order of evaluation is not specified by parentheses. /. . . The third operation is division because it is at a higher precedence level than the second addition operator. The following table shows the priority of all operators.10 * (SALARY + BONUS) + SALARY / :VAR3 ┌┴┐ │2│ └─┘ ┌┴┐ │1│ └─┘ ┌┴┐ │4│ └─┘ ┌┴┐ │3│ └─┘ Example 2: In this example. The second operation (-) then subtracts that date from the date being processed in DATECOL. The result is a date duration that indicates the time elapsed between the two dates. unary minus) and before multiplication and division. Priority 1 2 3 4 Operators +.(when used between two operands) Example 1: In this example.Expressions Precedence of Operations Expressions within parentheses are evaluated first. Multiplication and division are applied before addition and subtraction. CONCAT. 1. the first operation is the addition in (SALARY + BONUS) because it is within parenthesis.

and the result when that condition is true. There must be at least one result-expression in the CASE expression with a defined data type. Chapter 2. Note that when a when-clause evaluates to unknown (because of nulls). In general. the when-clause is not true and hence is treated the same way as a when-clause that evaluates to false. result-expression or NULL Specifies the value that follows the THEN keyword and ELSE keywords. v must not include a function that is non-deterministic or has an external action. If no when-clause evaluates to true and the ELSE keyword is not present then the result is NULL. the value of the case-expression is the value of the result-expression following the first (leftmost) when-clause that evaluates to true. where the attributes of the result are determined based on the “Rules for Result Data Types” on page 94. searched-when-clause Specifies a search-condition that is applied to each row or group of table data presented for evaluation. If no when-clause evaluates to true and the ELSE keyword is present then the result is the value of the ELSE result-expression or NULL.Expressions CASE Expressions ELSE NULL CASE searched-when-clause simple-when-clause END ELSE result-expression searched-when-clause: WHEN search-condition THEN result-expression NULL simple-when-clause: expression WHEN expression THEN result-expression NULL CASE expressions allow an expression to be selected based on the evaluation of one or more conditions. All result-expressions must have compatible data types. Language Elements 141 . simple-when-clause Specifies that the value of the expression prior to the first WHEN keyword is tested for equality with the value of the expression that follows each WHEN keyword. NULL cannot be specified for every case. The data type of the expression prior to the first WHEN keyword: v must be compatible with the data types of the expression that follows each WHEN keyword. It also specifies the result when that condition is true.

but who are not fully paid on commission: SELECT EMPNO...25 v The following CASE expressions are equivalent: SELECT LASTNAME. SALARY+COMM FROM EMPLOYEE WHERE (CASE WHEN SALARY=0 THEN NULL ELSE COMM/SALARY END) > 0. FIRSTNME.e2.eN) Examples v If the first character of a department number is a division in the organization. For example. NULLIF and COALESCE. false. CASE SUBSTR(WORKDEPT. LASTNAME. Table 23. LASTNAME. the following code finds the employees who earn more than 25% of their income from commission. then a CASE expression can be used to list the full name of the division to which each employee belongs: SELECT EMPNO. A CASE expression can be used to group these and to show the level of education.Expressions search-condition Specifies a condition that is true... or unknown about a row or group of table data.1) WHEN ’A’ THEN ’Administration’ WHEN ’B’ THEN ’Human Resources’ WHEN ’C’ THEN ’Accounting’ WHEN ’D’ THEN ’Design’ WHEN ’E’ THEN ’Operations’ END FROM EMPLOYEE v The number of years of education are used in the EMPLOYEE table to give the education level. ELSE ’Unknown’ END FROM EMPLOYEE 142 DB2 UDB for iSeries SQL Reference V5R2 . SELECT EMPNO. that are specialized to handle a subset of the functionality provided by CASE... WORKDEPT.. There are two scalar functions.1. Equivalent CASE Expressions CASE Expression CASE WHEN e1=e2 THEN NULL ELSE e1 END CASE WHEN e1 IS NOT NULL THEN e1 ELSE e2 END CASE WHEN e1 IS NOT NULL THEN e1 ELSE COALESCE(e2.e2) COALESCE(e1.eN) END Equivalent Expression NULLIF(e1.. The following table shows the equivalent expressions using CASE or these functions. CASE WHEN EDLEVEL < 15 THEN ’SECONDARY’ WHEN EDLEVEL < 19 THEN ’COLLEGE’ ELSE ’POST GRADUATE’ END FROM EMPLOYEE v Another interesting example of CASE statement usage is in protecting from division by 0 errors.. CASE WHEN LASTNAME = ’Haas’ THEN ’President’ ..e2) COALESCE(e1. The search-condition must not include a subquery in an EXISTS or IN predicate. MIDINIT.

..Expressions SELECT LASTNAME. CASE LASTNAME WHEN ’Haas’ THEN ’President’ . ELSE ’Unknown’ END FROM EMPLOYEE Chapter 2. Language Elements 143 .

144 DB2 UDB for iSeries SQL Reference V5R2 . For more information see “Naming Conventions” on page 45.Expressions CAST Specification (1) CAST ( expression NULL parameter-marker AS data-type ) Notes: 1 The data type names may be qualified.

0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( 1 ) CHARACTER CHAR CHARACTER CHAR VARCHAR ( integer ) VARYING ( integer ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer .Expressions data-type: built-in-type distinct-type built-in-type: | SMALLINT INTEGER INT BIGINT (5. integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 ) GRAPHIC ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( CCSID integer ) ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 TIMESTAMP ( 200 ) DATALINK ( integer ) ROWID Chapter 2.0 ( integer . Language Elements ) CCSID integer 145 .

and Distinct Type Names” on page 54. 146 DB2 UDB for iSeries SQL Reference V5R2 . the SQL path is used to find the appropriate data type. when specifying a floating-point data type. the CCSID of the expression is used. (For portability across operating systems. v For a cast operand that is the keyword NULL. parameter-marker A parameter marker (specified as a question mark character) is normally considered an expression. where the first column represents the data type of the cast operand (source data type) and the data types across the top represent the target data type of the CAST specification. For more information. The result is the argument value converted to the specified target data type. but is documented separately in this case because it has a special meaning. see Table 12 on page 79 for the target data types that are supported based on the data type of the cast operand. see “Unqualified Function. use REAL or DOUBLE instead of FLOAT.Expressions The CAST specification returns the cast operand (the first operand) cast to the type specified by the data type. an error is returned. the default CCSID for the data-type is used. Such a parameter marker is called a typed parameter marker. v For a cast operand that is an expression. a warning is returned if truncation of other than trailing blanks occurs. the target data type can be any data type. Typed parameter markers will be treated like any other typed value for the purpose of DESCRIBE of a select list or for column assignment. VARGRAPHIC. If the cast operand is a parameter-marker. v Otherwise. the application that uses the parameter marker will use the source data type of the distinct type.) Restrictions on the supported data types are based on the specified cast operand. data-type Specifies the data type of the result. When casting character or graphic strings to a character or graphic string with a different length. v If the expression is a character string. If the data type of either operand is a distinct type. VARCHAR. The result is a null value that has the specified data type. If the cast is not supported. v If the expression is a graphic string. v For a cast operand that is a parameter marker. the CCSID of the expression is used. or DBCLOB. If the data type is not qualified. the target data type can be any data type. the privileges held by the authorization ID of the statement must include USAGE authority on the distinct type. If the data type is a distinct type. see “CREATE TABLE” on page 526. then: v If the data-type is BLOB. the specified data type is considered a promise that the replacement will be assignable to the specified data type (using the same rules as assignment to a column). expression Specifies that the cast operand is an expression other than NULL or a parameter marker. NULL Specifies that the cast operand is the null value. For a description of data-type. The supported casts are shown in Table 12 on page 79. a CCSID of 65535 is used. Procedure. or CLOB. Specific. and the data-type is GRAPHIC. and the data-type is CHAR. If the CCSID attribute is not specified.

SELECT EMPNO.Expressions For information on which casts between data types are supported and the rules for casting to a data type see “Casting Between Data Types” on page 78. Language Elements 147 . UPDATE PERSONNEL SET RETIRE_YEAR = ? WHERE AGE = CAST( ? AS T_AGE ) Chapter 2. CAST(SALARY AS INTEGER) FROM EMPLOYEE | | | | | | v Assume that two distinct types exist. T_AGE was sourced on SMALLINT and is the data type for the AGE column in the PERSONNEL table. The following CAST specification will convert the SALARY column to INTEGER. The following UPDATE statement could be prepared. R_YEAR was sourced on INTEGER and is the data type for the RETIRE_YEAR column in the same table. Examples v An application is only interested in the integer portion of the SALARY column (defined as DECIMAL(9.2)) from the EMPLOYEE table.

or unknown about a given row or group. The following rules apply to all types of predicates: v All values specified in a predicate must be compatible. v Use of a DataLink value is limited to the NULL predicate.Predicates Predicates A predicate specifies a condition that is true. v The CCSID conversion of operands of predicates involving two or more operands are done according to “Conversion Rules for Comparison” on page 91. false. 148 DB2 UDB for iSeries SQL Reference V5R2 .

substitute ’<>’ for ’¬=’. !<. The hex value varies and is dependent on the keyboard that is used. For values x and y: Predicate x = y x<> y x < y x > y x>= y x<= y Is true if and only if.¬<. A not sign (¬) or the character that must be used in its place in certain countries. ¬=. 28 A basic predicate compares two values. The following forms of the comparison operators are also supported in basic and quantified predicates: !=. can cause parsing errors in statements passed from one database server to another. All these product-specific forms of the comparison operators are intended only to support existing SQL statements that use these operators and are not recommended for use when writing new SQL statements. If the operands of the predicate contain SBCS data or mixed data. For example. ’<=’ for ’¬>’. To avoid this problem. and if the sort sequence in effect at the time the statement is executed is not *HEX.. Language Elements 149 . then the comparison of the operands is performed using weighted values for the operands. Otherwise the result is either true or false. The weighted values are based on the sort sequence..Basic Predicate Basic Predicate (1) expression = <> < > <= >= expression Notes: 1 Other comparison operators are also supported. the result of the predicate is unknown. and¬> are supported. Chapter 2. and ’>=’ for ’¬<’. !>. Some keyboards must use the hex values for the not (¬) symbol. substitute an equivalent operator for any operator that includes a not sign. The problem occurs if the statement undergoes character conversion with certain combinations of source and target CCSIDs. | | If the value of either operand is null. x is equal to y x is not equal to y x is less than y x is greater than y x is greater than or equal to y x is less than or equal to y Examples EMPNO = ’528671’ PRTSTAFF <> :VAR1 SALARY + BONUS + COMM < 20000 SALARY > (SELECT AVG(SALARY) FROM EMPLOYEE) 28.

or if the specified relationship is true for every value returned by the subselect. The subselect must specify a single result column and can return any number of values. v Unknown if the specified relationship is not true for any of the values returned by the subselect and at least one comparison is unknown because of a null value. When SOME or ANY is specified. the result of the predicate is: v True if the result of the subselect is empty. Examples Table TBLA COLA ----1 2 3 4 null Table TBLB 150 DB2 UDB for iSeries SQL Reference V5R2 . If the operands of the predicate contain SBCS data or mixed data. whether null or not null. or if the specified relationship is false for every value returned by the subselect. 28 A quantified predicate compares a value with a set of values. v False if the specified relationship is false for at least one value returned by the subselect. the result of the predicate is: v True if the specified relationship is true for at least one value returned by the subselect. When ALL is specified. The weighted values are based on the sort sequence. then the comparison is performed using weighted values for the operands.Quantified Predicate Quantified Predicate (1) expression = <> < > <= >= SOME ANY ALL (subselect) Notes: 1 Other comparison operators are also supported. v False if the result of the subselect is empty. v Unknown if the specified relationship is not false for any values returned by the subselect and at least one comparison is unknown because of a null value. and if the sort sequence in effect at the time the statement is executed is not *HEX.

3. The subselect returns (2.3. Example 2 SELECT * FROM TBLA WHERE COLA > ANY(SELECT COLB FROM TBLB) Results in 3. The subselect returns no values. The subselect returns (2. Example 5 SELECT * FROM TBLA WHERE COLA > ANY(SELECT COLB FROM TBLB WHERE COLB<0) Results in the empty set. and null.4. Thus. Chapter 2.Quantified Predicate COLA ----2 3 Example 1 SELECT * FROM TBLA WHERE COLA = ANY(SELECT COLB FROM TBLB) Results in 2.3). COLA in row 4 is the only one that is greater than both these values. The subselect returns no values. the predicate is false for all rows in TBLA. Example 4 SELECT * FROM TBLA WHERE COLA > ALL(SELECT COLB FROM TBLB WHERE COLB<0) Results in 1.3).3).4. COLA in rows 2 and 3 equals at least one of these values. the predicate is true for all rows in TBLA. Example 3 SELECT * FROM TBLA WHERE COLA > ALL(SELECT COLB FROM TBLB) Results in 4. COLA in rows 3 and 4 is greater than at least one of these values.2. Language Elements 151 . The subselect returns (2. Thus.

If the operands of the BETWEEN predicate are strings with different CCSIDs.BETWEEN Predicate BETWEEN Predicate expression NOT BETWEEN expression AND expression The BETWEEN predicate compares a value with a range of values. The weighted value is based on the sort sequence. Given a mixture of datetime values and string representations of datetime values.SALARY BETWEEN 20000 AND 40000 SALARY NOT BETWEEN 20000 + :HV1 AND 40000 152 DB2 UDB for iSeries SQL Reference V5R2 . value1 < value2 OR value1 > value3. The BETWEEN predicate: value1 BETWEEN value2 AND value3 is logically equivalent to the search condition: value1 >= value2 AND value1 <= value3 The BETWEEN predicate: value1 NOT BETWEEN value2 AND value3 is equivalent to the search condition: NOT(value1 BETWEEN value2 AND value3). operands are converted as if the above logically-equivalent search conditions were specified. the weighted values of the strings are compared instead of the values. If a sort sequence other than *HEX is in effect when the statement is executed and the BETWEEN predicate involves SBCS data or mixed data. Examples EMPLOYEE. all values are converted to the data type of the datetime operand.that is.

The subselect may specify any number of columns. The values returned by the subselect are ignored. v The result is false only if the number of rows specified by the subselect is zero.EXISTS Predicate EXISTS Predicate EXISTS (subselect) The EXISTS predicate tests for the existence of certain rows. v The result cannot be unknown. and v The result is true only if the number of rows specified by the subselect is not zero. Language Elements 153 . Example EXISTS (SELECT * FROM EMPLOYEE WHERE SALARY > 60000) Chapter 2.

. valuen) is logically equivalent to: expression IN (SELECT * FROM R) where T is a table with a single row and R is a temporary table formed by the following fullselect: SELECT value1 FROM T UNION SELECT value2 FROM T UNION . 154 DB2 UDB for iSeries SQL Reference V5R2 . If a sort sequence other than *HEX is in effect when the statement is executed and the IN predicate involves SBCS data or mixed data. . the subselect must identify a single result column and may return any number of values. whether null or not null. . UNION SELECT valuen FROM T Each host variable must identify a structure or variable that is described in accordance with the rule for declaring host structures or variables.IN Predicate IN Predicate expression NOT IN (subselect) . In the subselect form. . the weighted values of the strings are compared instead of the actual values. ( expression expression ) The IN predicate compares a value with a set of values. An IN predicate of the form: expression IN (subselect) is equivalent to a quantified predicate of the form: expression = ANY (subselect) An IN predicate of the form: expression NOT IN (subselect) is equivalent to a quantified predicate of the form: expression <> ALL (subselect) An IN predicate of the form: expression IN (value1. The weighted values are based on the sort sequence... value2.

’B01’. Language Elements 155 .IN Predicate If the operands of the IN predicate have different data types or attributes. see “Rules for Result Data Types” on page 94. ’C01’) EMPNO IN(SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT = ’E11’) Chapter 2. For a description. For a description. see “Conversion Rules for Operations That Combine Strings” on page 98. the rules used to determine the data type for evaluation of the IN predicate are those for UNION and UNION ALL. the rules used to determine which operands are converted are those for operations that combine strings. If the operands of the IN predicate are strings with different CCSIDs. Examples DEPTNO IN (’D01’.

the weighted values of the strings are compared instead of the actual values. The pattern is specified by a string in which the underscore and percent sign have special meanings. the terms refer to the code points of those single-byte characters. None of the expressions can yield a distinct type. The match-expression. 156 DB2 UDB for iSeries SQL Reference V5R2 . percent sign. and escape-expression must either all be binary strings or none can be binary strings. the terms refer to double-byte or UCS-2 characters. the escape-expression is used to specify a character to precede either the underscore or percent character in the pattern. However. pattern-expression. A rigorous description of the pattern This more rigorous description of the pattern ignores the use of the escape-expression. A simple description of the pattern The pattern is used to specify the conformance criteria for values in the match-expression where: v The underscore sign (_) represents any single character. LIKE pattern-expression An expression that specifies the string that is to be matched. The values for match-expression. the terms character. and escape-expression must identify strings. If a sort sequence other than *HEX is in effect when the statement is executed and the LIKE predicate involves SBCS data or mixed data. which is covered the later.LIKE Predicate LIKE Predicate match-expression NOT LIKE pattern-expression ESCAPE escape-expression The LIKE predicate searches for strings that have a certain pattern. Trailing blanks in a pattern are a part of the pattern. If the pattern-expression needs to include either the underscore or the percent character. v The percent sign (%) represents a string of zero or more characters. With graphic strings. With character strings. The weighted values are based on the sort sequence. match-expression An expression that specifies the string that is to be examined to see if it conforms to a certain pattern of characters. With binary strings. it can be a function that casts a distinct type to its source type. If the value of any of the arguments is null. and underscore in the following discussion refer to single-byte characters. pattern-expression. the result of the LIKE predicate is unknown. The three arguments can include a mixture of character strings and graphic strings. v Any other character represents itself.

the CCSID of the match-expression. The result is true either if both m and p are empty strings. the nth substring of m is equal to that substring specifier and has the same length as that substring specifier. and the pattern can include both SBCS and DBCS characters. and escape-expression are converted to the compatible CCSID between the match-expression and pattern-expression. Redundant shifts are normally ignored.LIKE Predicate Let m denote a value of match-expression and p denote the value of pattern-expression. A substring specifier is an underscore. The string p is interpreted as a sequence of the minimum number of substring specifiers. the nth substring of m is any sequence of zero or more characters. The 29. It follows that if p is an empty string and m is not an empty string. or any nonempty sequence of characters other than an underscore or a percent sign. v A percent sign (either SBCS or DBCS) refers to any number of characters of any type. v The number of substrings of m is the same as the number of substring specifiers. it follows that if m is an empty string and p is not an empty string consisting of other than percent signs. however. v If the nth substring specifier is neither an underscore nor a percent sign. the nth substring of m is any single character. v Redundant shifts in match-expression and pattern-expression are ignored. To guarantee that they are ignored. v A DBCS underscore refers to one DBCS character. the expression might contain double-byte characters. v If the nth substring specifier is an underscore. or there exists a partitioning of m into substrings such that: v A substring of m is a sequence of zero or more contiguous characters and each character of m is part of exactly one substring. either SBCS or DBCS. the pattern can include either or both of the supported code points for the UCS-2 underscore and percent sign. v If the nth substring specifier is a percent sign. The predicate m NOT LIKE p is equivalent to the search condition NOT(m LIKE p). Chapter 2. the result is false. Similarly. In that case the special characters in p are interpreted as follows: v An SBCS underscore refers to one SBCS character.29 UCS-2 data If the expression is UCS-2 graphic data. otherwise. If necessary. Language Elements 157 . the result is false. so each character of p is part of exactly one substring specifier. The result of the predicate is unknown if m or p is the null value. specify the IGNORE_LIKE_REDUNDANT_SHIFTS query attribute. pattern-expression. the result of the predicate is either true or false. Mixed data If the expression is mixed data. a percent sign.

+% ++% +++% The actual pattern is.LIKE Predicate supported code points for the UCS-2 underscore are X’005F’ and X’FF3F’. if '+' is the escape character. and a fixed-length character host variable is used to replace the parameter marker. percent. For example. Parameter Marker When the pattern specified in a LIKE predicate is a parameter marker. For example. if the host variable is defined as CHAR(10).. The following rules apply the use of the ESCAPE clause and the escape-expression: v The escape-expression must be a string of length 1. ESCAPE escape-expression An expression that specifies a character to be used to modify the special meaning of the underscore (_) and percent (%) characters in the pattern-expression. The supported code points for the UCS-2 percent sign are X’0025’ and X’FF05’. This allows the LIKE predicate to be used to match values that contain the actual percent and underscore characters. any occurrences of '+' other than '++'. v The escape-expression can be a parameter marker. If you intended to search for only the values that start with ’WYSE’ you should assign the value ’WYSE%%%%%%’ to the host variable. 30. and the value WYSE% is assigned to that host variable. SELECT PROJNAME FROM PROJECT WHERE PROJECT. If it is NUL-terminated.PROJNAME LIKE ’%SYSTEMS%’ Example 2: Search for a string with a first character of ‘J’ that is exactly two characters long in the FIRSTNME column of the EMPLOYEE table.. 158 DB2 UDB for iSeries SQL Reference V5R2 . specify a value for the host variable that is the correct length. The pattern used is ’WYSE% ’ This pattern requests the database manager to search for all values that start with WYSE and end with five blank spaces. When the pattern string is. the select will not return the intended results.30 v The pattern-expression must not contain the escape character except when followed by the escape character. '+_'.. A percent sign A plus sign followed by zero or more arbitrary characters A plus sign followed by a percent sign Examples Example 1: Search for the string ‘SYSTEMS’ appearing anywhere within the PROJNAME column in the PROJECT table. a C character string variable of length 2 can be specified. or '+%' in the pattern-expression is an error. the host variable is padded with blanks on assignment.. or underscore. The following example shows the effect of successive occurrences of the escape character. which in this case is the plus sign (+). If a correct length is not specified.

If the host variable LASTNAME has a value of ’JONES’. the following statement selects the RESUME column when the string JONES appears anywhere in the column. SELECT RESUME FROM EMP_RESUME WHERE RESUME LIKE ’%’||LASTNAME||’%’ Example 6: In the following table of EBCDIC examples. Language Elements 159 . The '+%' is interpreted as a single occurrence of '%' in the pattern. The table shows the results when the predicates in the first column are evaluated using the COL1 values from the second column: Chapter 2.LIKE Predicate SELECT FIRSTNME FROM EMPLOYEE WHERE EMPLOYEE. Example 4: Assume that a distinct type named ZIP_TYPE with a source data type of CHAR(5) exists and an ADDRZIP column with data type ZIP_TYPE exists in some table TABLEY. SELECT * FROM TABLEY WHERE CHAR(ADDRZIP) LIKE ’9555%’ Example 5: The RESUME column in sample table EMP_RESUME is defined as a CLOB.FIRSTNME LIKE ’J_’ Example 3: In this example: SELECT * FROM TABLEY WHERE C1 LIKE ’AAAA+%BBB%’ ESCAPE ’+’ '+' is the escape character and indicates that the search is for a string that starts with 'AAAA%BBB'. The following statement selects the row if the zip code (ADDRZIP) begins with ’9555’. assume COL1 is mixed data.

LIKE Predicate 160 DB2 UDB for iSeries SQL Reference V5R2 .

If the value of the expression is null. Examples EMPLOYEE. the result is false. the result is true. the result is reversed.PHONE IS NULL SALARY IS NOT NULL Chapter 2. The result of a NULL predicate cannot be unknown. If NOT is specified. If the value is not null. Language Elements 161 .NULL Predicate NULL Predicate expression IS NOT NULL The NULL predicate tests for null values.

If the order of evaluation is not specified by parentheses. 162 DB2 UDB for iSeries SQL Reference V5R2 . or unknown about a given row or group. and NOT(unknown) is unknown. The order in which operators at the same precedence level are evaluated is undefined to allow for optimization of search conditions. false. the result of the search condition is the result of the specified predicate. Search conditions within parentheses are evaluated first. If logical operators are not specified. OR. The result of a search condition is derived by application of the specified logical operators (AND. Truth Tables for AND and OR P True True True False False False Unknown Unknown Unknown Q True False Unknown True False Unknown True False Unknown P AND Q True False Unknown False False False Unknown False Unknown P OR Q True True True True False Unknown True Unknown Unknown NOT(true) is false. NOT is applied before AND. and AND is applied before OR. NOT) to the result of each specified predicate. NOT(false) is true.Search Conditions Search Conditions predicate (search-condition) NOT AND OR NOT predicate (search-condition) A search condition specifies a condition that is true. AND and OR are defined in the following table in which P and Q are any predicates: Table 24.

Search Conditions Examples In the examples. Example 1 MAJPROJ = ’MA2100’ AND DEPTNO = ’D11’ OR DEPTNO = ’B03’ OR DEPTNO = ’E11’ 1 2 or 3 2 or 3 Example 2 MAJPROJ = ’MA2100’ AND 2 (DEPTNO = ’D11’ OR 1 DEPTNO = ’B03’) OR 3 DEPTNO = ’E11’ Chapter 2. Language Elements 163 . the numbers on the second line indicate the order in which the operators are evaluated.

Search Conditions 164 DB2 UDB for iSeries SQL Reference V5R2 .

In the syntax of SQL. Additional restrictions apply to the use of column functions as specified in the following section and in Chapter 4.” on page 331. The built-in functions are part of schema QSYS2. Functions are classified as column functions or scalar functions. A built-in function is denoted by a function name followed by one or more operands which are enclosed in parentheses. 1998. “MAX” on page 175 “MIN” on page 176 “STDDEV_POP or STDDEV” on page 177 “SUM” on page 178 “VAR_POP or VARIANCE or VAR” on page 179 Table 26. The argument of a column function is a set of values. The result of a function is a single value derived by applying the operation of the function to the arguments. | | | | | | | | | | | | | | | | | | | | | | | The following tables list the different types of built-in functions: Table 25. It is similar to COUNT except that the result can be greater than the maximum value of integer. Cast Scalar Functions “BIGINT” on page 188 “BLOB” on page 189 “CHAR” on page 192 “CLOB” on page 198 “DATE” on page 209 “DBCLOB” on page 217 “DECIMAL or DEC” on page 219 Returns a big integer representation of a number Returns a BLOB representation of a string of any type Returns a CHARACTER representation of a value Returns a CLOB representation of a value Returns a DATE from a value Returns a DBCLOB representation of a string expression Returns a DECIMAL representation of a number © Copyright IBM Corp. A built-in function can be invoked with or without its schema name. Built-In Functions | | | | | | | | | | A built-in function is a function that is supplied with DB2 UDB for iSeries. Thus. Returns the sum of a set of numbers Returns the biased variance (/n) of a set of numbers. Regardless of whether a schema name qualifies the function name. The operands of functions are called arguments. a function can be used only where an expression can be used. “Queries. An argument of a scalar function is a single value. Column Functions “AVG” on page 171 “COUNT” on page 172 “COUNT_BIG” on page 174 Returns the average of a set of numbers Returns the number of rows or values in a set of rows or values Returns the number of rows or values in a set of rows or values.Chapter 3. For more information on functions and the process of function resolution. see “Function resolution” on page 125. the term function is used only in the definition of an expression. and each argument is specified by an expression. Returns the maximum value in a set of values in a group Returns the minimum value in a set of values in a group Returns the biased standard deviation (/n) of a set of numbers. the database manager uses function resolution to determine which function to use. 2002 165 .

where 1 is Monday and 7 is Sunday Returns an integer that represents the day of the year 166 DB2 UDB for iSeries SQL Reference V5R2 . Returns a SMALLINT representation of a number Returns a TIME from a value Returns a TIMESTAMP from a value or a pair of values Returns a VARCHAR representative of a value Returns a VARGRAPHIC representation of a string expression Returns a zoned decimal representation of a number “DLURLPATHONLY” on page 229 “DLURLSCHEME” on page 230 “DLURLSERVER” on page 231 “DLVALUE” on page 232 Table 28. the value returned includes a file access token. Returns the scheme from a DataLink value with a linktype of URL Returns the file server from a DataLink value with a linktype of URL Returns a DataLink value Return a DOUBLE_PRECISION representation of a number Return a FLOAT representation of a number Returns a GRAPHIC representation of a string expression Returns an INTEGER representation of a number Returns a REAL representation of a number Returns a Row ID from a value. Returns the path and file name necessary to access a file within a given server from a DataLink value with a linktype of URL. The value returned NEVER includes a file access token. Datalink Scalar Functions “DLCOMMENT” on page 225 “DLLINKTYPE” on page 226 “DLURLCOMPLETE” on page 227 “DLURLPATH” on page 228 Returns the comment value from a DataLink value Returns the link type value from a DataLink value Returns the complete URL value from a DataLink value with a link type of URL Returns the path and file name necessary to access a file within a given server from a DataLink value with a linktype of URL.Built-In Functions | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 26. Datetime Scalar Functions “CURDATE” on page 207 “CURTIME” on page 208 “DAY” on page 211 “DAYOFMONTH” on page 212 “DAYOFWEEK” on page 213 “DAYOFWEEK_ISO” on page 214 “DAYOFYEAR” on page 215 Returns a date based on a reading of the time-of-day clock Returns a time based on a reading of the time-of-day clock Returns the day part of a value Returns the day part of a value Returns an integer that represents the day of the week. where 1 is Sunday and 7 is Saturday Returns an integer that represents the day of the week. Cast Scalar Functions (continued) “DOUBLE_PRECISION or DOUBLE” on page 234 “FLOAT” on page 237 “GRAPHIC” on page 239 “INTEGER or INT” on page 250 “REAL” on page 285 “ROWID” on page 288 “SMALLINT” on page 295 “TIME” on page 305 “TIMESTAMP” on page 306 “VARCHAR” on page 318 “VARGRAPHIC” on page 322 “ZONED” on page 329 Table 27. When appropriate.

The week starts with Monday. Returns an integer that represents the week of the year. to the date specified in the argument Returns the microsecond part of a value Returns an integer value representing the number of seconds between midnight and a specified time value Returns the minute part of a value Returns the month part of a value Returns a timestamp based on a reading of the time-of-day clock Returns an integer that represents the quarter of the year in which the date resides Returns the seconds part of a value Returns an estimated number of intervals based on the difference between two timestamps Returns an integer that represents the week of the year. Miscellaneous Scalar Functions “COALESCE” on page 202 “HEX” on page 243 “IDENTITY_VAL_LOCAL” on page 245 “IFNULL” on page 249 “LENGTH” on page 257 “MAX” on page 265 “MIN” on page 268 “NULLIF” on page 276 “RRN” on page 289 “VALUE” on page 317 Returns the partition number of a set of values Returns the relational database name of where a row is located Returns the node number of a row Returns the partition number of a row Returns the first argument that is not null Returns a hexadecimal representation of a value Returns the most recently assigned value for an identity column Returns the first argument that is not null Returns the length of a value Returns the maximum value in a set of values Returns the minimum value in a set of values Returns a null value if the arguments are equal. 4712 B. Built-In Functions 167 . Datetime Scalar Functions (continued) “DAYS” on page 216 “HOUR” on page 244 “JULIAN_DAY” on page 252 Returns an integer representation of a date Returns the hour part of a value Returns an integer value representing a number of days from January 1.Built-In Functions | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 28. The week starts with Sunday. Returns the year part of a value “MICROSECOND” on page 266 “MIDNIGHT_SECONDS” on page 267 “MINUTE” on page 269 “MONTH” on page 272 “NOW” on page 275 “QUARTER” on page 282 “SECOND” on page 291 “TIMESTAMPDIFF” on page 308 “WEEK” on page 325 “WEEK_ISO” on page 326 “YEAR” on page 328 Table 29. otherwise it returns the value of the first argument Returns the relative record number of a row Returns the first argument that is not null Chapter 3. Partitioning Scalar Functions “HASH” on page 242 “NODENAME” on page 273 “NODENUMBER” on page 274 “PARTITION” on page 277 Table 30.C.

in radians Returns the arc tangent of a number. in radians Returns the hyperbolic arc tangent of a number. String Scalar Functions “CHARACTER_LENGTH” on page 197 Returns the length of a string expression. in radians Returns the anti-logarithm (base 10) of a number Returns the arc sine of a number.Built-In Functions | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 31. 168 DB2 UDB for iSeries SQL Reference V5R2 . Numeric Scalar Functions “ABS” on page 181 “ACOS” on page 182 “ANTILOG” on page 183 “ASIN” on page 184 “ATAN” on page 185 “ATANH” on page 186 “ATAN2” on page 187 “CEILING” on page 191 “COS” on page 204 “COSH” on page 205 “COT” on page 206 “DEGREES” on page 222 “DIGITS” on page 224 “EXP” on page 236 “FLOOR” on page 238 “LN” on page 258 “LOG10” on page 261 “MOD” on page 270 “PI” on page 278 “POWER” on page 281 “RADIANS” on page 283 “RAND” on page 284 “ROUND” on page 286 “SIGN” on page 292 “SIN” on page 293 “SINH” on page 294 “SQRT” on page 298 “TAN” on page 303 “TANH” on page 304 “TRUNCATE or TRUNC” on page 313 Return the absolute value of a number Returns the arc cosine of a number. in radians Returns the arc tangent of x and y coordinates as an angle expressed in radians Returns the smallest integer value that is greater than or equal to a numeric-expression Returns the cosine of a number Returns the hyperbolic cosine of a number Returns the cotangent of a number Returns the number of degrees of an angle Returns a character-string representation of the absolute value of a number Returns a value that is the base of the natural logarithm (e) raised to a power specified by the argument Returns the largest integer value less than or equal to a numeric-expression Returns the natural logarithm of a number Return the common logarithm (base 10) of a number Divides the first argument by the second argument and returns the remainder Returns the value of PI Returns the result of raising the first argument to the power of the second argument Returns the number of radians for an argument that is expressed in degrees Returns a random number Returns a numeric value that has been rounded to the specified number of decimal places Returns an indicator of the sign of an expression Returns the sine of a number Returns the hyperbolic sine of a number Returns the square root of a number Returns the tangent of a number Returns the hyperbolic tangent of a number Returns a number value that as been truncated at a specified number of decimal places Table 32.

Built-In Functions | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Table 32. Built-In Functions 169 . String Scalar Functions (continued) “CONCAT” on page 203 “DIFFERENCE” on page 223 “LAND” on page 253 “LCASE” on page 254 “LEFT” on page 255 “LNOT” on page 259 “LOCATE” on page 260 “LOR” on page 262 “LOWER” on page 263 “LTRIM” on page 264 “POSITION or POSSTR” on page 279 “RTRIM” on page 290 “SOUNDEX” on page 296 “SPACE” on page 297 “STRIP” on page 299 “SUBSTRING or SUBSTR” on page 300 “TRANSLATE” on page 309 “TRIM” on page 311 “UCASE” on page 315 “UPPER” on page 316 “XOR” on page 327 Concatenates two strings. Returns a value representing the difference between the sounds of two strings Returns a string that is the logical ’AND’ of the argument strings Returns a string in which all the characters have been converted to lowercase characters Returns the leftmost characters from the string Returns a string that is the logical NOT of the argument string Returns the starting position of one string within another string Returns a string that is the logical OR of the argument strings Returns a string in which all the characters have been converted to lowercase characters Removes blanks or hexadecimal zeros from the beginning of a string expression Return the starting position of one string within another string Removes blanks or hexadecimal zeroes from the end of a string expression Returns a character code representing the sound of the words in the argument Returns a character string that consists of the number of blanks that the argument specifies Removes blanks or another specified character from the end or beginning of a string expression Returns a substring of a string Translates one or more characters in a string Removes blanks or another specified character from the end or beginning of a string expression Returns a string in which all the characters have been converted to uppercase characters Returns a string in which all the characters have been converted to uppercase characters Returns a string that is the logical XOR of the argument strings Chapter 3.

If ALL is implicitly or explicitly specified. v If a GROUP BY clause is specified in a query and the intermediate result of the FROM. If DISTINCT is specified. each column name must be a correlated reference to the same group. v A column function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name. and the SQLSTATE is set to ’02000’. v If a GROUP BY clause is not specified in a query and the intermediate result of the FROM. then the column functions are applied to the empty set. but rather a specification of an operation that is performed before the function is applied. ″Queries″. the result of the query is the empty set. The expression may include columns but cannot include another column function. For example. and HAVING clauses is the empty set. 170 DB2 UDB for iSeries SQL Reference V5R2 . v The argument of a column function is a set of values derived from an expression. WHERE. WHERE. and HAVING clauses is the empty set. duplicate values are not eliminated. then the column functions are not applied. The scope of the set is a group or an intermediate result table as explained in Chapter 4.Built-In Functions Column Functions | | | | | | | | | | | | | | | | | | | | | | | | | | | The following information applies to all column functions other than COUNT(*) and COUNT_BIG(*). GROUP BY. the SQLCODE is set to +100. duplicate values are eliminated. the result of the following SELECT statement is the number of distinct values of JOB for employees in department D01: SELECT COUNT(DISTINCT JOB) FROM EMPLOYEE WHERE WORKDEPT = ’D01’ v The keyword DISTINCT is not considered an argument of the function.

the fractional part of the average is lost. v The result is large integer if the argument values are small integers.AVG AVG ALL AVG ( DISTINCT numeric-expression ) The AVG function returns the average of a set of numbers. Otherwise. The argument values must be any built-in numeric data type and their sum must be within the range of the data type of the result.66 (that is. set the host variable AVERAGE (DECIMAL(5. The function is applied to the set of values derived from the argument values by the elimination of null values. the result is the null value.25 (that is. 14/3). Examples v Using the PROJECT table. except that: v The result is double-precision floating point if the argument values are single-precision floating point. Chapter 3. the result is the average value of the set. The data type of the result is the same as the data type of the argument values. but every intermediate result must be within the range of the result data type. SELECT AVG(DISTINCT PRSTAFF) INTO :ANY_CALC FROM PROJECT WHERE DEPTNO = ’D11’ Results in ANY_CALC being set to 4.2)) to the average staffing level (PRSTAFF) of projects in department (DEPTNO) ‘D11’. SELECT AVG(PRSTAFF) INTO :AVERAGE FROM PROJECT WHERE DEPTNO = ’D11’ Results in AVERAGE being set to 4. v Using the PROJECT table. v The result is decimal with precision 31 and scale 31-p+s if the argument values are decimal or nonzero scale binary with precision p and scale s. The order in which the values are aggregated is undefined. duplicate values are eliminated. 17/4). If set of values is empty. The result can be null. If DISTINCT is used. If the type of the result is integer. set the host variable ANY_CALC to the average of each unique staffing value (PRSTAFF) of projects in department (DEPTNO) ’D11’. Built-In Functions 171 .

set the host variable FEMALE_IN_DEPT (INTEGER) to the number of departments (WORKDEPT) that have at least one female as a member. The result is the number of values in the set. If the table is a distributed table. The argument of COUNT(expression) or COUNT(ALL expression) is a set of values. The argument of COUNT(DISTINCT expression) is a set of values. or mixed data. then the result is obtained by comparing weighted values for each value in the set. The argument values can be of any built-in data type other than a BLOB.0). The weighted values are based on the sort sequence. or DataLink. A row that includes only null values is included in the count. The function is applied to the set of values derived from the argument values by the elimination of null values and duplicate values. The function is applied to the set derived from the argument values by the elimination of null values. If DISTINCT is used. UCS-2. SELECT COUNT(*) INTO :FEMALE FROM EMPLOYEE WHERE SEX = ’F’ Results in FEMALE being set to 13. The argument of COUNT(*) is a set of rows. set the host variable FEMALE (INTEGER) to the number of rows where the value of the SEX column is ‘F’. The result is the number of rows in the set. then the result is DECIMAL(15. the resulting expression must not have a length attribute greater than 2000 for a character column or 1000 for a graphic column. Examples v Using the EMPLOYEE table. If a sort sequence other than *HEX is in effect when the statement that contains the COUNT(DISTINCT expression) is executed and the arguments contain SBCS. CLOB. DBCLOB. The result cannot be null. The result is the number of non-null values in the set including duplicates. SELECT COUNT(DISTINCT WORKDEPT) INTO :FEMALE_IN_DEPT FROM EMPLOYEE WHERE SEX=’F’ 172 DB2 UDB for iSeries SQL Reference V5R2 .COUNT COUNT ALL COUNT ( DISTINCT * expression ) The COUNT function returns the number of rows or values in a set of rows or values. see the DB2 Multisystem book. For more information about distributed tables. v Using the EMPLOYEE table. The result of the function is a large integer and it must be within the range of large integers.

COUNT Results in FEMALE_IN_DEPT being set to 5. (There is at least one female in departments A00. D11. C01.) Chapter 3. and E11. Built-In Functions 173 . D21.

The weighted values are based on the sort sequence. It is similar to COUNT except that the result can be greater than the maximum value of integer. the resulting expression must not have a length attribute greater than 2000 for a character column or 1000 for a graphic column. If DISTINCT is used.COUNT(CHAR()) RETURNS DOUBLE SOURCE QSYS2.COUNT_BIG COUNT_BIG ALL COUNT_BIG ( DISTINCT * expression ) The COUNT_BIG function returns the number of rows or values in a set of rows or values. 174 DB2 UDB for iSeries SQL Reference V5R2 . SET CURRENT PATH RICK. A row that includes only null values is included in the count. DBCLOB. or mixed data. The empty parenthesis in the parameter list for the new function (RICK. The results are the same except for the data type of the result. v To count on a specific column. In this example. | | | | If a sort sequence other than *HEX is in effect when the statement that contains the COUNT_BIG(DISTINCT expression) is executed and the arguments contain SBCS. CREATE FUNCTION RICK. The query shown counts the number of unique departments in the sample employee table.COUNT) means that the input parameter for the new function is the same type as the input parameter for the function named in the SOURCE clause. The result is the number of rows in the set. The result of the function is a decimal with precision 31 and scale 0.COUNT_BIG(CHAR()). SYSTEM PATH SELECT COUNT(DISTINCT WORKDEPT FROM EMPLOYEE. The argument values can be of any built-in data type other than a BLOB. The argument of COUNT_BIG(expression) is a set of values. The result cannot be null. The result is the number of values in the set. UCS-2. CLOB. then the result is obtained by comparing weighted values for each value in the set. the CREATE FUNCTION statement creates a sourced function that takes any column defined as CHAR. a sourced function must specify the type of the column. The empty parenthesis in the parameter list in the SOURCE clause (COUNT_BIG) means that the length attribute of the CHAR parameter of the COUNT_BIG function is ignored when DB2 locates the COUNT_BIG function. The argument of COUNT_BIG(*) is a set of rows. and returns the result as a double precision floating-point number. The function is applied to the set derived from the argument values by the elimination of null values. uses COUNT_BIG to perform the counting. or DataLink. Examples v Refer to COUNT examples and substitute COUNT_BIG for occurrences of COUNT.

the result is a null value. When the argument is a string. The argument values can be any built-in data types except LOB and DataLink values. SELECT MAX(PROJNAME) INTO :LAST_PROJ FROM PROJECT Results in LAST_PROJ being set to 'WELD LINE PLANNING '. The function is applied to the set of values derived from the argument values by the elimination of null values. or mixed data. Otherwise. The weighted values are based on the sort sequence.2)) to the maximum monthly salary (SALARY / 12) value. Built-In Functions 175 . If the function is applied to the empty set. SELECT MAX(SALARY) /12 INTO :MAX_SALARY FROM EMPLOYEE Results in MAX_SALARY being set to 4395. The result can be null. UCS-2. The specification of DISTINCT has no effect on the result and is not advised. The data type and length attribute of the result are the same as the data type and length attribute of the argument values.83. Examples v Using the EMPLOYEE table. the result has the same CCSID as the argument. then the result is obtained by comparing weighted values for each value in the set.MAX MAX ALL MAX ( DISTINCT expression ) The MAX column function returns the maximum value in a set of values in a group. set the host variable MAX_SALARY (DECIMAL(7. Chapter 3. If a sort sequence other than *HEX is in effect when the statement that contains the MAX function is executed and the arguments contain SBCS. the result is the maximum value in the set. v Using the PROJECT table. set the host variable LAST_PROJ (CHAR(24)) to the project name (PROJNAME) that comes last in the sort sequence.

The specification of DISTINCT has no effect on the result and is not advised. Otherwise. SELECT MAX(COMM) . The data type and length attribute of the result are the same as the data type and length attribute of the argument values. The result can be null. the result has the same CCSID as the argument. 176 DB2 UDB for iSeries SQL Reference V5R2 .MIN MIN ALL MIN ( DISTINCT expression ) The MIN column function returns the minimum value in a set of values in a group. set the host variable COMM_SPREAD (DECIMAL(7. 2580 .1462). then the result is obtained by comparing weighted values for each value in the set. set the host variable FIRST_FINISHED (CHAR(10)) to the estimated ending date (PRENDATE) of the first project scheduled to be completed. When the argument is a string. The function is applied to the set of values derived from the argument values by the elimination of null values. If the function is applied to the empty set. SELECT MIN(PRENDATE) INTO :FIRST_FINISHED FROM PROJECT Results in FIRST_FINISHED being set to ‘1982-09-15’.2)) to the difference between the maximum and minimum commission (COMM) for the members of department (WORKDEPT) ‘D11’. The argument values can be any built-in data types except LOB and DataLink values. or mixed data. v Using the PROJECT table. Examples v Using the EMPLOYEE table. the result is the minimum value in the set. the result is a null value. UCS-2. If a sort sequence other than *HEX is in effect when the statement that contains the MIN function is executed and the arguments contain SBCS.MIN(COMM) INTO :COMM_SPREAD FROM EMPLOYEE WHERE WORKDEPT = ’D11’ Results in COMM_SPREAD being set to 1118 (that is.

SELECT STDDEV_POP(SALARY) INTO :DEV FROM EMPLOYEE WHERE WORKDEPT = ’A00’. Note Syntax alternatives: STDDEV is a synonym for STDEV_POP. set the host variable DEV (double-precision floating point) to the standard deviation of the salaries for those employees in department A00. Results in DEV being set to approximately 9938. Built-In Functions 177 . If DISTINCT is specified. but every intermediate result must be within the range of the result data type. Otherwise. The formula used to calculate the biased standard deviation is: STDDEV_POP = SQRT(VAR_POP) where SQRT(VAR_POP) is the square root of the variance. If the function is applied to the empty set. The data type of the result is double-precision floating point. duplicate values are eliminated. The result can be null.00. Example v Using the EMPLOYEE table. The argument values must be any built-in numeric data type. The function is applied to the set of values derived from the argument values by the elimination of null values. the result is the standard deviation of the values in the set. Chapter 3. the result is a null value.STDDEV_POP or STDDEV | | | ALL STDDEV_POP STDDEV ( DISTINCT numeric-expression ) STDDEV_POP or STDDEV | | | | | | | | | | | | | | | | | | | | | | | | The STDDEV_POP function returns the biased standard deviation (/n) of a set of numbers. The order in which the values are added is undefined.

The function is applied to the set of values derived from the argument values by the elimination of null values. The result can be null.SUM SUM ALL SUM ( DISTINCT numeric-expression ) The SUM function returns the sum of a set of numbers. Example v Using the EMPLOYEE table. If the data type of the argument values is decimal or nonzero scale binary. the precision of the result is 31 and the scale is the same as the scale of the argument values. 178 DB2 UDB for iSeries SQL Reference V5R2 . The data type of the result is the same as the data type of the argument values except that the result is: v A double-precision floating point if the argument values are single-precision floating point v A large integer if the argument values are small integers v A decimal with precision 31 and scale s if the argument values are decimal or nonzero scale binary numbers with precision p and scale s. Otherwise. SELECT SUM(BONUS) INTO :JOB_BONUS FROM EMPLOYEE WHERE JOB = ’CLERK’ Results in JOB_BONUS being set to 2800. The argument values must be any built-in numeric data type. the result is a null value. set the host variable JOB_BONUS (DECIMAL(9. If DISTINCT is specified. the result is the sum of the values in the set. but every intermediate result must be within the range of the result data type. duplicate values are eliminated. The order in which the values are added is undefined. If the function is applied to the empty set.2)) to the total bonus (BONUS) paid to clerks (JOB='CLERK').

The order in which the values are added is undefined. The formula used to calculate the biased variance is: VAR_POP = SUM(X**2)/COUNT(X) . The function is applied to the set of values derived from the argument values by the elimination of null values. Note Syntax alternatives: VARIANCE and VAR are synonyms for VAR_POP. but every intermediate result must be within the range of the result data type. the result is the variance of the values in the set. The result can be null.VAR_POP or VARIANCE or VAR VAR_POP or VARIANCE or VAR ALL VAR_POP VARIANCE VAR ( DISTINCT numeric-expression ) | | | The VAR_POP function returns the biased variance (/n) of a set of numbers. duplicate values are eliminated. Results in VARNCE being set to approximately 98763888. Chapter 3. set the host variable VARNCE (double-precision floating point) to the variance of the salaries for those employees in department A00. the result is a null value. | | | | SELECT VAR_POP(SALARY) INTO :VARNCE FROM EMPLOYEE WHERE WORKDEPT = ’A00’. The data type of the result is double-precision floating point. Built-In Functions 179 .(SUM(X)/COUNT(X))**2 The argument values must be any built-in numeric data type. Example v Using the EMPLOYEE table. If DISTINCT is specified. If the function is applied to the empty set. Otherwise.88.

The argument of a scalar function can be a function. For example. However. because a scalar function is applied to single parameter values rather than to sets of values. The restrictions on the use of column functions do not apply to scalar functions. the argument of a scalar function can be a column function only if a column function is allowed in the context in which the scalar function is used. the restrictions that apply to the use of expressions and column functions also apply when an expression or column function is used within a scalar function.BIRTHDATE) FROM EMPLOYEE WHERE WORKDEPT = ’D01’ 180 DB2 UDB for iSeries SQL Reference V5R2 . LASTNAME. YEAR(CURRENT DATE . Example The result of the following SELECT statement has as many rows as there are employees in department D01: SELECT EMPNO.Scalar Functions Scalar Functions A scalar function can be used wherever an expression can be used.

except that the result is a large integer if the argument value is a small integer. if the argument is null. and the result is double-precision floating point if the argument value is single-precision floating point. The argument must be an expression that returns a value of any built-in numeric data type. | | | Note Syntax alternatives: ABSVAL is a synonym for ABS. the result is the null value.ABS ABS ABS ( numeric-expression ) The ABS function returns the absolute value of a number.SYSDUMMY1 Returns the value 50000. The data type and length attribute of the result are the same as the data type and length attribute of the argument value. the result can be null. If the argument can be null. It is supported only for compatibility with previous DB2 releases. Example v Assume the host variable PROFIT is a large integer with a value of -50000. Chapter 3. Built-In Functions 181 . SELECT ABS(:PROFIT) FROM SYSIBM.

if the argument is null. Example v Assume the host variable ACOSINE is a DECIMAL(10. the result is the null value.9) host variable with a value of 0. The argument must be an expression that returns a value of any built-in numeric data type. 182 DB2 UDB for iSeries SQL Reference V5R2 .49. SELECT ACOS(:ACOSINE) FROM SYSIBM.070737202. The result is greater than or equal to 0 and less than or equal to PI. the result can be null.ACOS ACOS ACOS ( numeric-expression ) The ACOS function returns the arc cosine of the argument as an angle expressed in radians.SYSDUMMY1 Returns the approximate value 1. The ACOS and COS functions are inverse operations. The value must be greater than or equal to -1 and less than or equal to 1. The data type of the result is double-precision floating point. If the argument can be null.

the result can be null. Chapter 3. Example v Assume the host variable ALOG is a DECIMAL(10. The data type of the result is double-precision floating point.62. If the argument can be null. the result is the null value.ANTILOG ANTILOG ANTILOG ( numeric-expression ) The ANTILOG function returns the anti-logarithm (base 10) of a number. Built-In Functions 183 .9) host variable with a value of 1. The argument must be an expression that returns a value of any built-in numeric data type. if the argument is null.SYSDUMMY1 Returns the approximate value 31. SELECT ANTILOG(:ALOG) FROM SYSIBM.499961866. The ANTILOG and LOG functions are inverse operations.

The argument must be an expression that returns a value of any built-in numeric data type. SELECT ASIN(:ASINE) FROM SYSIBM. if the argument is null. The value must be greater than or equal to -1 and less than or equal to 1. The ASIN and SIN functions are inverse operations.ASIN ASIN ASIN ( numeric-expression ) The ASIN function returns the arc sine of the argument as an angle expressed in radians. Example v Assume the host variable ASINE is a DECIMAL(10.9) host variable with a value of 0. The result is greater than or equal to -PI /2 and less than or equal to PI /2.997494987. If the argument can be null.SYSDUMMY1 Returns the approximate value 1.50. The data type of the result is double-precision floating point. the result is the null value. the result can be null. 184 DB2 UDB for iSeries SQL Reference V5R2 .

The argument must be an expression that returns a value of any built-in numeric data type. Chapter 3.50.ATAN ATAN ATAN ( numeric-expression ) The ATAN function returns the arc tangent of the argument as an angle expressed in radians. The data type of the result is double-precision floating point.10141995. the result is the null value. The ATAN and TAN functions are inverse operations. Example v Assume the host variable ATANGENT is a DECIMAL(10.SYSDUMMY1 Returns the approximate value 1.8) host variable with a value of 14. Built-In Functions 185 . The result is greater than or equal to -PI/2 and less than or equal to PI/2. if the argument is null. SELECT ATAN(:ATANGENT) FROM SYSIBM. If the argument can be null. the result can be null.

If the argument can be null. The ATANH and TANH functions are inverse operations. The argument must be an expression that returns a value of any built-in numeric data type. the result can be null. SELECT ATANH(:HATAN) FROM SYSIBM. in radians. The value must be greater than -1 and less than 1.50. The data type of the result is double-precision floating point. the result is the null value. if the argument is null.9) host variable with a value of 0.SYSDUMMY1 Returns the approximate value 1.ATANH ATANH ATANH ( numeric-expression ) The ATANH function returns the hyperbolic arc tangent of a number. 186 DB2 UDB for iSeries SQL Reference V5R2 . Example v Assume the host variable HATAN is a DECIMAL(10.905148254.

The first and second arguments specify the x and y coordinates.ATAN2 ATAN2 ATAN2 ( numeric-expression1 . respectively. Chapter 3. if any argument is null. SELECT ATAN2(:HATAN2A. respectively. the result can be null.1071487. Built-In Functions 187 .:HATAN2B) FROM SYSIBM. numeric-expression2 ) The ATAN2 function returns the arc tangent of x and y coordinates as an angle expressed in radians. Each argument is an expression that returns the value of any built-in numeric data type. the result is the null value.SYSDUMMY1 Returns a double precision floating-point number with an approximate value of 1. If any argument can be null. The data type of the result is double-precision floating point. Example v Assume that host variables HATAN2A and HATAN2B are DOUBLE host variables with values of 1 and 2. Both arguments must not be 0.

the result is the same number that would result from CAST( character-expression AS BIGINT). If the whole part of the argument is not within the range of integers. If the argument is a numeric-expression. see “CAST Specification” on page 144. Note Syntax alternatives: The CAST specification should be used for maximal portability. the result can be null. The expression must not be a CLOB. If the whole part of the argument is not within the range of big integers. integer. or decimal constant. Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming a floating-point. the result is the null value. The result of the function is a big integer. SELECT BIGINT(SALARY) FROM EMPLOYEE 188 DB2 UDB for iSeries SQL Reference V5R2 . select the EMPNO column in big integer form for further processing in the application. If the argument is a character-expression. Example v Using the EMPLOYEE table. Any fractional part of the argument is truncated. the result is the same number that would occur if the argument were assigned to a big integer column or variable. For more information.BIGINT BIGINT Numeric to Big Integer BIGINT ( numeric-expression ) Character to Big Integer BIGINT ( character-expression ) The BIGINT function returns a big integer representation of: v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Big Integer numeric-expression An expression that returns a numeric value of any built-in numeric data type. The fractional part of the argument is truncated. if the argument is null. an error occurs. an error occurs. If the argument can be null. Character to Big Integer character-expression An expression that returns a value that is a character-string representation of an integer.

the result is the null value. the length attribute of the result is the same as the length attribute of the first argument. SELECT BLOB(:myclob_locator) FROM SYSIBM. If the first argument can be null.SYSDUMMY1 v Assume that a table has a BLOB column named TOPOGRAPHIC_MAP and a VARCHAR column named MAP_NAME. or the first input argument is a graphic string and all the truncated characters are double-byte blanks. A warning (SQLSTATE 01004) is returned unless the first input argument is a character string and all the truncated characters are blanks.SYSDUMMY1 v The following function returns a BLOB for the large object that is identified by locator myclob_locator. | | string-expression A string-expression whose value can be a character string. the length attribute of the result is 1.BLOB BLOB BLOB ( string-expression . integer Specifies the length attribute for the resulting binary string. the length attribute of the result is twice the length attribute of the argument. Note Syntax alternatives: When the length is specified. For more information. graphic string. unless the argument is a graphic string. Locate any maps that contain the string ’Pellow Island’ and return a single binary string with the map name concatenated in front of the actual map. the CAST specification should be used for maximal portability. if the first argument is null. The value must be between 1 and 2 147 483 647. see “CAST Specification” on page 144. integer ) The BLOB function returns a BLOB representation of a string of any type. v Otherwise. Chapter 3. Example v The following function returns a BLOB for the string ’This is a BLOB’. the result can be null. If integer is not specified: v If the string-expression is the empty string constant. binary string. truncation is performed. The result of the function is a BLOB. If the length of the string-expression is greater than the length attribute of the result. or row ID. The following function returns a BLOB for the large object that is identified by locator myclob_locator. SELECT BLOB(’This is a BLOB’) FROM SYSIBM. The actual length of the result is the minimum of the length attribute of the result and the actual length of the expression (or twice the length of the expression when the input is graphic data). In this case. Built-In Functions 189 .

BLOB SELECT BLOB( MAP_NAME CONCAT ’: ’ CONCAT TOPOGRAPHIC_MAP ) FROM ONTARIO_SERIES_4 WHERE TOPOGRAPHIC_MAP LIKE ’%Pellow Island%’ 190 DB2 UDB for iSeries SQL Reference V5R2 .

CEILING(-3.00 per year. The result of the function has the same data type and length attribute of the argument except that the scale is 0 if the argument is DECIMAL or NUMERIC.0).5). 04.5) will result in DECIMAL(5. FROM SYSIBM. The SALARY column has a decimal data type SELECT CEIL(MAX(SALARY)/12 FROM EMPLOYEE This example returns 4396.SYSDUMMY1 This example returns: 04.5). if the argument is null.83. the result is the null value. CEILING( 3.1). Her average monthly salary before applying the CEIL function is 4395. v Use CEILING on both positive and negative numbers. CEILING(-3. -03.CEILING CEILING CEILING CEIL ( numeric-expression ) The CEIL or CEILING function returns the smallest integer value that is greater than or equal to numeric-expression. an argument with a data type of DECIMAL(5. SELECT CEILING( 3.00 because the highest paid employee is Christine Haas who earns $52750. Chapter 3. respectively. -03. Examples v Find the highest monthly salary for all the employees. If the argument can be null. Built-In Functions 191 . The argument must be an expression that returns a value of any built-in numeric data type. Round the result up to the next integer. For example. the result can be null.1).

v A time value if the first argument is a TIME. v A timestamp value if the first argument is a TIMESTAMP. the result can be null. v A character string if the first argument is any type of character string. integer ) Integer to Character CHAR ( integer-expression ) Decimal to Character CHAR ( decimal-expression .CHAR CHAR Datetime to Character CHAR ( datetime-expression . v A decimal number if the first argument is a decimal number. v A row ID value if the first argument is a ROWID. Datetime to Character 192 DB2 UDB for iSeries SQL Reference V5R2 . If the first argument can be null. ISO USA EUR JIS ) Character to Character CHAR ( character-expression . v A double-precision floating-point number if the first argument is a DOUBLE or REAL. The first argument must be a built-in data type other than a BLOB. The result of the function is a fixed-length character string. if the first argument is null. decimal-character ) | The CHAR function returns a fixed-length character-string representation of: v An integer number if the first argument is a SMALLINT. the result is the null value. or BIGINT. decimal-character ) Floating-point to Character CHAR ( floating-point-expression . v A date value if the first argument is a DATE. VARGRAPHIC. GRAPHIC. INTEGER. or DBCLOB.

truncation is performed. Chapter 3. If the length of the character-expression is greater than the length attribute of the result. or BIGINT). | | | ISO. EUR. the length attribute of the result is 1. The result is the character-string representation of the timestamp. the result is padded with blanks up to the length of the result. For more information see “String Representations of Datetime Values” on page 68. If the format is ISO. INTEGER. For more information see “String Representations of Datetime Values” on page 68. integer Specifies the length attribute for the resulting fixed length character string.CHAR datetime-expression An expression that is one of the following three built-in data types | | | | | | | | | | | | date The result is the character-string representation of the date in the format specified by the second argument. Built-In Functions 193 . The actual length is the same as the length attribute of the result. A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. USA. USA. Integer to Character integer-expression An expression that returns a value that is an integer data type (either SMALLINT. the format used is the default time format. If the length of the character-expression is less than the length of the result. EUR. Character to Character character-expression An expression that returns a value that is a built-in character-string data type. or JIS. the length attribute of the result is the same as the length attribute of the first argument. If the second argument is not specified. If the second argument is not specified. see “String Representations of Datetime Values” on page 68. time timestamp The second argument is not applicable and must not be specified. The length of the result is 8. the length of the result is 10. or JIS Specifies the date or time format of the resulting character string. the second argument cannot be less than 4. The CCSID of the string is the CCSID of the character-expression. For more information. The value must be between 1 and 32766 (32765 if nullable). the format used is the default date format. v Otherwise. If the first argument is mixed data. The CCSID of the string is the default SBCS CCSID at the current server. If the second argument is not specified: v If the character-expression is the empty string constant. Otherwise the length of the result is the length of the default date format. The result is the character-string representation of the time in the format specified by the second argument. The length of the result is 26.

the decimal point is the default decimal point. see “Decimal Point” on page 103. the first character is a digit. The result is left justified. v If the argument is a large integer: The length of the result is 11. The character must be a period or comma. Floating-point to Character floating-point expression An expression that returns a value that is a built-in floating-point data type (DOUBLE or REAL). the first character of the result is a minus sign. The CCSID of the string is the default SBCS CCSID at the current server. The length of the result is 2+p where p is the precision of the decimal-expression. If the number of characters in the result is less than 20. the decimal point is the default decimal point. the result includes the smallest number of characters that can be used to represent the value 194 DB2 UDB for iSeries SQL Reference V5R2 . If the argument is zero. Trailing zeros are returned. The result is a fixed-length character-string representation of the argument in the form of a floating-point constant. The CCSID of the string is the default SBCS CCSID at the current server. then the result is padded on the right with blanks. If the second argument is not specified. If the number of characters in the result is less than 6. then the result is padded on the right with blanks. The character must be a period or comma. The result includes a decimal character and up to p digits. Decimal to Character decimal-expression An expression that returns a value that is a built-in decimal data type (either DECIMAL or NUMERIC). where p is the precision of the decimal-expression with a preceding minus sign if the argument is negative. Leading zeros are not returned. For more information. This means that a positive value will always include one trailing blank. If the argument is negative. v If the argument is a big integer: The length of the result is 20. The result is a fixed-length character string representation of the argument. If a different precision and scale is desired. For more information. then the result is padded on the right with blanks.CHAR The result is the fixed-length character-string representation of the argument in the form of an SQL integer constant. decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string. If the second argument is not specified. The result consists of n characters that are the significant digits that represent the value of the argument with a preceding minus sign if the argument is negative. the DECIMAL scalar function can be used to make the change. Otherwise. v If the argument is a small integer: The length of the result is 6. Otherwise. The length of the result is 24. the result is 0E0. If the number of characters in the result is less than 11. decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string. see “Decimal Point” on page 103.

If the number of characters in the result is less than 24.000000’. v Assume the column STARTING has an internal value equivalent to 17. then the result is padded on the right with blanks. v Assume the column RECEIVED (timestamp) has an internal value equivalent to the combination of the PRSTDATE and STARTING columns.30.30.12. | | SELECT CHAR(STARTING + :HOUR_DUR. JIS) FROM CL_SCHED Results in the value ‘10:12:00’. the host variable HOUR_DUR (DECIMAL(6. Examples v Assume the column PRSTDATE has an internal value equivalent to 1988-12-25. v Use the CHAR function to make the type fixed-length character and reduce the length of the displayed results to 10 characters for the LASTNAME column (defined as VARCHAR(15)) of the EMPLOYEE table. The CCSID of the string is the default SBCS CCSID at the current server.12. For more information.0)) is a time duration with a value of 050000 (that is. or the first argument is a string and the length argument is specified. | | SELECT CHAR(EDLEVEL) FROM EMPLOYEE Chapter 3. USA) FROM PROJECT Results in the value ‘12/25/1988’. The date format is *MDY and the date separator is a slash (/).CHAR of the argument such that the mantissa consists of a single digit other than zero followed by a period and a sequence of digits. USA) FROM CL_SCHED Results in the value ‘5:12 PM’. | | SELECT CHAR(STARTING. | | SELECT CHAR(PRSTDATE) FROM PROJECT Results in the value ‘12/25/88’. | | SELECT CHAR(RECEIVED) FROM IN_TRAY Results in the value ‘1988-12-25-17. 5 hours). | | SELECT CHAR(PRSTDATE. the CAST specification should be used for maximal portability. Built-In Functions 195 . | | SELECT CHAR(LASTNAME. a warning (SQLSTATE 01004) that the value is truncated is returned.10) FROM EMPLOYEE For rows having a LASTNAME with a length greater than 10 characters (excluding trailing blanks). see “CAST Specification” on page 144. v Use the CHAR function to return the values for EDLEVEL (defined as SMALLINT) as a fixed length string. Note Syntax alternatives: When the first argument is numeric.

v Assume a host variable. | | SELECT CHAR(SALARY. SELECT CHAR(:DOUBLE_NUM) FROM SYSIBM.CHAR An EDLEVEL of 18 would be returned as the CHAR(6) value ’18 ’ (18 followed by 4 blanks).’) FROM EMPLOYEE returns the value ’18357.654321E-35.8765432100000002E-33 ’.50 ’ (18357.50).50 and it is to be returned with a comma as the decimal character (18357. DOUBLE_NUM.SYSDUMMY1 Results in the character value ’-9. v Assume that the STAFF table has a SALARY column defined as decimal with precision of 9 and scale of 2. ’. has a double precision floating-point data type and a value of -987. 196 DB2 UDB for iSeries SQL Reference V5R2 . The current value is 18357.50 followed by 3 blanks).

SELECT CHARACTER_LENGTH(:ADDRESS) FROM SYSIBM. Built-In Functions 197 .CHARACTER_LENGTH CHARACTER_LENGTH CHARACTER_LENGTH CHAR_LENGTH ( string-expression ) The CHARACTER_LENGTH or CHAR_LENGTH function returns the length of a string expression. Example v Assume the host variable ADDRESS is a varying-length character string with a value of ‘895 Don Mills Road’. not the maximum length. if the argument is null. Chapter 3. The result is the number of characters in the argument (not the number of bytes). the result can be null.SYSDUMMY1 Returns the value 18. See “LENGTH” on page 257 for a similar function. The length of strings includes trailing blanks. The argument must be an expression that returns a value of any built-in string data type. A single character is either an SBCS or DBCS character. the result is the null value. The length of a varying-length string is the actual length. The result of the function is a large integer. If the argument can be null.

CLOB CLOB Character to CLOB CLOB ( character-expression . If the first argument can be null. the second argument cannot be less than 4. length DEFAULT . The value must be between 1 and 2 147 483 647. if the first argument is null. the result can be null. decimal-character ) Floating-point to CLOB CLOB ( floating-point-expression . If the second argument is not specified or DEFAULT is specified: 198 DB2 UDB for iSeries SQL Reference V5R2 . the result is the null value. decimal-character ) The CLOB function returns a character-string representation of: v An integer number if the first argument is a SMALLINT. If the first argument is mixed data. INTEGER. integer ) Integer to CLOB CLOB ( integer-expression ) Decimal to CLOB CLOB ( decimal-expression . integer ) Graphic to CLOB CLOB ( graphic-expression . | | | | | length Specifies the length attribute for the resulting varying length character string. Character to CLOB character-expression An expression that returns a value that is a built-in character-string data type. or BIGINT v A decimal number if the first argument is a packed or zoned decimal number v A double-precision floating-point number if the first argument is a DOUBLE or REAL v A character string if the first argument is any type of character string v A graphic string if the first argument is an UCS-2 graphic string The result of the function is a CLOB. length DEFAULT .

A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. If the third argument is a SBCS CCSID. The actual length of the result is the minimum of the length attribute of the result and the actual length of character-expression. then the result is SBCS data. If the third argument is not specified. then the first argument cannot be a DBCS-either or DBCS-only string. The actual length of the result is the minimum of the length attribute of the result and the actual length of graphic-expression. v If the result is mixed data. then the result is mixed data. | | | | | | | | | | | | | | | | length Specifies the length attribute for the resulting varying length character string. Built-In Functions 199 . then the result is mixed data. If the third argument is a mixed CCSID. the length attribute of the result is 1. the length attribute of the result is 1. If the result is mixed data. or DBCS-either). Graphic to CLOB graphic-expression An expression that returns a value that is a built-in graphic-string data type. If the length of the graphic-expression is greater than the length attribute of the result. If the third argument is an SBCS CCSID. If the second argument is not specified or DEFAULT is specified. the result length is (2. v If the first argument is SBCS data. v If the result is SBCS data. The third argument cannot be 65535. If the third argument is a mixed CCSID. If the third argument is an SBCS CCSID.5*(n-1)) + 4. truncation is performed. v Otherwise. Chapter 3. The CCSID of the result is the same as the CCSID of the first argument. It must be a valid SBCS CCSID or mixed data CCSID. The third argument cannot be 65535. A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. the length attribute of the result is determined as follows (where n is the length attribute of the first argument): v If the graphic-expression is the empty graphic string constant. then the result is mixed data. the length attribute of the result is the same as the length attribute of the first argument. then the result is SBCS data. It must not be DBCS-graphic data. truncation is performed. an error occurs.CLOB | | | | | | | | | v If the character-expression is the empty string constant. If the length of the character-expression is greater than the length attribute of the result. DBCS-only. v If the first argument is mixed data (DBCS-open. the result length is n. integer Specifies the CCSID of the result. It must be a valid SBCS CCSID or mixed data CCSID. The value must be between 1 and 2 147 483 647. The CCSID of the result is the same as the CCSID of the first argument. the first argument must not have a CCSID of 65535: v If the first argument is bit data. the second argument cannot be less than 4. integer Specifies the CCSID of the result. then the result is SBCS data.

The result is a varying-length character string of the argument in the form of an SQL integer constant. If the default CCSID is mixed data. or BIGINT). Leading zeroes are not included. 200 DB2 UDB for iSeries SQL Reference V5R2 . If a different precision and scale is desired. If the second argument is not specified. If the default CCSID is SBCS data. Floating-point to CLOB floating-point expression An expression that returns a value that is a built-in floating-point data type (DOUBLE or REAL). The result is a varying-length character string representation of the argument. the decimal point is the default decimal point. The actual length of the result is the smallest number of characters that can be used to represent the result. | | | | | decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string. the first character of the result is a minus sign. except that trailing characters are included. v If the argument is a big integer. The result is left justified. v If the argument is a large integer. Otherwise. v If the argument is a small integer. INTEGER. the CCSID of the result is the default CCSID at the current server. Otherwise. Leading zeros are not returned. If the argument is negative. The result consists of n characters that are the significant digits that represent the value of the argument with a preceding minus sign if the argument is negative. The length attribute of the result is 2+p where p is the precision of the decimal-expression. the DECIMAL scalar function can be used to make the change. see “Decimal Point” on page 103. The result includes a decimal character and up to p digits. Decimal to CLOB decimal-expression An expression that returns a value that is a built-in decimal data type (either DECIMAL or NUMERIC). the first character is a digit. the result begins with a minus sign. the length attribute of the result is 6. The character must be a period or comma. The CCSID of the result is the default SBCS CCSID at the current server. where p is the precision of the decimal-expression with a preceding minus sign if the argument is negative. Integer to CLOB integer-expression An expression that returns a value that is a built-in integer data type (either SMALLINT. The CCSID of the result is the default SBCS CCSID at the current server. Leading zeros are not included. then the result is SBCS data. then the result is mixed data. the length attribute of the result is 20. Trailing zeros are returned. The actual length of the result is the smallest number of characters that can be used to represent the value of the argument. the length attribute of the result is 11. the result begins with a digit.CLOB If the third argument is not specified. For more information. If the argument is negative.

The actual length of the result is the smallest number of characters that can represent the value of the argument such that the mantissa consists of a single digit other than zero followed by the decimal-character and a sequence of digits. or the first argument is a string and the length argument is specified. Example v The following function returns a CLOB for the string ’This is a CLOB’. The CCSID of the result is the default SBCS CCSID at the current server. If the argument is zero. the first character is a digit. If the second argument is not specified.SYSDUMMY1 Chapter 3. If the argument is negative. SELECT CLOB(’This is a CLOB’) FROM SYSIBM. otherwise. the CAST specification should be used for maximal portability. Note Syntax alternatives: When the first argument is numeric. The character must be a period or comma. see “CAST Specification” on page 144. The result is a varying-length character string representation of the argument in the form of a floating-point constant. The length attribute of the result is 24. the decimal point is the default decimal point. the first character of the result is a minus sign. see “Decimal Point” on page 103. For more information. Built-In Functions 201 . the result is 0E0. For more information.CLOB | | | | | decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string.

SELECT EMPNO. it is not necessary to create additional signatures to support distinct types. ADMRDEPT FROM DEPARTMENT v When selecting the employee number (EMPNO) and salary (SALARY) from all the rows in the EMPLOYEE table. see “Assignments and Comparisons” on page 81. SELECT DEPTNO. Because it accepts any compatible data types as arguments. to the attributes of the result. null). if necessary. 202 DB2 UDB for iSeries SQL Reference V5R2 . DEPTNAME. This function cannot be used as a source function when creating a user-defined function. COALESCE(MGRNO. and the result of the function is the first argument that is not null. Examples v When selecting all the values from all the rows in the DEPARTMENT table.31 The arguments are evaluated in the order in which they are specified. The selected argument is converted.COALESCE COALESCE COALESCE ( expression .0) FROM EMPLOYEE 31. The result can be null only if all arguments can be null. if the salary is missing (that is null). COALESCE(SALARY. The arguments must be compatible. if the department manager (MGRNO) is missing (that is. The arguments can be of either a built-in data type or a distinct type. expression ) The COALESCE function returns the value of the first non-null expression. The attributes of the result are determined by all the operands as explained in “Rules for Result Data Types” on page 94. then return a value of 'ABSENT'. ’ABSENT’). and the result is null only if all arguments are null. For more information about data type compatibility. then return a value of zero. Character-string arguments are compatible with datetime values.

Example v Concatenate the column FIRSTNME with the column LASTNAME. the result is the null value. LASTNAME) FROM EMPLOYEE WHERE EMPNO =’000010’ Returns the value ’CHRISTINEHAAS’. If either argument can be null. string-expression-2 ) The CONCAT function combines two string arguments.CONCAT CONCAT CONCAT ( string-expression-1 . see “With the Concatenation Operator” on page 133. The result of the function is a string that consists of the first argument string followed by the second. For more information. The CONCAT function is identical to the CONCAT operator. Built-In Functions 203 . Chapter 3. The arguments must be compatible strings. see “Assignments and Comparisons” on page 81. if either argument is null. the result can be null. SELECT CONCAT(FIRSTNME. For more information about data type compatibility.

where the argument is an angle expressed in radians.SYSDUMMY1 Returns the approximate value 0. the result can be null. The argument must be an expression that returns a value of any built-in numeric data type.COS COS COS ( numeric-expression ) The COS function returns the cosine of the argument. If the argument can be null. the result is the null value.5. 204 DB2 UDB for iSeries SQL Reference V5R2 . SELECT COS(:COSINE) FROM SYSIBM. Example v Assume the host variable COSINE is a DECIMAL(2. if the argument is null. The data type of the result is double-precision floating point.07. The COS and ACOS functions are inverse operations.1) host variable with a value of 1.

The data type of the result is double-precision floating point. if the argument is null.5. Example v Assume the host variable HCOS is a DECIMAL(2. Built-In Functions 205 .COSH COSH COSH ( numeric-expression ) The COSH function returns the hyperbolic cosine of the argument. Chapter 3.1) host variable with a value of 1. the result can be null. If the argument can be null.35.SYSDUMMY1 Returns the approximate value 2. the result is the null value. The argument must be an expression that returns a value of any built-in numeric data type. where the argument is an angle expressed in radians. SELECT COSH(:HCOS) FROM SYSIBM.

5. the result can be null.SYSDUMMY1 Returns the approximate value 0. The argument must be an expression that returns a value of any built-in numeric data type. The data type of the result is double-precision floating point. if the argument is null.07.COT COT COT ( numeric-expression ) The COT function returns the cotangent of the argument. 206 DB2 UDB for iSeries SQL Reference V5R2 . the result is the null value. where the argument is an angle expressed in radians. Example v Assume the host variable COTAN is a DECIMAL(2. If the argument can be null.1) host variable with a value of 1. SELECT COT(:COTAN) FROM SYSIBM.

SELECT CURDATE() FROM SYSIBM. Example v Return the current date based on the time-of-day clock. or CURRENT TIMESTAMP special registers within a single statement. The result cannot be null.SYSDUMMY1 Chapter 3. Built-In Functions 207 . CURRENT TIME. The value returned by the CURDATE function is the same as the value returned by the CURRENT DATE special register. or used with the CURTIME or NOW scalar functions or the CURRENT DATE. If this function is used more than once within a single SQL statement. The data type of the result is a date. all values are based on a single clock reading.CURDATE CURDATE CURDATE ( ) The CURDATE function returns a date based on a reading of the time-of-day clock when the SQL statement is executed at the current server.

or CURRENT TIMESTAMP special registers within a single statement. The value returned by the CURTIME function is the same as the value returned by the CURRENT TIME special register. all values are based on a single clock reading. SELECT CURTIME() FROM SYSIBM. The result cannot be null. Example v Return the current time based on the time-of-day clock. CURRENT TIME.CURTIME CURTIME CURTIME ( ) The CURTIME function returns a time based on a reading of the time-of-day clock when the SQL statement is executed at the current server. If this function is used more than once within a single SQL statement. The data type of the result is a time.SYSDUMMY1 208 DB2 UDB for iSeries SQL Reference V5R2 . or used with the CURDATE or NOW scalar functions or the CURRENT DATE.

timestamp. Note Syntax alternatives: When the argument is a date. or any numeric data type. v If expression is a character string. v If the argument is a date: The result is that date. Built-In Functions 209 . it must not be a CLOB and its value must be one of the following: – A valid character-string representation of a date or timestamp. v If the argument is a character string: The result is the date represented by the string or the date part of the timestamp value represented by the string. where yyyy are digits denoting a year. When a string representation of a date is SBCS data with a CCSID that is not the same as the default CCSID for SBCS data. v If expression is a number. The result of the function is a date. the result can be null. the result is the null value. a timestamp. see “String Representations of Datetime Values” on page 68. a character string. The other rules depend on the data type of the argument: v If the argument is a timestamp: The result is the date part of the timestamp. – A character string with an actual length of 7 that represents a valid date in the form yyyynnn. v If the argument is a number: The result is the date that is n-1 days after January 1. For more information. For the valid formats of string representations of dates and timestamps. it must be a positive number less than or equal to 3652059. When a string representation of a date is mixed data with a CCSID that is not the same as the default CCSID for mixed data. that value is converted to adhere to the default CCSID for SBCS data before it is interpreted and converted to a date value. the CAST specification should be used for maximal portability. or character string. If the argument can be null. where n is the integral part of the number.DATE DATE DATE ( expression ) The DATE function returns a date from a value. 0001. Chapter 3. if the argument is null. and nnn are digits between 001 and 366 denoting a day of that year. that value is converted to adhere to the default CCSID for mixed data before it is interpreted and converted to a date value. see “CAST Specification” on page 144. The argument must be an expression that returns a value of one of the following built-in data types: a date.

| | SELECT DATE(RECEIVED) FROM IN_TRAY Results in an internal representation of ‘1988-12-25’.SYSDUMMY1 Results in an internal representation of ‘1988-12-25’. v The following DATE scalar function applied to an EUR string representation of a date: SELECT DATE(’25.000000’.30.12.1988’) FROM SYSIBM. 210 DB2 UDB for iSeries SQL Reference V5R2 .SYSDUMMY1 Results in an internal representation of ‘1988-12-25’.DATE Examples v Assume that the column RECEIVED (TIMESTAMP) has an internal value equivalent to ‘1988-12-25-17. v The following DATE scalar function applied to an ISO string representation of a date: SELECT DATE(’1988-12-25’) FROM SYSIBM. v The following DATE scalar function applied to a positive number: SELECT DATE(35) FROM SYSIBM.SYSDUMMY1 Results in an internal representation of ‘0001-02-04’.12.

it must be a date duration or timestamp duration. v If the argument is a date duration or timestamp duration: The result is the day part of the value. timestamp. a timestamp. the result can be null. Built-In Functions 211 .SYSDUMMY1 Results in the value 15. see “String Representations of Datetime Values” on page 68. which is an integer between 1 and 31. The result of the function is a large integer. or a numeric data type. v If expression is a number. The other rules depend on the data type of the argument: v If the argument is a date. see “Datetime Operands and Durations” on page 135. set the host variable END_DAY (SMALLINT) to the day that the WELD LINE PLANNING project (PROJNAME) is scheduled to stop (PRENDATE). For the valid formats of string representations of dates and timestamps.DATE(’1999-12-31’) ) FROM SYSIBM. which is an integer between −99 and 99. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. the result is the null value. The argument must be an expression that returns a value of one of the following built-in data types: a date. A nonzero result has the same sign as the argument. v If expression is a character string. Examples v Using the PROJECT table. If the argument can be null. if the argument is null.DAY DAY DAY ( expression ) The DAY function returns the day part of a value. Chapter 3. SELECT DAY(PRENDATE) INTO :END_DAY FROM PROJECT WHERE PROJNAME = ’WELD LINE PLANNING’ Results in END_DAY being set to 15. a character string. or valid character-string representation of a date or timestamp: The result is the day part of the value. v Return the day part of the difference between two dates: SELECT DAY( DATE(’2000-03-15’) . For the valid formats of datetime durations.

212 DB2 UDB for iSeries SQL Reference V5R2 . If the argument can be null. set the host variable END_DAY (SMALLINT) to the day that the WELD LINE PLANNING project (PROJNAME) is scheduled to stop (PRENDATE). the result can be null. see “String Representations of Datetime Values” on page 68. a timestamp. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. The argument must be an expression that returns a value of one of the following built-in data types: a date. The result of the function is a large integer. For the valid formats of string representations of dates and timestamps. or a character string. SELECT DAYOFMONTH(PRENDATE) INTO :END_DAY FROM PROJECT WHERE PROJNAME = ’WELD LINE PLANNING’ Results in END_DAY being set to 15.DAYOFMONTH DAYOFMONTH DAYOFMONTH ( expression ) The DAYOFMONTH function returns an integer between 1 and 31 that represents the day of the month. Examples v Using the PROJECT table. If expression is a character string. if the argument is null. the result is the null value.

or a character string. For another alternative. 2.’01.DAYOFWEEK DAYOFWEEK DAYOFWEEK ( expression ) The DAYOFWEEK function returns an integer between 1 and 7 that represents the day of the week. the result can be null. DAYOFWEEK(CAST(CAST(’10/11/1998’ AS DATE)) AS CHAR(20))). the result is the null value. set the host variable DAY_OF_WEEK (INTEGER) to the day of the week that Christine Haas (EMPNO=‘000010’) started (HIREDATE).SYSDUMMY1 Chapter 3. The argument must be an expression that returns a value of one of the following built-in data types: a date. 1. v The following query returns four values: 1. SELECT DAYOFWEEK(HIREDATE) INTO :DAY_OF_WEEK FROM EMPLOYEE WHERE EMPNO = ’000010’ Results in DAY_OF_WEEK being set to 6. where 1 is Sunday and 7 is Saturday. if the argument is null. and 2. Example v Using the EMPLOYEE table. SELECT DAYOFWEEK(CAST(’10/11/1998’ AS DATE)). FROM SYSIBM. see “String Representations of Datetime Values” on page 68. which represents Friday.’01. For the valid formats of string representations of dates and timestamps.02’)). Built-In Functions 213 .02’) AS CHAR(20))). DAYOFWEEK(TIMESTAMP(’10/12/1998’. DAYOFWEEK(CAST(TIMESTAMP(’10/12/1998’. The result of the function is a large integer. If the argument can be null. see “DAYOFWEEK_ISO” on page 214. If expression is a character string. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. a timestamp.

7. v The following query returns four values: 7. set the host variable DAY_OF_WEEK (INTEGER) to the day of the week that Christine Haas (EMPNO=‘000010’) started (HIREDATE). a timestamp. SELECT DAYOFWEEK_ISO(CAST(’10/11/1998’ AS DATE)). Examples v Using the EMPLOYEE table. The argument must be an expression that returns a value of one of the following built-in data types: a date. the result is the null value. The result of the function is a large integer.DAYOFWEEK_ISO DAYOFWEEK_ISO DAYOFWEEK_ISO ( expression ) The DAYOFWEEK_ISO function returns an integer between 1 and 7 that represents the day of the week. or a character string. if the argument is null.’01. DAYOFWEEK_ISO(CAST(CAST(’10/11/1998’ AS DATE)) AS CHAR(20))). For another alternative. DAYOFWEEK_ISO(TIMESTAMP(’10/12/1998’. where 1 is Monday and 7 is Sunday. SELECT DAYOFWEEK_ISO(HIREDATE) INTO :DAY_OF_WEEK FROM EMPLOYEE WHERE EMPNO = ’000010’ Results in DAY_OF_WEEK being set to 5. If expression is a character string. and 1. see “String Representations of Datetime Values” on page 68. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. 1.02’) AS CHAR(20))). which represents Friday. the result can be null. see “DAYOFWEEK” on page 213. For the valid formats of string representations of dates and timestamps.SYSDUMMY1 214 DB2 UDB for iSeries SQL Reference V5R2 . FROM SYSIBM. DAYOFWEEK_ISO(CAST(TIMESTAMP(’10/12/1998’.02’)). If the argument can be null.’01.

SELECT AVG(DAYOFYEAR(HIREDATE)) INTO :AVG_DAY_OF_YEAR FROM EMPLOYEE Results in AVG_DAY_OF_YEAR being set to 202. the result is the null value.DAYOFYEAR DAYOFYEAR DAYOFYEAR ( expression ) The DAYOFYEAR function returns an integer between 1 and 366 that represents the day of the year where 1 is January 1. a timestamp. Chapter 3. The result of the function is a large integer. Built-In Functions 215 . set the host variable AVG_DAY_OF_YEAR (INTEGER) to the average of the day of the year that employees started on (HIREDATE). the result can be null. Example v Using the EMPLOYEE table. The argument must be an expression that returns a value of one of the following built-in data types: a date. If expression is a character string. or a character string. if the argument is null. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. If the argument can be null. For the valid formats of string representations of dates and timestamps. see “String Representations of Datetime Values” on page 68.

a timestamp. SELECT SUM(DAYS(PRENDATE) . the result can be null. where D is the date that would occur if the DATE function were applied to the argument. If the argument can be null. The argument must be an expression that returns a value of one of the following built-in data types: a date. set the host variable EDUCATION_DAYS (INTEGER) to the number of elapsed days (PRENDATE . set the host variable TOTAL_DAYS (INTEGER) to the sum of elapsed days (PRENDATE . 216 DB2 UDB for iSeries SQL Reference V5R2 . see “String Representations of Datetime Values” on page 68. The result is 1 more than the number of days from January 1. SELECT DAYS(PRENDATE) .DAYS(PRSTDATE) INTO :EDUCATION_DAYS FROM PROJECT WHERE PROJNO = ’IF2000’ Results in EDUCATION_DAYS being set to 396. If expression is a character string.PRSTDATE) estimated for all projects in department (DEPTNO) ‘E21’.PRSTDATE) estimated for the project (PROJNO) ‘IF2000’. 0001 to D. if the argument is null. Examples v Using the PROJECT table. The result of the function is a large integer. or a character string.DAYS(PRSTDATE)) INTO :TOTAL_DAYS FROM PROJECT WHERE DEPTNO = ’E21’ Results in TOTAL_DAYS being set to 1484.DAYS DAYS DAYS ( expression ) The DAYS function returns an integer representation of a date. For the valid formats of string representations of dates and timestamps. v Using the PROJECT table. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. the result is the null value.

M is determined as follows: v If the CCSID of S is a mixed CCSID. The value must be between 1 and 1 073 741 823. It must be a DBCS or UCS-2 CCSID. It cannot be a BLOB. – Otherwise the operation is not allowed. S is the result of the expression after converting the data to a CCSID in a native encoding scheme. If the third argument is not specified and the first argument is character. The following table summarizes the result CCSID based on M. string-expression An expression that returns a value that is a character-string or graphic-string.DBCLOB DBCLOB DBCLOB ( string-expression .) v If the string expression is data in a native encoding scheme. S denotes one of the following: v If the string expression is a host variable containing data in a foreign encoding scheme. S is that string expression. Built-In Functions 217 . If the second argument is not specified or DEFAULT is specified: v If the expression is an empty string constant. integer Specifies the CCSID for the resulting varying-length graphic string. integer ) The DBCLOB function returns a DBCLOB representation of a string expression. M is that CCSID. The CCSID cannot be 65535. M 930 933 935 937 939 Result CCSID 300 834 837 835 300 Description Japanese EBCDIC Korean EBCDIC S-Chinese EBCDIC T-Chinese EBCDIC Japanese EBCDIC DBCS Substitution Character X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ Chapter 3. It cannot be GRAPHIC or VARGRAPHIC with a CCSID of 65535 unless a third argument is specified. M is that CCSID. the length attribute of the result is the same as the length attribute of the first argument. It cannot be CHAR or VARCHAR bit data. Let M denote that mixed CCSID. In the following rules. the length attribute of the result is 1. (See “Character Conversion” on page 32 for more information. length DEFAULT . v If the CCSID of S is an SBCS CCSID: – If the CCSID of S has an associated mixed CCSID. length Specifies the length attribute for the resulting varying-length graphic string. then the CCSID of the result is determined by a mixed CCSID. v Otherwise.

If the expression can be null.DBCLOB M 5026 5035 Result CCSID 4396 4396 Description Japanese EBCDIC Japanese EBCDIC DBCS Substitution Character X’FEFE’ X’FEFE’ If the third argument is not specified and the first argument is not character. v If the nth character of the argument is a DBCS character. SELECT DBCLOB(FIRSTNME) INTO :VAR_DESC FROM EMPLOYEE WHERE EMPNO = ’000050’ 218 DB2 UDB for iSeries SQL Reference V5R2 . see “CAST Specification” on page 144. The result of the function is a DBCLOB string. each character of the argument determines a character of the result. set the host variable VAR_DESC (VARGRAPHIC(24)) to the DBCLOB equivalent of the first name (FIRSTNME) for employee number (EMPNO) ’000050’. then the CCSID of the result is the same as the CCSID of the first argument. The actual length of the result is the minimum of the length attribute of the result and the actual length of expression. If the expression is null. the result is the null value. For more information. Note Syntax alternatives: When the length attribute is specified. the CAST specification should be used for maximal portability. the equivalence of SBCS and DBCS characters depends on M. If the result is DBCS-graphic data. the result is an empty string. Example v Using the EMPLOYEE table. the nth character of the result is that equivalent DBCS character. v If the nth character of the argument is an SBCS character that does not have an equivalent DBCS character. If the length attribute of the resulting DBCLOB is less than the actual length of the first argument. the nth character of the result is that DBCS character. the nth character of the result is the DBCS substitution character. the result can be null. and every single-byte code point in the argument is considered an SBCS character with the exception of the EBCDIC mixed data shift codes X’0E’ and X’0F’. The nth character of the result is the UCS-2 equivalent of the nth character of the argument. If the result is UCS-2 graphic data. If the expression is an empty string or the EBCDIC string X’0E0F’. truncation is performed and no warning is returned. Regardless of the CCSID. every double-byte code point in the argument is considered a DBCS character. v If the nth character of the argument is an SBCS character that has an equivalent DBCS character.

precision An integer constant with a value greater than or equal to 1 and less than or equal to 31. Character to Decimal character-expression An expression that must contain a character-string representation of a number. decimal-character ) The DECIMAL function returns a decimal representation of: v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Decimal numeric-expression An expression that returns a value of any built-in numeric data type. An error occurs if the number of significant decimal digits required to represent the whole part of the number is greater than p-s. or nonzero scale binary v 19 for big integer v 11 for large integer v 5 for small integer scale An integer constant that is greater than or equal to 0 and less than or equal to precision. precision . Built-In Functions 219 . the default is 0. The default for precision depends on the data type of the numeric-expression: v 15 for floating point. scale ) Character to Decimal DECIMAL DEC ( character-expression . precision .DECIMAL DECIMAL or DEC Numeric to Decimal DECIMAL DEC ( numeric-expression . numeric. Chapter 3. The result is the same number that would occur if the first argument were assigned to a decimal column or variable with a precision of p and a scale of s. scale . decimal. If not specified.

DECIMAL Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming an integer or decimal constant. scale An integer constant that is greater than or equal to 0 and less than or equal to precision. in order to use its value as a date duration it must be “cast” as DECIMAL(8. the user inputs 21400. if the first argument is null. SELECT PRSTDATE + DECIMAL(:PERIOD. Assume the host variable PERIOD is of type INTEGER. the CAST specification should be used for maximal portability. the result can be null. the result is the null value.50). The result is the same number that would result from CAST(character-expression AS DECIMAL(p. UPDATE STAFF SET SALARY = DECIMAL(:newsalary. precision An integer constant that is greater than or equal to 1 and less than or equal to 31. where p and s are the second and third arguments.2) FROM EMPLOYEE v Using the PROJECT table. 9. the default is 0. If the second argument is not specified. see “CAST Specification” on page 144. The result of the function is a decimal number with precision of p and scale of s. An error occurs if the number of significant digits to the left of the decimal character (the whole part of the number) in character-expression is greater than p-s. Examples v Use the DECIMAL function in order to force a DECIMAL data type (with a precision of 5 and a scale of 2) to be returned in a select-list for the EDLEVEL column (data type = SMALLINT) in the EMPLOYEE table.s)). The character must be a period or comma. | | | | | | decimal-character Specifies the single-byte character constant that was used to delimit the decimal digits in character-expression from the whole part of the number. Once validated by the application. If not specified. For more information. For more information.’) WHERE ID = :empid 220 DB2 UDB for iSeries SQL Reference V5R2 . The EMPNO column should also appear in the select list. If not specified. The default decimal character is not valid in the substring if the decimal-character argument is specified. DECIMAL(EDLEVEL. Then. Digits are truncated from the end of the decimal number if the number of digits to the right of the decimal separator character is greater than the scale s. SELECT EMPNO. it is assigned to the host variable newsalary which is defined as CHAR(10).5. see “Decimal Point” on page 103.0). Note Syntax alternatives: When the precision is specified. 2.8) FROM PROJECT v Assume that updates to the SALARY column are input through a window as a character string using comma as a decimal character (for example. If the first argument can be null. the default is 15. select all of the starting dates (PRSTDATE) that have been incremented by a duration that is specified in a host variable. ’. the decimal point is the default decimal separator character. The expression must not be a CLOB.

DECIMAL The value of SALARY becomes 21400. Chapter 3.50. Built-In Functions 221 .

3) host variable with a value of 3. 222 DB2 UDB for iSeries SQL Reference V5R2 . The argument must be an expression that returns the value of any built-in numeric data type. SELECT DEGREES(:RAD) FROM SYSIBM. If the argument can be null. The data type of the result is double-precision floating point.DEGREES DEGREES DEGREES ( numeric-expression ) The DEGREES function returns the number of degrees of the argument which is an angle expressed in radians.142.SYSDUMMY1 Returns the approximate value 180. if the argument is null.0. Example v Assume the host variable RAD is a DECIMAL(4. the result is the null value. the result can be null.

SYSDUMMY1 Returns 4. Examples v Assume the following statement: SELECT DIFFERENCE(’CONSTRAINT’. SOUNDEX(’CONSTRAINT’). CLOBs.SYSDUMMY1 Returns 2. the difference is 4 (the highest value possible). In this case. string-expression-2 ) The DIFFERENCE function returns a value from 0 to 4 representing the difference between the sounds of two strings based on applying the SOUNDEX function to the strings. and C536. The arguments must be a built-in string data types. and hence. a lower difference value. SOUNDEX(’CONSTRAINT’).DIFFERENCE DIFFERENCE DIFFERENCE ( string-expression-1 . A value of 4 is the best possible sound match. v Assume the following statement: SELECT DIFFERENCE(’CONSTRAINT’. SOUNDEX(’CONSTANT’) FROM SYSIBM.’CONTRITE’). SOUNDEX(’CONTRITE’) FROM SYSIBM. and DBCLOBs. C523. If any argument can be null. but not BLOBs. the two strings return different SOUNDEX values. Built-In Functions 223 . Chapter 3. The data type of the result is INTEGER. if any argument is null.’CONSTANT’). and C523. the result can be null. Since the two strings return the same SOUNDEX value. C523. the result is the null value.

and that one of its values is -6.2) data type.1. INTEGER. Examples v Assume that a table called TABLEX contains an INTEGER column called INTCOL containing 10-digit numbers. if the argument is a big integer p. leading zeros to fill out the string. The result is a string of length six (the precision of the column) with leading zeros padding the string out to this length. the result is the null value. Instead. if the argument is null. The length of the string is: v v v v 5. Neither sign nor decimal point appear in the result.4) FROM TABLEX v Assume that COLUMNX has the DECIMAL(6. SELECT DISTINCT SUBSTR(DIGITS(INTCOL). if the argument is a small zero scale integer 10. The result does not include a sign or a decimal point. List all combinations of the first four digits contained in column INTCOL. The result of the function is a fixed-length character string representing the absolute value of the argument without regard to its scale.DIGITS DIGITS DIGITS ( numeric-expression ) The DIGITS function returns a character-string representation of the absolute value of a number. If the argument can be null. 224 DB2 UDB for iSeries SQL Reference V5R2 . if necessary. BIGINT. SELECT DIGITS(COLUMNX) FROM TABLEX Returns the value '000628'. The argument must be a built-in numeric data type of SMALLINT. if the argument is a large zero scale integer 19. including. the result can be null. it consists exclusively of digits.28. or DECIMAL. if the argument is a decimal or nonzero scale integer with a precision of p The CCSID of the character string is the default SBCS CCSID at the current server.

’A comment’)) then the following function operating on that value: SELECT DLCOMMENT(COLA) FROM TBLA Returns the value ’A comment’. if the argument is null. DESCRIPTION.com/x/y/a.ibm. if it exists. EXEC SQL PREPARE HOCKEY_STMT FROM :stmtvar. the result can be null. the result is the null value. Built-In Functions 225 . Examples v Prepare a statement to select the date. The rows to be selected are those for goals scored by either of the Richard brothers (Maurice or Henri).almaden.b’. DLCOMMENT(ARTICLES) FROM HOCKEY_GOALS WHERE BY_PLAYER = ’Maurice Richard’ OR BY_PLAYER = ’Henri Richard’ ". The result of the function is VARCHAR(254). Chapter 3. The CCSID of the character string is the same as that of DataLink-expression. stmtvar = "SELECT DATE_OF_GOAL. v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TBLA VALUES (DLVALUE(’http://dlfs. from a DataLink value.’URL’. If the argument can be null. the description and the comment from the link to the ARTICLES column from the HOCKEY_GOALS table.DLCOMMENT DLCOMMENT DLCOMMENT ( DataLink-expression ) The DLCOMMENT function returns the comment value. The argument must be an expression that results in a value with a built-in DataLink data type.

the result can be null. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs. The result of the function is VARCHAR(4). if the argument is null.com/x/y/a.’URL’. If the argument can be null. the result is the null value.DLLINKTYPE DLLINKTYPE DLLINKTYPE ( DataLink-expression ) The DLLINKTYPE function returns the link type value from a DataLink value. The CCSID of the character string is the same as that of DataLink-expression. The argument must be an expression that results in a value with a built-in DataLink data type.ibm.’A comment’) ) then the following function operating on that value: SELECT DLLINKTYPE(COLA) FROM TBLA Returns the value ’URL’.almaden. 226 DB2 UDB for iSeries SQL Reference V5R2 .b’.

the value includes a file access token.IBM.almaden. If the DataLink value only includes the comment. the result is the null value.b’.ALMADEN. the length attribute of the result is the length attribute of the argument plus 19. If the DataLink has an attribute of FILE LINK CONTROL and READ PERMISSION DB. The value is the same as what would be returned by the concatenation of DLURLSCHEME with ’://’. If the argument can be null. Built-In Functions 227 .COM/x/y/****************. then DLURLSERVER.’A comment’) ) then the following function operating on that value: SELECT DLURLCOMPLETE(COLA) FROM TBLA Returns the value ’HTTP://DLFS.DLURLCOMPLETE DLURLCOMPLETE DLURLCOMPLETE ( DataLink-expression ) The DLURLCOMPLETE function returns the complete URL value from a DataLink value with a link type of URL. the length attribute of the result is the length attribute of the argument.ibm. the result can be null. v Otherwise. The CCSID of the character string is the same as that of DataLink-expression. The argument must be an expression that results in a value with a built-in DataLink data type. and then DLURLPATH. The length attribute depends on the attributes of the DataLink: v If the DataLink has an attribute of FILE LINK CONTROL and READ PERMISSION DB. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs.b’.com/x/y/a.’URL’.a. if the argument is null. The result of the function is a varying-length string. the result returned is a zero length string. where **************** represents the access token. Chapter 3.

the length attribute of the result is the length attribute of the argument plus 19.’URL’. the result can be null.DLURLPATH DLURLPATH DLURLPATH ( DataLink-expression ) The DLURLPATH function returns the path and file name necessary to access a file within a given server from a DataLink value with a linktype of URL.ibm. the length attribute of the result is the length attribute of the argument. When appropriate. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs. The CCSID of the character string is the same as that of DataLink-expression.com/x/y/a. the value includes a file access token. The result of the function is a varying-length string. the result is the null value. if the argument is null. where **************** represents the access token. If the argument can be null.b’.a. If the DataLink value only includes the comment. 228 DB2 UDB for iSeries SQL Reference V5R2 . The length attribute depends on the attributes of the DataLink: v If the DataLink has an attribute of FILE LINK CONTROL and READ PERMISSION DB.almaden.’A comment’) ) then the following function operating on that value: SELECT DLURLPATH(COLA) FROM TBLA Returns the value ’/x/y/****************. v Otherwise. The argument must be an expression that results in a value with a built-in DataLink data type. the result returned is a zero length string.b’.

b’.’A comment’) ) then the following function operating on that value: SELECT DLURLPATHONLY(COLA) FROM TBLA Returns the value ’/x/y/a.b’. The value returned NEVER includes a file access token.com/x/y/a. Built-In Functions 229 . the result returned is a zero length string.’URL’. The CCSID of the character string is the same as that of DataLink-expression. If the argument can be null. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs.ibm. the result is the null value.almaden. if the argument is null. The result of the function is a varying-length string with a length attribute of that is equal to the length attribute of the argument. the result can be null. If the DataLink value only includes the comment. Chapter 3. The argument must be an expression that results in a value with a built-in DataLink data type.DLURLPATHONLY DLURLPATHONLY DLURLPATHONLY ( DataLink-expression ) The DLURLPATHONLY function returns the path and file name necessary to access a file within a given server from a DataLink value with a linktype of URL.

The argument must be an expression that results in a value with a built-in DataLink data type. The result of the function is VARCHAR(20). If the argument can be null. The CCSID of the character string is the same as that of DataLink-expression.DLURLSCHEME DLURLSCHEME DLURLSCHEME ( DataLink-expression ) The DLURLSCHEME function returns the scheme from a DataLink value with a linktype of URL.’A comment’) ) then the following function operating on that value: SELECT DLURLSCHEME(COLA) FROM TBLA Returns the value ’HTTP’. the result can be null. The value will always be in upper case.almaden. the result returned is a zero length string.’URL’. the result is the null value.com/x/y/a. if the argument is null. 230 DB2 UDB for iSeries SQL Reference V5R2 .b’.ibm. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs. If the DataLink value only includes the comment.

The result of the function is a varying-length string with a length attribute of that is equal to the length attribute of the argument.ALMADEN. The argument must be an expression that results in a value with a built-in DataLink data type.b’. The CCSID of the character string is the same as that of DataLink-expression. The value will always be in upper case.com/x/y/a.’URL’.ibm. Chapter 3. if the argument is null. the result can be null.almaden. Built-In Functions 231 . If the argument can be null. the result is the null value. the result returned is a zero length string.COM’. Examples v Given a DataLink value that was inserted into column COLA of a row in table TBLA using the scalar function: INSERT INTO TABLA VALUES( DLVALUE(’http://dlfs.DLURLSERVER DLURLSERVER DLURLSERVER ( DataLink-expression ) The DLURLSERVER function returns the file server from a DataLink value with a linktype of URL.IBM.’A comment’) ) then the following function operating on that value: SELECT DLURLSERVER(COLA) FROM TBLA Returns the value ’DLFS. If the DataLink value only includes the comment.

If the expression is not an empty string. the result is the null value. The actual length of the character string expression must be less than or equal to 32718 characters. the DataLink value is created with empty linkage attributes so there is no file link. comment-string An optional character string expression that provides a comment or additional location information. If the first argument can be null. The only valid value is ’URL’. the CCSID of the results will be 939. the CCSID of the result is described in the following table: CCSID of data-location 65535 65535 CCSID of comment-string 65535 non-65535 Result CCSID Job Default CCSID comment-string CCSID (unless the CCSID is 290. However. or 5026). if only a comment is specified (in which case the data-location is a zero-length string). then this is a character string expression that contains a complete URL value. The CCSID of the DataLink is the same as that of data-location except in the following cases: v If the comment string is mixed data and data-location is not mixed data.DLVALUE DLVALUE DLVALUE ( data-location . 5026. Turkish data (905 or 1026). If the CCSID of comment string is 5026 or 930.32 v If the data-location has a CCSID of bit data (65535). 930. if the first argument is null. or 13488 where the CCSID will then be further modified as described in the following rows. 1026. The comment-string cannot be the null value. it usually also creates a link to a file. 930. 905. The result of the function is a DataLink value.) 4396 939 290 930 or 5026 any any 32. linktype-string An optional character string expression that specifies the link type of the DataLink value. The actual length of the character string expression must be less than or equal to 254 characters. it must include the URL scheme and URL server. the result can be null. or Japanese data (290. 232 DB2 UDB for iSeries SQL Reference V5R2 . If a comment-string is not specified. the comment-string is the empty string. comment-string ) The DLVALUE function returns a DataLink value. data-location If the link type is URL. the CCSID of the result will be the CCSID of the comment string. UCS-2 graphic data (13488). When the function is on the right hand side of a SET clause in an UPDATE statement or is in a VALUES clause in an INSERT statement. linktype-string .

only a comment in the variable named url_movie_comment. ’1952-04-24’. There is.DLVALUE CCSID of data-location 905 or 1026 13488 CCSID of comment-string any any Result CCSID 500 500 When defining a DataLink value using this function. DLVALUE(:url_snapshot. ’Boston Bruins. then the maximum length of the data-location plus the comment is 200 bytes. The URL values for the first two links are contained in the variables named url_article and url_snapshot. if a column is defined as DataLink(200). INSERT INTO HOCKEY_GOALS VALUES(’Maurice Richard’. ’URL’. :url_movie_comment) ) Chapter 3. as yet. The variable named url_snapshot_comment contains a comment to accompany the snapshot link. :url_snapshot_comment). DLVALUE(’’. DLVALUE(:url_article). ’URL’. Built-In Functions 233 . ’Montreal canadian’. ’Winning goal in game 7 of Stanley Cup final’. ’?’. consider the maximum length of the target of the value. Examples v Insert a row into the table. no link for the movie. For example.

234 DB2 UDB for iSeries SQL Reference V5R2 . the result is the null value. see “CAST Specification” on page 144. The argument must not be a CLOB. The CAST specification should be used for maximal portability. If the argument can be null. For more information. integer. Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming an floating-point. Character to Double character-expression An expression that returns a character string value. if the argument is null. the result can be null. or decimal constant. The single-byte character constant that must be used to delimit the decimal digits in character-expression from the whole part of the number is the default decimal point. see “Decimal Point” on page 103. The result is the same number that would result from CAST( character-expression AS DOUBLE PRECISION). For more information.DOUBLE_PRECISION or DOUBLE DOUBLE_PRECISION or DOUBLE Numeric to Double DOUBLE_PRECISION DOUBLE ( numeric-expression ) Character to Double DOUBLE_PRECISION DOUBLE ( character-expression ) The DOUBLE_PRECISION and DOUBLE functions return a floating-point representation of: v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Double numeric-expression An expression that returns a value of any built-in numeric data type. The result of the function is a double-precision floating-point number. Note Syntax alternatives: FLOAT is a synonym for DOUBLE_PRECISION and DOUBLE. The result is the same number that would occur if the expression were assigned to a double-precision floating-point column or variable.

The columns involved (SALARY and COMM) have DECIMAL data types. DOUBLE_PRECISION(SALARY)/COMM FROM EMPLOYEE WHERE COMM > 0 Chapter 3. find the ratio of salary to commission for employees whose commission is not zero. To eliminate the possibility of out-of-range results.DOUBLE_PRECISION or DOUBLE Example v Using the EMPLOYEE table. DOUBLE_PRECISION is applied to SALARY so that the division is carried out in floating point: SELECT EMPNO. Built-In Functions 235 .

If the argument can be null. The argument muat be an expression that returns the value of any built-in numeric data type.453789832.SYSDUMMY1 Returns the approximate value 31.9) host variable with a value of 3. the result is the null value.EXP EXP EXP ( numeric-expression ) The EXP function returns a value that is the base of the natural logarithm (e) raised to a power specified by the argument. SELECT EXP(:E) FROM SYSIBM. 236 DB2 UDB for iSeries SQL Reference V5R2 . The data type of the result is double-precision floating point. Example v Assume the host variable E is a DECIMAL(10. if the argument is null.62. The EXP and LN functions are inverse operations. the result can be null.

FLOAT is a synonym for the DOUBLE_PRECISION and DOUBLE functions.FLOAT FLOAT Numeric to Float FLOAT ( numeric-expression ) Character to Float FLOAT ( character-expression ) The FLOAT function returns a floating point representation of a number. see “DOUBLE_PRECISION or DOUBLE” on page 234. Built-In Functions 237 . For more information. Chapter 3.

3. The argument must be an expression that returns a value of any built-in numeric data type. FLOOR(-3. For example. -4.1). SELECT FLOOR(SALARY) FROM EMPLOYEE v Use FLOOR on both positive and negative numbers. FLOOR(-3. an argument with a data type of DECIMAL(5.5).0).5). SELECT FLOOR( 3. the result is the null value. respectively. FLOOR( 3. The result of the function has the same data type and length attribute of the argument except that the scale is 0 if the argument is a decimal number.FLOOR FLOOR FLOOR ( numeric-expression ) The FLOOR function returns the largest integer value less than or equal to numeric-expression. the result can be null.SYSDUMMY1 This example returns: 3. Example v Use the FLOOR function to truncate any digits to the right of the decimal point.1). if the argument is null. -4.5) will result in DECIMAL(5. 238 DB2 UDB for iSeries SQL Reference V5R2 . If the argument can be null. FROM SYSIBM.

or if DEFAULT is specified. length DEFAULT . each character of the argument determines a character of the result. truncation is performed and no warning is returned. The CCSID cannot be 65535. Character to Graphic character-expression Specifies a character string expression.GRAPHIC GRAPHIC Character to Graphic GRAPHIC ( character-expression . the result is padded with double-byte blanks to the length of the result. length Specifies the length attribute of the result and must be an integer constant between 1 and 16383 if the first argument is not nullable or between 1 and 16382 if the first argument is nullable. the length attribute of the result is the same as the length attribute of the first argument. integer ) Graphic to Graphic GRAPHIC ( graphic-expression . S denotes one of the following: Chapter 3. The result of the function is a fixed-length graphic string (GRAPHIC). the result can be null. If the length attribute of the resulting fixed-length string is less than the actual length of the first argument. integer Specifies the CCSID of the result. integer ) The GRAPHIC function returns a fixed-length graphic-string representation of a string expression. If the CCSID represents UCS-2 graphic data. the result is the null value. If the length of character-expression is less than the length specified. If the expression can be null. It must be a DBCS or UCS-2 CCSID. It cannot be a CHAR or VARCHAR bit data. length DEFAULT . In the following rules. the result is an empty string. If the expression is null. If integer is not specified then the CCSID of the result is determined by a mixed CCSID. If length is not specified. Let M denote that mixed CCSID. Built-In Functions 239 . Each character of the argument determines a character of the result. The nth character of the result is the UCS-2 equivalent of the nth character of the argument. If the expression is an empty string or the EBCDIC string X’0E0F’.

the nth character of the result is that DBCS character. v If the nth character of the argument is an SBCS character that has an equivalent DBCS character. v If the nth character of the argument is an SBCS character that does not have an equivalent DBCS character. the length attribute of the result is the same as the length attribute of the first argument. v If the CCSID of S is an SBCS CCSID: – If the CCSID of S has an associated mixed CCSID. v If the nth character of the argument is a DBCS character. (See “Character Conversion” on page 32 for more information. length Specifies the length attribute of the result and must be an integer constant between 1 and 16383 if the first argument is not nullable or between 1 and 16382 if the first argument is nullable. Regardless of the CCSID. If the length of graphic-expression is less than the length specified. every double-byte code point in the argument is considered a DBCS character. S is that string expression. If the second argument is not specified.) v If the string expression is data in a native encoding scheme. the nth character of the result is the DBCS substitution character. M is that CCSID. the result is padded with double-byte blanks to the length of the result. M is that CCSID. or if DEFAULT is specified. – Otherwise the operation is not allowed. and every single-byte code point in the argument is considered an SBCS character with the exception of the EBCDIC mixed data shift codes X’0E’ and X’0F’. the nth character of the result is that equivalent DBCS character. S is the result of the expression after converting the data to a CCSID in a native encoding scheme. The following table summarizes the result CCSID based on M.GRAPHIC v If the string expression is a host variable containing data in a foreign encoding scheme. M is determined as follows: v If the CCSID of S is a mixed CCSID. M 930 933 935 937 939 5026 5035 Result CCSID 300 834 837 835 300 4396 4396 Description Japanese EBCDIC Korean EBCDIC S-Chinese EBCDIC T-Chinese EBCDIC Japanese EBCDIC Japanese EBCDIC Japanese EBCDIC DBCS Substitution Character X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ The equivalence of SBCS and DBCS characters depends on M. 240 DB2 UDB for iSeries SQL Reference V5R2 . Graphic to Graphic graphic-expression Specifies a graphic string expression.

the CAST specification should be used for maximal portability. Note Syntax alternatives: If the length attribute is specified. Example v Using the EMPLOYEE table. SELECT GRAPHIC( VARGRAPHIC(FIRSTNME)) INTO :DESC FROM EMPLOYEE WHERE EMPNO = ’000050’ Chapter 3. see “CAST Specification” on page 144. It must be a DBCS or UCS-2 CCSID. Built-In Functions 241 . set the host variable DESC (GRAPHIC(24)) to the GRAPHIC equivalent of the first name (FIRSTNME) for employee number (EMPNO) ’000050’.GRAPHIC If the length of the graphic-expression is greater than the length attribute of the result. The CCSID cannot be 65535. A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. integer Specifies the CCSID of the result. truncation is performed. If integer is not specified then the CCSID of the result is the CCSID of the first argument. For more information.

If any of the arguments are null. see the DB2 Multisystem book. LASTNAME) FROM EMPLOYEE 242 DB2 UDB for iSeries SQL Reference V5R2 . or DataLink values. The arguments can be any built-in data type except date. This query returns the partition number for every row in EMPLOYEE. SELECT HASH(EMPNO. The result cannot be null. Also see the PARTITION function. the result is zero. floating-point. Example v Use the HASH function to determine what the partitions would be if the partitioning key was composed of EMPNO and LASTNAME. The result of the function is a large integer with a value between 0 and 1023. HASH ( expression ) The HASH function returns the partition number of a set of values. time.HASH HASH . timestamp. For more information about partition numbers.

The argument can be of any built-in data type. the result can be null. The result is a string of hexadecimal digits. if the argument is null.33 The length attribute of the result is twice the storage length attribute of the argument. the result is a varying-length string. LASTNAME.HEX HEX HEX ( expression ) The HEX function returns a hexadecimal representation of a value. the result is the hexadecimal representation of the internal form of the argument. the first two digits represent the first byte of the argument. The CCSID of the string is the default SBCS CCSID at the current server. Chapter 3. Built-In Functions 243 . The length attribute of the result cannot be greater than 32766 for fixed-length results or greater than 32740 for varying-length results. SELECT FIRSTNME. and so forth. If the argument can be null. and NUMERIC data types is different from other database products because the internal form for these data types is different. the result is the null value. Otherwise. the next two digits represent the second byte of the argument. the result is a fixed-length string. Example v Use the HEX function to return a hexadecimal representation of the education level for each employee. If the argument is a varying-length string. This hexadecimal representation for DATE. TIMESTAMP. For information on the storage length attribute see “CREATE TABLE” on page 526. MIDINIT. HEX(EDLEVEL) FROM EMPLOYEE 33. If the argument is a datetime value. The result of the function is a character string.

SELECT * FROM CL_SCHED WHERE HOUR(STARTING) BETWEEN 12 AND 17 244 DB2 UDB for iSeries SQL Reference V5R2 . see “Datetime Operands and Durations” on page 135. The other rules depend on the data type of the argument: v If the argument is a time.HOUR HOUR HOUR ( expression ) The HOUR function returns the hour part of a value. see “String Representations of Datetime Values” on page 68. if the argument is null. The result of the function is a large integer. If the argument can be null. the result can be null. select all the classes that start in the afternoon. Example v Using the CL_SCHED sample table. it must not be a CLOB and its value must be a valid character-string representation of a time or timestamp. which is an integer between −99 and 99. v If expression is a number. a character string or a numeric data type. A nonzero result has the same sign as the argument. it must be a time duration or timestamp duration. which is an integer between 0 and 24. For the valid formats of datetime durations. For the valid formats of string representations of times and timestamps. v If expression is a character string. or valid character-string representation of a time or timestamp: The result is the hour part of the value. a timestamp. the result is the null value. The argument must be an expression that returns a value of one of the following built-in data types: a time. v If the argument is a time duration or timestamp duration: The result is the hour part of the value. timestamp.

the value that is used is the most recently assigned value for an identity column from a previous INSERT statement. The INSERT statement has to be issued at the same level. The result can be null. The result of the IDENTITY_VAL_LOCAL function is not affected by the following statements: v An INSERT statement for a table which does not contain an identity column v An UPDATE statement v A COMMIT statement v A ROLLBACK statement Notes The following notes explain the behavior of the function when it is invoked in various situations: Invoking the function within the VALUES clause of an INSERT statement Expressions in an INSERT statement are evaluated before values are assigned to the target columns of the INSERT statement.IDENTITY_VAL_LOCAL | | | IDENTITY_VAL_LOCAL ( ) IDENTITY_VAL_LOCAL | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | IDENTITY_VAL_LOCAL is a non-deterministic function that returns the most recently assigned value for an identity column. The function has no input parameters. Thus. Built-In Functions 245 . The assigned value can be a value supplied by the user (if the identity column is defined as GENERATED BY DEFAULT) or an identity value that was generated by the database manager. The value returned is the value that was assigned to the identity column of the table identified in the most recent INSERT statement for a table containing an identity column. The result is null if an INSERT statement has not been issued for a table containing an identity column at the current processing level. that is. The result is a DECIMAL(31. A new level is initiated when a trigger. The value might be the value that would have been returned from the function had it been invoked before the failed INSERT or the value that would have been assigned had the INSERT succeeded. The actual value returned depends on the point of failure and is therefore unpredictable.0) regardless of the actual data type of the identity column that the result value corresponds to. function. The function returns the null value if no such INSERT statement had been executed within the same level as the invocation of the IDENTITY_VAL_LOCAL function. Invoking the function following a failed INSERT statement The function returns an unpredictable result when it is invoked after the unsuccessful execution of an INSERT statement for a table with an identity column. Chapter 3. when you invoke IDENTITY_VAL_LOCAL in an INSERT statement. or stored procedure is invoked. the value has to be available locally within the level at which it was assigned until replaced by the next assigned value. This includes invoking the function in a before or after insert trigger. A trigger condition is at the same level as the associated triggered action.

SALARY.IDENTITY_VAL_LOCAL | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Invoking the function within the SELECT statement of a cursor Because the results of the IDENTITY_VAL_LOCAL function are not deterministic. SALARY DECIMAL(5. The result of invoking the IDENTITY_VAL_LOCAL function from within the triggered action of a before insert trigger is the null value. and identity values generated by SQL statements issued within a triggered action are not available to other triggered actions using the IDENTITY_VAL_LOCAL function. DEPT SMALLINT) INSERT INTO EMPLOYEE (NAME. CREATE TABLE EMPLOYEE (EMPNO INTEGER GENERATED ALWAYS AS IDENTITY. The value for the identity column of the table for which the trigger is defined cannot be obtained by invoking the IDENTITY_VAL_LOCAL function within the triggered action of a before insert trigger. Invoking the function within a triggered action of an insert trigger Multiple before or after insert triggers can exist for a table. NAME CHAR(30). Do not use the IDENTITY_VAL_LOCAL function in the triggered action of a before insert trigger. Invoking the function following an INSERT with triggered actions The result of invoking the function after an INSERT that activates triggers is the value actually assigned to the identity column (that is. The result of invoking the IDENTITY_VAL_LOCAL function in the triggered action of an after insert trigger is the value assigned to an identity column of the table identified in the most recent INSERT statement invoked in the same triggered action for a table containing an identity column. This value is not necessarily the value provided in the INSERT statement or a value generated by the database manager. then the function returns a null value. However. Invoking the function within the trigger condition of an insert trigger The result of invoking the IDENTITY_VAL_LOCAL function from within the condition of an insert trigger is the null value. the value that would be returned on a subsequent SELECT statement). This is the case even though the multiple triggered actions are conceptually defined at the same level. In such cases. the value for the identity column can be obtained in the triggered action by referencing the trigger transition variable for the identity column. If an INSERT statement for a table containing an identity column was not executed within the same triggered action before invoking the IDENTITY_VAL_LOCAL function.2). DEPTNO) 246 DB2 UDB for iSeries SQL Reference V5R2 . Examples v Set the variable IVAR to the value assigned to the identity column in the EMPLOYEE table. The value returned from the function in the VALUES statement should be 1. the result of an invocation of the IDENTITY_VAL_LOCAL function from within the SELECT statement of a cursor can vary for each FETCH statement. each trigger is processed separately. The assigned value could be a value that was specified in a SET transition variable statement within the triggered action of a before insert trigger for a trigger transition variable associated with the identity column.

. have an identity column named C1. 3. 13 ) SELECT * FROM T2 WHERE C1 = DECIMAL( IDENTITY_VAL_LOCAL().for the C1 column in table T1. Thus. 50) VALUES IDENTITY_VAL_LOCAL() INTO :IVAR v Assume two tables. C1 ) VALUES( IDENTITY_VAL_LOCAL(). INSERT INTO T2 ( C2. which is the value generated by the database manager for column C1 of T2. INSERT INTO T2 ( C2 ) VALUES( IDENTITY_VAL_LOCAL() ) SELECT * FROM T2 WHERE C1 = DECIMAL( IDENTITY_VAL_LOCAL().. consider the following table definition: Chapter 3. 15... the database manager assigns a value of 13 to identity column C1 and gives C2 a value of 10 from IDENTITY_VAL_LOCAL. C2 SMALLINT) CREATE TABLE T2 (C1 DECIMAL(15. 2. The following INSERT statement inserts a single row into T2 where column C2 gets a value of 2 from the IDENTITY_VAL_LOCAL function. 0) C1 10 C2 2 Invoking the IDENTITY_VAL_LOCAL function after this INSERT would result in a value of 10. C2 SMALLINT) INSERT INTO T1 ( C2 ) VALUES(5) INSERT INTO T1 ( C2 ) VALUES(5) SELECT * FROM T1 C1 1 2 VALUES IDENTITY_VAL_LOCAL() INTO :IVAR C2 5 5 At this point. 0) C1 13 C2 10 v The IDENTITY_VAL_LOCAL function can also be invoked in an INSERT statement that both invokes the IDENTITY_VAL_LOCAL function and causes a new value for an identity column to be assigned.0) GENERATED BY DEFAULT AS IDENTITY ( START WITH 10 ) . The database manager generates values 1. For the following INSERT statement.. The next value to be returned is thus established when the IDENTITY_VAL_LOCAL function is invoked after the INSERT statement completes.. C2 is given the last identity value that was inserted into T2. 15. T1 and T2. Assume another single row is inserted into T2. the IDENTITY_VAL_LOCAL function would return a value of 2 in IVAR. For example. Built-In Functions 247 .99. 11. and values 10.for the C1 column in table T2. 12.IDENTITY_VAL_LOCAL | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | VALUES(’Rupert’. CREATE TABLE T1 (C1 SMALLINT GENERATED ALWAYS AS IDENTITY. 989.

INSERT INTO T3 ( C2. Thus. INSERT INTO T3 ( C2 ) VALUES( 25 ) In the following INSERT statement. the identity column. the IDENTITY_VAL_LOCAL function is again invoked to provide a value for the C2 column. This establishes 1 as the value that will be returned on the next invocation of the IDENTITY_VAL_LOCAL function. table T3 contains the following: C1 1 2 11 C2 25 1 2 The contents of T3 illustrate that the expressions in the VALUES clause are evaluated before the assignments for the columns of the INSERT statement. an invocation of an IDENTITY_VAL_LOCAL function invoked from a VALUES clause of an INSERT statement uses the most recently assigned value for an identity column in a previous INSERT statement. A value of 1 (the identity value assigned to the C1 column of the first row) is assigned to the C2 column.IDENTITY_VAL_LOCAL | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE TABLE T3 (C1 SMALLINT GENERATED BY DEFAULT AS IDENTITY. The assignment of 11 to C1 establishes 11 as the value that will be returned on the next invocation of the IDENTITY_VAL_LOCAL function. and the database manager generates a value of 2 for C1. and the user provides a value of 11 for C1. the IDENTITY_VAL_LOCAL function is invoked to provide a value for the C2 column. specify a value of 25 for the C2 column. C1 ) VALUES( IDENTITY_VAL_LOCAL(). This establishes 2 as the value that will be returned on the next invocation of the IDENTITY_VAL_LOCAL function. the identity column. 248 DB2 UDB for iSeries SQL Reference V5R2 . C2 SMALLINT) For the following INSERT statement. A value of 2 (the identity value assigned to the C1 column of the second row) is assigned to the C2 column. INSERT INTO T3 ( C2 ) VALUES( IDENTITY_VAL_LOCAL() ) In the following INSERT statement. 11 ) After the 3 INSERT statements have been processed. and the database manager generates a value of 1 for C1. the identity column.

Built-In Functions 249 . IFNULL(SALARY. if the salary is missing (that is. then return a value of zero. null). Example v When selecting the employee number (EMPNO) and salary (SALARY) from all the rows in the EMPLOYEE table. The IFNULL function is identical to the COALESCE scalar function with two arguments. For more information. SELECT EMPNO.0) FROM EMPLOYEE Chapter 3. expression ) The IFNULL function returns the value of the first non-null expression.IFNULL IFNULL IFNULL ( expression . see “COALESCE” on page 202.

Example v Using the EMPLOYEE table. an error occurs. integer. select a list containing salary (SALARY) divided by education level (EDLEVEL). an error occurs. the result can be null. If the whole part of the argument is not within the range of integers. The result is the same number that would result from CAST( character-expression AS INTEGER). If the whole part of the argument is not within the range of integers. 250 DB2 UDB for iSeries SQL Reference V5R2 . Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming a floating-point. Truncate any decimal in the calculation. see “CAST Specification” on page 144. The fractional part of the argument is truncated. If the argument is a numeric-expression. Character to Integer character-expression An expression that returns a value that is a character-string representation of an integer.INTEGER INTEGER or INT Numeric to Integer INTEGER INT ( numeric-expression ) Character to Integer INTEGER INT ( character-expression ) The INTEGER function returns an integer representation of: v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Integer numeric-expression An expression that returns a numeric value of any built-in numeric data type. The list should also contain the values used in the calculation and the employee number (EMPNO). the result is the same number that would occur if the argument were assigned to a large integer column or variable. the result is the null value. If the argument can be null. or decimal constant. Note Syntax alternatives: The CAST specification should be used for maximal portability. The expression must not be a CLOB. The result of the function is a large integer. For more information. if the argument is null. Any fractional part of the argument is truncated.

INTEGER SELECT INTEGER(SALARY / EDLEVEL). EDLEVEL. Built-In Functions 251 . EMPNO FROM EMPLOYEE Chapter 3. SALARY.

if the argument is null.SYSDUMMY1 The result is that JDAY is set to 2450815. 252 DB2 UDB for iSeries SQL Reference V5R2 . v Set integer host variable JDAY to the Julian day for January 1. set the integer host variable JDAY to the Julian day of the day that Christine Haas (EMPNO = ’000010’) was employed (HIREDATE = ’1965-01-01’). or a valid character-string representation of a date or timestamp. 1998. An argument with a character string data type must not be a CLOB. The result can be null.C. the result is the null value. Examples v Using sample table EMPLOYEE. For the valid formats of string representations of dates and timestamps. a timestamp. The argument must be an expression that returns a value of one of the following built-in data types: a date. 4713 B. The result of the function is a large integer. see “String Representations of Datetime Values” on page 68. SELECT JULIAN_DAY(HIREDATE) INTO :JDAY FROM EMPLOYEE WHERE EMPNO = ’000010’ The result is that JDAY is set to 2438762. SELECT JULIAN_DAY(’1998-01-01’) INTO :JDAY FROM SYSIBM.JULIAN_DAY JULIAN_DAY JULIAN_DAY ( expression ) The JULIAN_DAY function returns an integer value representing a number of days from January 1. (the start of the Julian date calendar) to the date specified in the argument.

character-expression ) The LAND function returns a string that is the logical ’AND’ of the argument strings. Likewise. Chapter 3. Example v Assume the host variable L1 is a CHARACTER(2) host variable with a value of X’A1B1’. SELECT LAND(:L1. If an argument is encountered that is shorter than the previous result. The arguments cannot be mixed data character strings or graphic strings. and then continues to do AND comparisons with each successive argument using the previous result. the shorter arguments are padded with blanks (X’40’). and host variable L3 is a CHARACTER(4) host variable with a value of X’A1B10040’. This function takes the first argument string. the result is a fixed-length string of length n. the result is a varying-length string with length attribute n. the result is the null value. where m is the actual length of the longest argument. The attributes of the result are determined as follows: v If all the arguments are fixed-length strings. host variable L2 is a CHARACTER(3) host variable with a value of X’F0F040’.:L2.SYSDUMMY1 v Returns the value X’A0B00000’.LAND LAND LAND ( character-expression . where n is the length attribute of the argument with greatest length attribute. where n is the length of the longest argument. Built-In Functions 253 . In this case. if an argument is null.SYSDUMMY1 Returns the value X’A0B00040’. The actual length of the result is m. the result can be null.:L1) FROM SYSIBM. if necessary. so the logical AND result differs from the first example. it is padded with blanks. The CCSID of the result is 65535.:L3) FROM SYSIBM. The arguments are converted. If an argument can be null. SELECT LAND(:L3. does an AND comparison with the next string. v If any argument is a varying-length string. to the attributes of the result.:L2. The arguments must be character strings but cannot be LOBs.

see “LOWER” on page 263. based on the CCSID of the argument. The LCASE function is identical to the LOWER function. For more information. 254 DB2 UDB for iSeries SQL Reference V5R2 .LCASE | | | LCASE ( string-expression ) LCASE | | | | The LCASE function returns a string in which all the characters have been converted to lowercase characters.

A substring of string-expression is zero or more contiguous characters of string-expression. integer must be an integer greater than or equal to 0 and less than or equal to n. 34. the result of the function is a fixed-length string. and each character is a DBCS or UCS-2 character. Built-In Functions 255 . the result is a graphic string. The result of the function is a varying-length string with a length attribute that is the same as the length attribute of string-expression and a data type that depends on the data type of string-expression: v VARGRAPHIC if string-expression is GRAPHIC or VARGRAPHIC v VARCHAR if string-expression is CHAR or VARCHAR v DBCLOB if string-expression is DBCLOB v CLOB if string-expression is CLOB v BLOB if string-expression is BLOB If integer is an integer constant and the argument is not a BLOB. The string-expression is effectively padded on the right with the necessary number of blank characters (or hexadecimal zeroes for binary strings) so that the specified substring of string-expression always exists. the result is a binary string. The actual length of the result is integer. and each character is one byte. If any argument can be null. if any argument is null. If string-expression is a graphic string. the result will not necessarily be a properly formed mixed data string. integer ) | | | | | | | | | | | | | | | | | | | | The LEFT function returns the leftmost integer bytes of string-expression. string-expression must be a character string. or a binary string with a built-in data type. The LEFT function accepts mixed data strings. The CCSID of the result is the same as that of string-expression. If string-expression is a character string. If string-expression is a graphic string. the result can be null.LEFT LEFT LEFT ( string-expression . because LEFT operates on a strict byte-count basis. a character is a byte. graphic string. a character is a DBCS or UCS-2 character. CLOB. string-expression An expression that specifies the string from which the result is derived. the result is the null value. If string-expression is a character string or binary string. and each character is one byte. the result is a character string. Chapter 3.34 integer An expression that specifies the length of the result. where n is the length attribute of string-expression. However. or DBCLOB. If string-expression is a binary string.

LEFT Example v Assume the host variable NAME (VARCHAR(50)) has a value of 'KATIE AUSTIN' and the host variable FIRSTNAME_LEN (int) has a value of 5.SYSDUMMY1 Returns the value 'KATIE' 256 DB2 UDB for iSeries SQL Reference V5R2 . SELECT LEFT(:NAME. :FIRSTNAME_LEN) FROM SYSIBM.

The result is the length of the argument. v Assume that PRSTDATE is a column of type DATE. SELECT LENGTH(CHAR(PRSTDATE.LENGTH LENGTH LENGTH ( expression ) The LENGTH function returns the length of a value. EUR)) FROM PROJECT Returns the value 10. Built-In Functions 257 . The length of a varying-length string is the actual length. The length of strings includes blanks. If the argument can be null. if the argument is null. the result is the null value. not the length attribute. See “CHARACTER_LENGTH” on page 197 for a similar function. The result of the function is a large integer. SELECT LENGTH(:ADDRESS) FROM SYSIBM. The argument must be an expression that returns a value of any built-in data type.SYSDUMMY1 | | | | | | | | Returns the value 18. Chapter 3. SELECT LENGTH(PRSTDATE) FROM PROJECT Returns the value 4. v Assume that PRSTDATE is a column of type DATE. The length of a graphic string is the number of double-byte characters (the number of bytes divided by 2). the result can be null. The length of all other values is the number of bytes used to represent the value: v v v v v v v v v v v v 2 for small integer 4 for large integer 8 for big integer The integral part of (p/2)+1 for packed decimal numbers with precision p p for zoned decimal numbers with precision p 4 for single-precision float 8 for double-precision float The length of the string for strings 3 for time 4 for date 10 for timestamp The actual number of bytes used to store the DataLink value (plus 19 if the DataLink is FILE LINK CONTROL and READ PERMISSION DB) for datalinks v 26 for row ID Examples v Assume the host variable ADDRESS is a varying-length character string with a value of ‘895 Don Mills Road’.

SYSDUMMY1 Returns the approximate value 3. The argument must be an expression that returns a value of any built-in numeric data type. Example v Assume the host variable NATLOG is a DECIMAL(4. The LN and EXP functions are inverse operations. if the argument is null. The data type of the result is double-precision floating point.LN LN LN ( numeric-expression ) The LN function returns the natural logarithm of a number. the result can be null. the result is the null value. If the argument can be null.45. The value of the argument must be greater than zero.2) host variable with a value of 31. SELECT LN(:NATLOG) FROM SYSIBM. 258 DB2 UDB for iSeries SQL Reference V5R2 .62.

LNOT LNOT LNOT ( character-expression ) The LNOT function returns a string that is the logical NOT of the argument string. The CCSID of the result is 65535. if the argument is null. the actual length of the result is the same as the actual length of the argument value. If the argument can be null. If the argument is a varying-length string. the result can be null. Example v Assume the host variable L1 is a CHARACTER(2) host variable with a value of X’F0F0’. The data type and length attribute of the result is the same as the data type and length attribute of the argument value. The argument must be a character string but cannot be a LOB. Chapter 3. the result is the null value.SYSDUMMY1 Returns the value X’0F0F’. Built-In Functions 259 . The argument cannot be a MIXED character string or a graphic string. SELECT LNOT(:L1) FROM SYSIBM.

the result is zero. NOTE_TEXT) FROM IN_TRAY WHERE LOCATE(’GOOD’. the result is a number from 1 to the actual length of the source-string. It must be compatible with the source-string. start An expression that specifies the position within source-string at which the search is to start.start) . If the CCSID of the search-string is different than the CCSID of the source-string. SELECT RECEIVED. it indicates the character position in the source-string at which the search is to begin. If the search-string is not found and neither argument is null. Source-string may be a character-string. or a binary-string expression. see “POSITION or POSSTR” on page 279.LOCATE LOCATE LOCATE ( search-string . Search-string may be a character-string. It must be an integer that is greater than or equal to zero. the result is the null value. LOCATE(’GOOD’. it is converted to the CCSID of the source-string. SUBJECT. if any of the arguments is null. search-string ) For more information. the result can be null. The result of the function is a large integer. If the search-string is found. If any of the arguments can be null. Example v Select RECEIVED and SUBJECT columns as well as the starting position of the words ’GOOD’ within the NOTE_TEXT column for all entries in the IN_TRAY table that contain these words. source-string An expression that specifies the source string in which the search is to take place. the function is similar to: POSSTR( SUBSTR(source-string. NOTE_TEXT) <> 0 260 DB2 UDB for iSeries SQL Reference V5R2 . or a binary-string expression. the function is equivalent to: POSSTR( source-string . If the optional start is specified. a graphic-string. start ) The LOCATE function returns the starting position of the first occurrence of one string (called the search-string) within another string (called the source-string). a graphic-string. search-string ) If start is not specified. search-string An expression that specifies the string that is to be searched for. If start is specified. source-string .

The data type of the result is double-precision floating point. if the argument is null. Chapter 3. It is supported only for compatibility with previous DB2 releases. SELECT LOG10(:L) FROM SYSIBM.LOG10 LOG10 LOG10 ( numeric-expression ) The LOG10 function returns the common logarithm (base 10) of a number.49. Note Syntax alternatives: LOG is a synonym for LOG10. Built-In Functions 261 . the result can be null. LOG10 should be used instead of LOG because some database managers and applications implement LOG as the natural logarithm of a number instead of the common logarithm of a number. Example v Assume the host variable L is a DECIMAL(4. If the argument can be null. The argument value can be of any built-in numeric data type. the result is the null value. The LOG10 and ANTILOG functions are inverse operations.62.2) host variable with a value of 31.SYSDUMMY1 Returns the approximate value 1.

if necessary. does an OR comparison with the next string. the result is the null value.:L2. character-expression ) The LOR function returns a string that is the logical OR of the argument strings. the result is a fixed-length string of length n. where m is the actual length of the longest argument. where n is the length attribute of the argument with greatest length attribute. Example v Assume the host variable L1 is a CHARACTER(2) host variable with a value of X’0101’. where n is the length of the longest argument. the shorter arguments are padded with blanks (X’40’). In this case. The actual length of the result is m.SYSDUMMY1 Returns the value X’F1F1404F’. If an argument is encountered that is shorter than the previous result.:L2. and host variable L3 is a CHARACTER(4) host variable with a value of X’0000000F’. The CCSID of the result is 65535. SELECT LOR(:L1. If an argument can be null. so the logical OR result differs from the first example. 262 DB2 UDB for iSeries SQL Reference V5R2 . v Likewise. The arguments are converted. This function takes the first argument string. The arguments must be character strings but cannot be LOBs.:L3) FROM SYSIBM. host variable L2 is a CHARACTER(3) host variable with a value of X’F0F000’. to the attributes of the result.:L1) FROM SYSIBM. it is padded with blanks. The arguments cannot be mixed data character strings or graphic strings. the result is a varying-length string with length attribute n. the result can be null. The attributes of the result are determined as follows: v If all the arguments are fixed-length strings. and then continues to do OR comparisons for each successive argument using the previous result.LOR LOR LOR ( character-expression . SELECT LOR(:L3. if an argument is null. v If any argument is a varying-length string.SYSDUMMY1 Returns the value X’F1F1000F’.

the result can be null.SYSDUMMY1 The result is the value ’christine smith’. length attribute. The result of the function has the same data type. based on the CCSID of the argument. String-expression must be a character or UCS-2 graphic string. string-expression An expression that specifies the string to be converted. If the argument is null. and CCSID as the argument. The characters A-Z are converted to a-z. NAME has a data type of VARCHAR(30) and a value of ’Christine Smith’. the result is the null value. Refer to the UCS-2 level 1 mapping tables section of the Globalization topic in the iSeries Information Center for a description of the monocasing tables that are used for this translation. actual length. If the argument can be null. and characters with diacritical marks are converted to their lowercase equivalent. Note Syntax alternatives: LCASE is a synonym for LOWER.LOWER LOWER LOWER ( string-expression ) The LOWER function returns a string in which all the characters have been converted to lowercase characters. Built-In Functions 263 . Chapter 3. Only SBCS and UCS-2 graphic characters are converted. SELECT LOWER(:NAME) FROM SYSIBM. if any. Examples v Ensure that the characters in the value of host variable NAME are lowercase.

v If the argument is a DBCS graphic string. the result can be null. If all characters are removed. then the leading DBCS blanks are removed. v If the argument is a binary string. Example v Assume the host variable HELLO of type CHAR(9) has a value of ’ Hello’. If the first argument can be null. The actual length of the result is the length of string-expression minus the number of bytes removed. then the leading hexadecimal zeros (X’00’) are removed. 35 The argument must be a string expression. v If the first argument is a UCS-2 graphic string. then the leading UCS-2 blanks are removed v Otherwise.LTRIM LTRIM LTRIM ( string-expression ) The LTRIM function removes blanks or hexadecimal zeros from the beginning of a string expression. SELECT LTRIM(:HELLO) FROM SYSIBM. the result is an empty string. The LTRIM function returns the same results as: STRIP(expression. The data type of the result depends on the data type of expression: Data type of expression CHAR or VARCHAR GRAPHIC or VARGRAPHIC BLOB CLOB DBCLOB Data type of the Result VARCHAR VARGRAPHIC BLOB CLOB DBCLOB The length attribute of the result is the same as the length attribute of string-expression. The CCSID of the result is the same as that of the string. leading SBCS blanks are removed. if the first argument is null.SYSDUMMY1 Results in: ’Hello’.LEADING) 264 DB2 UDB for iSeries SQL Reference V5R2 . 35. the result is the null value.

if necessary. Character-string arguments are compatible with datetime values. v Assume the host variable M1 is a CHARACTER(2) host variable with a value of ’AA’.:M3) FROM SYSIBM. to the attributes of the result.MAX MAX MAX ( expression . The result of the function is the largest argument value. Chapter 3. The selected argument is converted.:M2. expression ) The MAX scalar function returns the maximum value in a set of values. and host variable M3 is a DECIMAL(3.25. The arguments must be compatible. but are not compatible with graphic strings. host variable M2 is a DECIMAL(3.5. The arguments cannot be DataLink values.:M3) FROM SYSIBM.2) host variable with a value of 6. host variable M2 is a CHARACTER(3) host variable with a value of ’AA ’. The attributes of the result are determined by all the operands as explained in “Rules for Result Data Types” on page 94. If a sort sequence other than *HEX is in effect when the statement is executed and SBCS.:M2.SYSDUMMY1 Returns the value ’AA A’.25. or mixed data is involved. Examples v Assume the host variable M1 is a DECIMAL(2. UCS-2.1) host variable with a value of 4. | | SELECT MAX(:M1. The result can be null if at least one argument can be null. Built-In Functions 265 . SELECT MAX(:M1. the weighted values of the strings are compared instead of the actual values.5.1) host variable with a value of 5. The weighted values are based on the sort sequence.SYSDUMMY1 Returns the value 6. and host variable M3 is a CHARACTER(4) host variable with a value of ’AA A’. the result is the null value if one of the arguments is null.

Select all rows in which the microseconds portion of TS1 is not zero and the seconds portion of TS1 and TS2 are identical. a character string. The other rules depend on the data type of the argument: v If the argument is a timestamp or a valid character-string representation of a timestamp: The result is the microsecond part of the value. which is an integer between −999999 and 999999. A nonzero result has the same sign as the argument. v If expression is a number.MICROSECOND MICROSECOND MICROSECOND ( expression ) The MICROSECOND function returns the microsecond part of a value. or a numeric data type. of type TIMESTAMP. see “String Representations of Datetime Values” on page 68. For the valid formats of datetime durations. SELECT * FROM TABLEA WHERE MICROSECOND(TS1) <> 0 AND SECOND(TS1) = SECOND(TS2) 266 DB2 UDB for iSeries SQL Reference V5R2 . TS1 and TS2. The result of the function is a large integer. Example v Assume a table TABLEA contains two columns. The argument must be an expression that returns a value of one of the following built-in data types: a timestamp. If the argument can be null. which is an integer between 0 and 999999. if the argument is null. it must not be a CLOB and its value must be a valid character-string representation of a timestamp. For the valid formats of string representations of timestamps. the result can be null. v If expression is a character string. v If the argument is a duration: The result is the microsecond part of the value. the result is the null value. it must be a timestamp duration. see “Datetime Operands and Durations” on page 135.

SELECT MIDNIGHT_SECONDS(’24:00:00’). and midnight and 13:10:10. Examples v Find the number of seconds between midnight and 00:01:00. and midnight and 00:00:00. see “String Representations of Datetime Values” on page 68. The result of the function is large integer. v Find the number of seconds between midnight and 24:00:00.SYSDUMMY1 This example returns 86400 and 0. Because there are 60 seconds in a minute and 3600 seconds in an hour.MIDNIGHT_SECONDS MIDNIGHT_SECONDS MIDNIGHT_SECONDS ( expression ) The MIDNIGHT_SECONDS function returns an integer value that is greater than or equal to 0 and less than or equal to 86 400 representing the number of seconds between midnight and the time value specified in the argument. An argument with a character-string data type must not be a CLOB. if the argument is null. the result is the null value. The argument must be an expression that returns a value of one of the following built-in data types: time. The result can be null. or a valid character-string representation of a time or timestamp. MIDNIGHT_SECONDS(’00:00:00’) FROM SYSIBM. different values are returned. Chapter 3. Built-In Functions 267 . 00:01:00 is 60 seconds after midnight ((60 * 1) + 0). a timestamp. SELECT MIDNIGHT_SECONDS(:XTIME1). and that XTIME2 has a value of ’13:10:10’.SYSDUMMY1 This example returns 60 and 47410. For the valid formats of string representations of timestamps. and 13:10:10 is 47410 seconds ((3600 * 13) + (60 * 10) + 10). MIDNIGHT_SECONDS(:XTIME2) FROM SYSIBM. Assume that host variable XTIME1 has a value of ’00:01:00’. Although these two values represent the same point in time.

Examples v Assume the host variable M1 is a DECIMAL(2.25.1) host variable with a value of 5. The weighted values are based on the sort sequence. v Assume the host variable M1 is a CHARACTER(2) host variable with a value of ’AA’. host variable M2 is a DECIMAL(3. but are not compatible with graphic strings. expression ) The MIN scalar function returns the minimum value in a set of values. to the attributes of the result. The attributes of the result are determined by all the operands as explained in “Rules for Result Data Types” on page 94. If a sort sequence other than *HEX is in effect when the statement is executed and SBCS. SELECT MIN(:M1.50. Character-string arguments are compatible with datetime values. The result can be null if at least one argument can be null.SYSDUMMY1 Returns the value 4.5. SELECT MIN(:M1. if necessary. and host variable M3 is a DECIMAL(3.SYSDUMMY1 Returns the value ’AA ’.2) host variable with a value of 6.MIN MIN MIN ( expression . The arguments cannot be DataLink values. 268 DB2 UDB for iSeries SQL Reference V5R2 . The result of the function is the smallest argument value.:M2. The arguments must be compatible.:M3) FROM SYSIBM. The selected argument is converted.:M2. host variable M2 is a CHARACTER(3) host variable with a value of ’AAA’. the weighted values of the strings are compared instead of the actual values.5.:M3) FROM SYSIBM. and host variable M3 is a CHARACTER(4) host variable with a value of ’AAAA’.1) host variable with a value of 4. UCS-2. the result is the null value if one of the arguments is null. or mixed data is involved.

MINUTE MINUTE MINUTE ( expression ) The MINUTE function returns the minute part of a value. Built-In Functions 269 . v If the argument is a time duration or timestamp duration: The result is the minute part of the value. or a valid character-string representation of a time or timestamp: The result is the minute part of the value. The other rules depend on the data type of the argument: v If the argument is a time. the result can be null. select all classes with a duration less than 50 minutes. see “String Representations of Datetime Values” on page 68. The argument must be an expression that returns a value of one of the following built-in data types: a time. it must not be a CLOB and its value must be a valid character-string representation of a time or timestamp. if the argument is null. If the argument can be null. v If expression is a number. SELECT * FROM CL_SCHED WHERE HOUR(ENDING . which is an integer between 0 and 59.STARTING) = 0 AND MINUTE(ENDING . A nonzero result has the same sign as the argument. a character string or a numeric data type. which is an integer between −99 and 99. a timestamp. the result is the null value. For the valid formats of string representations of times and timestamps. Example v Using the CL_SCHED sample table. see “Datetime Operands and Durations” on page 135. a timestamp.STARTING) < 50 Chapter 3. it must be a time duration or timestamp duration. For the valid formats of datetime durations. The result of the function is a large integer. v If expression is a character string.

the data type of the result is big integer. numeric-expression-2 cannot be zero. The precision of the result is min (p-s. if an argument is null.p’-s’) + max (s. where the symbols p and s denote the precision and scale of the first operand. SELECT MOD(:M1. An operation involving a floating-point number and a decimal number is performed with a temporary copy of the decimal number that has been converted to double-precision floating point. The formula used to calculate the remainder is: MOD(x. The result is negative only if first argument is negative. v Assume the host variable M1 is an integer host variable with a value of 5. The arguments must each be an expression that returns a built-in numeric data type. and host variable M2 is an integer host variable with a value of 2. if necessary. The result of a floating-point operation must be within the range of floating-point numbers. the result is decimal with the same precision and scale as the decimal argument. An operation involving a floating-point number and an integer is performed with a temporary copy of the integer that has been converted to double-precision floating point. The attributes of the result are determined as follows: v If both arguments are large or small integers with zero scale. If an argument can be null. numeric-expression-2 ) The MOD function divides the first argument by the second argument and returns the remainder. and host variable M2 is a DECIMAL(3. and the scale of the result is max (s. v If one argument is an integer with zero scale and the other is decimal. the data type of the result is double-precision floating point.y) = x .:M2) FROM SYSIBM. 270 DB2 UDB for iSeries SQL Reference V5R2 .s’).2) host variable with a value of 2. the result can be null. Examples v Assume the host variable M1 is an integer host variable with a value of 5. The operation is performed in floating point. v If both arguments are integers with zero scale and at least one of the arguments is a big integer.20. the result is decimal. the operands having been first converted to double-precision floating-point numbers. v If both arguments are decimal or integer with scale numbers. and the symbols p’ and s’ denote the precision and scale of the second operand.s’). v If either argument is floating point.SYSDUMMY1 Returns the value 1. the result is the null value.(x/y) * y where x/y is the truncated integer result of the division.MOD MOD MOD ( numeric-expression-1 . the data type of the result is large integer.

2) host variable with a value of 5.SYSDUMMY1 Returns the value 0. Built-In Functions 271 .1) host variable with a value of 2. and host variable M2 is a DECIMAL(4.50. SELECT MOD(:M1. Chapter 3.:M2) FROM SYSIBM.0.SYSDUMMY1 Returns the value 1.MOD SELECT MOD(:M1. v Assume the host variable M1 is a DECIMAL(4.50.:M2) FROM SYSIBM.60.

A nonzero result has the same sign as the argument. For the valid formats of datetime durations. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. a timestamp. a timestamp. or a numeric data type. The argument must be an expression that returns a value of one of the following built-in data types: a date.MONTH MONTH MONTH ( expression ) The MONTH function returns the month part of a value. Example v Select all rows from the EMPLOYEE table for people who were born (BIRTHDATE) in DECEMBER. The other rules depend on the data type of the argument: v If the argument is a date. it must be a date duration or timestamp duration. if the argument is null. v If expression is a number. the result can be null. v If expression is a character string. v If the argument is a date duration or timestamp duration: The result is the month part of the value. For the valid formats of string representations of dates and timestamps. The result of the function is a large integer. which is an integer between 1 and 12. or a valid character-string representation of a date or timestamp: The result is the month part of the value. SELECT * FROM EMPLOYEE WHERE MONTH(BIRTHDATE) = 12 272 DB2 UDB for iSeries SQL Reference V5R2 . If the argument can be null. see “String Representations of Datetime Values” on page 68. the result is the null value. a character string. see “Datetime Operands and Durations” on page 135. which is an integer between −99 and 99.

The result can be null. or DISTINCT clause. If the argument identifies a non-distributed table. a GROUP BY clause. common table expression. The argument must be a table designator of the subselect. The data type of the result is VARCHAR(18). If the subselect contains a GROUP BY or HAVING clause. Example v Join the EMPLOYEE and DEPARTMENT tables. If the argument identifies a view. the table name may be qualified. or derived table whose outer subselect includes a column function. a HAVING clause. common table expression. select the employee number (EMPNO) and determine the node from which each row involved in the join originated.DEPTNO Chapter 3. the table name cannot be qualified. or derived table derived from more than one base table. SELECT EMPNO. a UNION clause. NODENAME(X). or derived table. | | | | | | | | | | | | | If the argument identifies a view. NODENAME(Y) FROM EMPLOYEE X. For more information about table designators. If the argument is a correlation name. In system naming. the function returns the relational database name of the first table in the outer subselect of the view. DEPARTMENT Y WHERE X. In SQL naming. For more information about nodes. common table expression. The CCSID of the result is the default CCSID of the current server. The argument must not identify a view.DEPTNO=Y. the correlation name must not identify a correlated reference. the value of the CURRENT SERVER special register is returned. see the DB2 Multisystem book. common table expression.NODENAME NODENAME NODENAME ( table-designator ) The NODENAME function returns the relational database name of where a row is located. or derived table. the NODENAME function can only be specified in the WHERE clause or as an operand of a column function. Built-In Functions 273 . see “Table Designators” on page 111. the function returns the relational database name of its base table.

the function returns the node number of the first table in the outer subselect of the view. see the DB2 Multisystem book. or DISTINCT clause. a GROUP BY clause. If this is a distributed table. or derived table. SELECT NODENUMBER(EMPLOYEE). or derived table derived from more than one base table. The argument must be a table designator of the subselect. the NODENUMBER function can only be specified in the WHERE clause or as an operand of a column function. or derived table whose outer subselect includes a column function. or derived table. If the argument is a correlation name. a HAVING clause. In system naming. common table expression. If the argument identifies a non-distributed table. NODENUMBER will not return 0. The data type of the result is a large integer. but instead will return the underlying physical file member number. common table expression. the value 0 is returned. In SQL naming. see “Table Designators” on page 111. common table expression. Example v Determine the node number and employee name for each row in the EMPLOYEE table.36 For more information about nodes and node numbers. the table name may be qualified. For more information about table designators. The result can be null.NODENUMBER NODENUMBER NODENUMBER ( table-designator ) The NODENUMBER function returns the node number of a row. the table name cannot be qualified. the number of the node where the row exists is returned. If the argument identifies a DDS created logical file that is based on more than one physical file member. 274 DB2 UDB for iSeries SQL Reference V5R2 . If the argument identifies a view. The argument must not identify a view. the function returns the node number of its base table. | | | | | | | | | | | | If the argument identifies a view. the correlation name must not identify a correlated reference. LASTNAME FROM EMPLOYEE 36. common table expression. a UNION clause. If the subselect contains a GROUP BY or HAVING clause.

SYSDUMMY1 Chapter 3. The data type of the result is a timestamp. The value returned by the NOW function is the same as the value returned by the CURRENT TIMESTAMP special register. all values are based on a single clock reading. CURRENT TIME. Example v Return the current timestamp based on the time-of-day clock. Built-In Functions 275 . The result cannot be null. or CURRENT TIMESTAMP special registers within a single statement.NOW NOW NOW ( ) The NOW function returns a timestamp based on a reading of the time-of-day clock when the SQL statement is executed at the current server. or used with the CURDATE or CURTIME scalar functions or the CURRENT DATE. If this function is used more than once within a single SQL statement. SELECT NOW() FROM SYSIBM.

The arguments must be compatible and comparable data types.00. otherwise it returns the value of the first argument. :LOSSES ) FROM SYSIBM.00 respectively: SELECT NULLIF (:PROFIT + :CASH. expression ) The NULLIF function returns a null value if the arguments compare equal. NULLIF returns the value of the first operand. If one operand is a distinct type. CASE expressions consider this not true. The result of using NULLIF(e1. and LOSSES have DECIMAL data types with the values 4500. Character-string arguments are compatible with datetime values.00. 276 DB2 UDB for iSeries SQL Reference V5R2 . the other operand must be the same distinct type.e2) is the same as using the expression CASE WHEN e1=e2 THEN NULL ELSE e1 END Note that when e1=e2 evaluates to unknown (because one or both arguments is NULL). e1. in this situation. Example v Assume host variables PROFIT.SYSDUMMY1 Returns the null value. The result can be null. The result is null if the first argument is null or if both arguments are equal. The arguments cannot be DataLink values.NULLIF NULLIF NULLIF ( expression . CASH. Therefore. 500. and 5000. The attributes of the result are the attributes of the first argument.

SELECT EMPNO FROM EMPLOYEE WHERE PARTITION(EMPLOYEE) = 100 Chapter 3. the value 0 is returned. or derived table derived from more than one base table. If the argument is a correlation name. the function returns the partition number of its base table. The result can be null. the table name may be qualified. or DISTINCT clause. common table expression. Also see the HASH function. The argument must be a table designator of the subselect. common table expression. or derived table. If the subselect contains a GROUP BY or HAVING clause. In SQL naming. The data type of the result is a large integer with a value between 0 and 1023. or derived table. see “Table Designators” on page 111. If the argument identifies a non-distributed table. a HAVING clause. or derived table whose outer subselect includes a column function. | | | | | | | | | | | | | If the argument identifies a view. a GROUP BY clause. the function returns the partition number of the first table in the outer subselect of the view. Built-In Functions 277 . the PARTITION function can only be specified in the WHERE clause or as an operand of a column function. The argument must not identify a view.PARTITION PARTITION PARTITION ( table-designator ) The PARTITION function returns the partition number of a row obtained by applying the hashing function on the partitioning key value of the row. In system naming. For more information about table designators. the table name cannot be qualified. common table expression. see the DB2 Multisystem book. For more information about partition numbers and partitioning keys. the correlation name must not identify a correlated reference. If the argument identifies a view. a UNION clause. Example v Select the employee number (EMPNO) from the EMPLOYEE table for all rows where the partition number is equal to 100. common table expression.

There are no arguments. The result cannot be null.PI PI PI ( ) Returns the value of PI 3.SYSDUMMY1 278 DB2 UDB for iSeries SQL Reference V5R2 . Example v The following returns the circumference of a circle with diameter 10: SELECT PI()*10 FROM SYSIBM.141592653589793. The result of the function is double-precision floating-point.

POSITION or POSSTR POSITION or POSSTR POSITION ( search-string IN source-string ) POSSTR ( source-string . source-string An expression that specifies the source string in which the search is to take place. search-string ) The POSITION and POSSTR functions return the starting position of the first occurrence of one string (called the search-string) within another string (called the source-string). Because POSSTR operates on a strict byte-count basis. If a sort sequence other than *HEX is in effect when the statement that contains the POSSTR or POSITION function is executed and the arguments contain SBCS. then the result is obtained by comparing weighted values for each value in the set. The result of the function is a large integer. the result is zero. UCS-2. then the result returned by the function is the starting position of the first such substring within the source-string value. If either of the arguments is null. the search-string will only be found if any shift-in and shift-out characters are also found in the source-string in exactly the same positions. or a graphic-string expression. if the search-string or source-string contains mixed data. Chapter 3. – If the value of search-string is equal to an identical length of substring of contiguous positions within the value of source-string. If the search-string has a length of zero. Built-In Functions 279 . It must be compatible with the source-string. Source-string may be a binary-string. POSITION should be used instead of POSSTR. it is converted to the CCSID of the source-string. the result is a number from 1 to the actual length of the source-string. Search-string may be a binary-string. any shift-in and shift-out characters are not required to be in exactly the same position and their only significance is to indicate which characters are SBCS and which characters are DBCS. character-string. The POSSTR function operates on a strict byte-count basis. “LOCATE” on page 260. the result returned by the function is 1. character-string. v Otherwise. If the search-string is not found and neither argument is null. The weighted values are based on the sort sequence. or mixed data. search-string An expression that specifies the string that is to be searched for. the result returned by the function is 0. the result can be null. If the search-string is found. See the related function. Because POSITION operates on a character-string basis. If the CCSID of the search-string is different than the CCSID of the source-string. or a graphic-string expression. The POSITION function operates on a character basis. If either of the arguments can be null. the result is the null value. It is recommended that if either the search-string or source-string contains mixed data. Otherwise: v if the source-string has a length of zero.

280 DB2 UDB for iSeries SQL Reference V5R2 . the result returned by the function is 0. POSSTR(NOTE_TEXT. SELECT RECEIVED.37 Example v Select RECEIVED and SUBJECT columns as well as the starting position of the words ’GOOD’ within the NOTE_TEXT column for all entries in the IN_TRAY table that contain these words. ’GOOD’) <> 0 37. SUBJECT. ’GOOD’) FROM IN_TRAY WHERE POSSTR(NOTE_TEXT. This includes the case where the search-string is longer than the source-string.POSITION or POSSTR – Otherwise.

If an argument can be null. Chapter 3. then numeric-expression-2 must be an integer value. Built-In Functions 281 . The result of the POWER function is exactly the same as the result of exponentiation: numeric-expression-1 ** numeric-expression-2. If both arguments are 0. if an argument is null. The result of the function is a double-precision floating-point number.SYSDUMMY1 Returns the value 8. Example v Assume the host variable HPOWER is an integer with value 3. the result is the null value. then numeric-expression-2 must be greater than or equal to zero. the result is 1. If the value of numeric-expression-1 is less than zero.POWER POWER POWER ( numeric-expression-1 .:HPOWER) FROM SYSIBM. SELECT POWER(2. the result can be null. 38. If the value of numeric-expression-1 is equal to zero. numeric-expression-2 ) The POWER function returns the result of raising the first argument to the power of the second argument. 38 Each argument must be an expression that returns the value of any built-in numeric data type.

SELECT QUARTER(PRENDATE) INTO :QUART FROM PROJECT WHERE PROJNO = ’PL2100’ Results in QUART being set to 3. If the argument can be null. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. see “String Representations of Datetime Values” on page 68. If expression is a character string. The result of the function is a large integer. or March will return the integer 1.QUARTER QUARTER QUARTER ( expression ) The QUARTER function returns an integer between 1 and 4 that represents the quarter of the year in which the date resides. if the argument is null. a timestamp. Example v Using the PROJECT table. any dates in January. February. or a character string. the result can be null. 282 DB2 UDB for iSeries SQL Reference V5R2 . For the valid formats of string representations of dates and timestamps. The argument must be an expression that returns a value of one of the following built-in data types: a date. set the host variable QUART (INTEGER) to the quarter in which project ‘PL2100’ ended (PRENDATE). For example. the result is the null value.

The argument must be an expression that returns the value of any built-in numeric data type. The data type of the result is double-precision floating point.RADIANS RADIANS RADIANS ( numeric-expression ) The RADIANS function returns the number of radians for an argument that is expressed in degrees. If the argument is not a double precision floating-point number. The following statement: SELECT RADIANS(:HDEG) FROM SYSIBM.SYSDUMMY1 Returns a double precision floating-point number with an approximate value of 3. if the argument is null. it is converted to one for processing by the function. If the argument can be null. Example v Assume that host variable HDEG is an INTEGER with a value of 180. the result is the null value. Chapter 3. Built-In Functions 283 .1415926536. the result can be null.

SYSDUMMY1 Returns a random floating-point number between 0 and 1. such as the approximate value . If an expression is specified. The following statement: SELECT RAND(:HRAND) FROM SYSIBM. to get a random number between 0 and 10.SYSDUMMY1 284 DB2 UDB for iSeries SQL Reference V5R2 .RAND RAND RAND ( numeric-expression ) The RAND function returns a floating point value between 0 and 1.0121398. For example.8731398. The expression must be a SMALLINT or INTEGER. the result can be null. it is used as the seed value. such as the approximate value 5. multiply the RAND function by the size of the desired interval. if the argument is null. v To generate values in a numeric interval other than 0 to 1. If the argument can be null. multiply the function by 10: SELECT RAND(:HRAND) * 10 FROM SYSIBM. The data type of the result is double-precision floating point. the result is the null value. Example v Assume that host variable HRAND is an INTEGER with a value of 100.

integer. see “CAST Specification” on page 144. or decimal constant. Built-In Functions 285 . an error occurs. an error occurs. REAL is applied to SALARY so that the division is carried out in floating point: SELECT EMPNO. If the argument can be null. REAL(SALARY)/COMM FROM EMPLOYEE WHERE COMM > 0 Chapter 3. if the argument is null. the result is the null value. find the ratio of salary to commission for employees whose commission is not zero. The result is the same number that would result from CAST( character-expression AS REAL). To eliminate the possibility of out-of-range results. If the numeric value of the argument is not within the range of single-precision floating-point. the result can be null. For more information. Note Syntax alternatives: The CAST specification should be used for maximal portability. The result of the function is a single-precision floating-point number. The result is the same number that would occur if the argument were assigned to a single-precision floating-point column or variable. If the numeric value of the argument is not within the range of single-precision floating-point.REAL REAL REAL ( numeric-expression character-expression ) The REAL function returns a single-precision floating-point representation of: v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Real numeric-expression The argument is an expression that returns a value of any built-in numeric data type. The columns involved (SALARY and COMM) have DECIMAL data types. Example v Using the EMPLOYEE table. Character to Real character-expression An expression that returns a character string value. Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming an floating-point.

2).700 0874. 1. The absolute value of integer specifies the number of places to the right of the decimal point for the result if numeric-expression–2 is not negative. ROUND(873.000 0900.726. ROUND(-3.726. the result can be null. numeric-expression–1 is rounded to the numeric-expression–2 number of places to the right of the decimal point. 1). For example. the result is the null value. ROUND(873. ROUND(873. ROUND(873. Examples v Calculate the number 873. -1). numeric-expression–1 An expression that returns a value of any built-in numeric data type.730 0873.SYSDUMMY1 286 DB2 UDB for iSeries SQL Reference V5R2 .000 0870. 0). the result is 0. -4) FROM SYSIBM.726. 0). If numeric-expression–2 is not negative. numeric-expression–1 is rounded to the absolute value of (numeric-expression–2+1) number of places to the left of the decimal point. ROUND(873. numeric-expression-2 ) The ROUND function returns numeric-expression–1 rounded to some number of places to the right or left of the decimal point.000 1000.726.1.726 rounded to 2.000 v Calculate both positive and negative numbers. respectively: 0873. SELECT ROUND( 3.726. The data type and length attribute of the result are the same as the data type and length attribute of the first argument. -3).2) will result in DECIMAL(6. An argument with a data type of DECIMAL(31.5. ROUND(-3. an argument with a data type of DECIMAL(5. A digit value of 5 is rounded to the next lower negative number. SELECT ROUND(873. 0) FROM SYSIBM.1.ROUND ROUND ROUND ( numeric-expression-1 .726.726. If either argument can be null.2).000 0000. -3. ROUND( 3. -1. except that precision is increased by one if numeric-expression–1 is DECIMAL or NUMERIC and the precision is less than 31. 0.SYSDUMMY1 Returns the following values. If either argument is null. If the absolute value of numeric-expression–2 is greater than the number of digits to the left of the decimal point. and -4 decimal places respectively. -2.2) will result in DECIMAL(31.5. A digit value of 5 is rounded to the next higher positive number. numeric-expression–2 An expression that returns a small or large integer. If numeric-expression–2 is negative. -2). 2). ROUND(873. 0). 0). or to left of the decimal point if numeric-expression–2 is negative.

0 -04. respectively: 04.ROUND Returns the following examples.0 respectively.0 03. Chapter 3. Built-In Functions 287 .0 -03.

Example v Assume that table EMPLOYEE contains a ROWID column EMP_ROWID. The length attribute of the result is 40. the result is truncated. If the actual length of string-expression is less than 40. If the actual length of string-expression is greater than 40. Although the string can contain any value. If the argument can be null. string-expression An expression that returns a character string or binary string value. the result is not padded. if the argument is null. SELECT EMPNO FROM EMPLOYEE WHERE EMP_ROWID = ROWID(X’F0DFD230E3C0D80D81C201AA0A280100000000000203’) 288 DB2 UDB for iSeries SQL Reference V5R2 . it is recommended that it contain a ROWID value that was previously generated by DB2 UDB for OS/390 and z/OS or DB2 UDB for iSeries to ensure a valid ROWID value is returned. Note Syntax alternatives: The CAST specification should be used for maximal portability. Using direct row access. the function can be used to convert a ROWID that value that was cast to CHAR value back to a ROWID value. The actual length of the result is the length of string-expression. For more information. a warning is returned. Also assume that the table contains a row that is identified by a row ID value that is equivalent to X’F0DFD230E3C0D80D81C201AA0A280100000000000203’. see “CAST Specification” on page 144. the result is the null value. The string-expression must not be a CLOB. select the employee number for that row. If non-blank characters are truncated. the result can be null.ROWID | | | ROWID ( string-expression ) ROWID | | | | | | | | | | | | | | | | | | | | | | | | | | | The ROWID function casts a character string to a row ID. The result of the function is a row ID. For example.

This means that RRN will not be unique for each row of a distributed table. Built-In Functions 289 . or derived table. common table expression. the table name may be qualified. a GROUP BY clause. The argument must be a table designator of the subselect. or DISTINCT clause. If the argument is a correlation name. common table expression. or derived table whose outer subselect includes a column function. or derived table. the function returns the relative record number of its base table. or derived table derived from more than one base table. | | | | | If the argument identifies a view. In SQL naming. the function returns the relative record number of the first table in the outer subselect of the view. a UNION clause. common table expression. In system naming. SELECT RRN(EMPLOYEE). see “Table Designators” on page 111. The data type of the result is a decimal with precision 15 and scale 0. The RRN function cannot be specified in a SELECT clause if the subselect contains a column function. the correlation name must not identify a correlated reference. The result can be null. or a HAVING clause. If the argument identifies a view. the function returns the relative record number of the row on the node where the row is located. | | | | | | | | The argument must not identify a view. the table name can not be qualified. a GROUP BY clause. common table expression. LASTNAME FROM EMPLOYEE WHERE DEPTNO = 20 Chapter 3. Example v Return the relative record number and employee name from table EMPLOYEE for those employees in department 20. a HAVING clause. If the argument identifies a distributed table.RRN RRN RRN ( table-designator ) The RRN function returns the relative record number of a row. For more information about table designators.

if the first argument is null. the result is an empty string. If all characters are removed.SYSDUMMY1 Results in: ’Hello’. The CCSID of the result is the same as that of the string. v If the first argument is a UCS-2 graphic string. 39 The argument must be a string expression. The data type of the result depends on the data type of string-expression: Data type of expression CHAR or VARCHAR GRAPHIC or VARGRAPHIC BLOB CLOB DBCLOB Data type of the Result VARCHAR VARGRAPHIC BLOB CLOB DBCLOB The length attribute of the result is the same as the length attribute of string-expression. v If the argument is a DBCS graphic string. If the first argument can be null. then the trailing hexadecimal zeros (X’00’) are removed. SELECT RTRIM(:HELLO) FROM SYSIBM. Example v Assume the host variable HELLO of type CHAR(9) has a value of ’Hello ’. 39.TRAILING) 290 DB2 UDB for iSeries SQL Reference V5R2 . the result is the null value. trailing SBCS blanks are removed. v If the argument is a binary string.RTRIM RTRIM RTRIM ( string-expression ) The RTRIM function removes blanks or hexadecimal zeroes from the end of a string expression. the result can be null. The actual length of the result is the length of the expression minus the number of bytes removed. The RTRIM function returns the same results as: STRIP(expression. then the trailing DBCS blanks are removed. then the trailing UCS-2 blanks are removed v Otherwise.

v If the argument is a time duration or timestamp duration: The result is the seconds part of the value. If the argument can be null. a timestamp. SELECT SECOND(RECEIVED) FROM IN_TRAY Returns the value 30. Chapter 3. which is an integer between 0 and 59. Examples v Assume that the host variable TIME_DUR (DECIMAL(6. it must be a time duration or timestamp duration. or a valid character-string representation of a time or timestamp: The result is the seconds part of the value. or a numeric data type. see “Datetime Operands and Durations” on page 135. which is an integer between −99 and 99. v Assume that the column RECEIVED (TIMESTAMP) has an internal value equivalent to 1988-12-25-17.0)) has the value 153045. v If expression is a character string. it must not be a CLOB and its value must be a valid character-string representation of a time or timestamp.000000. A nonzero result has the same sign as the argument. The result of the function is a large integer.12. the result can be null. a timestamp. the result is the null value.SECOND SECOND SECOND ( expression ) The SECOND function returns the seconds part of a value. The argument must be an expression that returns a value of one of the following built-in data types: a time.30.SYSDUMMY1 Returns the value 45. v If expression is a number. if the argument is null. For the valid formats of datetime durations. SELECT SECOND(:TIME_DUR) FROM SYSIBM. The other rules depend on the data type of the argument: v If the argument is a time. Built-In Functions 291 . see “String Representations of Datetime Values” on page 68. For the valid formats of string representations of times and timestamps. a character string.

an argument with a data type of DECIMAL(5. For example. Example v Assume that host variable PROFIT is a large integer with a value of 50000. For example. DECIMAL(31. If the argument can be null.30). if the argument is null. If the precision is already 31. the scale will be decreased by one. 292 DB2 UDB for iSeries SQL Reference V5R2 . the result is the null value.31) will result in DECIMAL(31.5) will result in DECIMAL(6. except that precision is increased by one if the argument is DECIMAL or NUMERIC and the scale of the argument is equal to its precision. SELECT SIGN(:PROFIT) FROM EMPLOYEE Returns the value 1.SIGN SIGN SIGN ( numeric-expression ) The SIGN function returns an indicator of the sign of expression.5). The returned value is: –1 0 1 if the argument is less than zero if the argument is zero if the argument is greater than zero The argument must be an expression that returns a value of any built-in numeric data type. The result has the same data type and length attribute as the argument. the result can be null.

If the argument can be null. The argument must be an expression that returns the value of any built-in numeric data type. Built-In Functions 293 . if the argument is null. The SIN and ASIN functions are inverse operations. the result is the null value.SYSDUMMY1 Returns the approximate value 0.99. where the argument is an angle expressed in radians. Example v Assume the host variable SINE is a decimal (2. The data type of the result is double-precision floating point.SIN SIN SIN ( numeric-expression ) The SIN function returns the sine of the argument. SELECT SIN(:SINE) FROM SYSIBM. Chapter 3. the result can be null.1) host variable with a value of 1.5.

If the argument can be null. the result can be null.12. SELECT SINH(:HSINE) FROM SYSIBM. Example v Assume the host variable HSINE is a decimal (2. if the argument is null.1) host variable with a value of 1. The data type of the result is double-precision floating point. where the argument is an angle expressed in radians.SYSDUMMY1 Returns the approximate value 2. the result is the null value.SINH SINH SINH ( numeric-expression ) The SINH function returns the hyperbolic sine of the argument.5. 294 DB2 UDB for iSeries SQL Reference V5R2 . The argument must be an expression that returns the value of any built-in numeric data type.

select a list containing salary (SALARY) divided by education level (EDLEVEL). The list should also contain the values used in the calculation and the employee number (EMPNO). If the whole part of the argument is not within the range of small integers.SMALLINT SMALLINT Numeric to Smallint SMALLINT ( numeric-expression ) Character to Smallint SMALLINT ( character-expression ) The SMALLINT function returns a small integer representation of v A number v A character string representation of a decimal number v A character string representation of an integer v A character string representation of a floating-point number Numeric to Smallint numeric-expression An expression that returns a numeric value of any built-in numeric data type. The result of the function is a small integer. Built-In Functions 295 . If the argument can be null. Example v Using the EMPLOYEE table. SALARY. SELECT SMALLINT(SALARY / EDLEVEL). If the argument is null. Any fractional part of the argument is truncated. The fractional part of the argument is truncated. see “CAST Specification” on page 144. integer. The fractional part of the argument is truncated. The result is the same number that would result from CAST( character-expression AS SMALLINT). or decimal constant. Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming a floating-point. an error occurs. Truncate any decimal in the calculation. The expression must not be a CLOB. Note Syntax alternatives: The CAST specification should be used for maximal portability. the result is the null value. EMPNO FROM EMPLOYEE Chapter 3. an error occurs. If the whole part of the argument is not within the range of small integers. the result can be null. EDLEVEL. The result is the same number that would occur if the argument were assigned to a small integer column or variable. Character to Smallint character-expression An expression that returns a value that is a character-string representation of an integer. For more information.

The result can be used to compare with the sound of other strings. LASTNAME FROM EMPLOYEE WHERE SOUNDEX(LASTNAME) = SOUNDEX(’Loucesy’) Returns the row: 000110 LUCCHESSI 296 DB2 UDB for iSeries SQL Reference V5R2 . It makes assumptions about the way that letters and combinations of letters sound that can help to search out words with similar sounds. The argument can be any built-in string data type other than a BLOB. The comparison can be done directly or by passing the strings as arguments to the DIFFERENCE function. The data type of the result is CHAR(4). or DBCLOB. CLOB. find the EMPNO and LASTNAME of the employee with a surname that sounds like ’Loucesy’. the result is the null value. SELECT EMPNO. see “DIFFERENCE” on page 223. The SOUNDEX function is useful for finding strings for which the sound is known but the precise spelling is not.SOUNDEX SOUNDEX SOUNDEX ( string-expression ) The SOUNDEX function returns a 4 character code representing the sound of the words in the argument. Example v Using the EMPLOYEE table. If the argument can be null. if the argument is null. | The CCSID of the result is the default CCSID of the current server. the result can be null. For more information.

The actual length of the result is the value of numeric-expression.SYSDUMMY1 Chapter 3. The CCSID is the default CCSID for SBCS data of the job. the length attribute of the result is the constant. the result is the null value. it must not be the constant 0. and it must be between 0 and 32740. The actual length of the result must not be greater than the length attribute of the result.SPACE SPACE SPACE ( numeric-expression ) The SPACE function returns a character string that consists of the number of SBCS blanks that the argument specifies. Otherwise. The argument must be an expression that results in an integer. Built-In Functions 297 . The result of the function is a varying-length character string (VARCHAR) that contains SBCS data. If the argument can be null. the length attribute of the result is 4000. The integer specifies the number of SBCS blanks for the result. SELECT SPACE(5) FROM SYSIBM. If numeric-expression is a constant. the result can be null. Example v The following statement returns a character string that consists of 5 blanks. if the argument is null. If numeric-expression is a constant.

The argument is converted to double-precision floating point for processing by the function.SYSDUMMY1 Returns the approximate value 3. The value of numeric-expression must be greater than or equal to zero. the result can be null.SQRT SQRT SQRT ( numeric-expression ) The SQRT function returns the square root of a number. 298 DB2 UDB for iSeries SQL Reference V5R2 .00. if the argument is null.1) host variable with a value of 9. the result is the null value. If the argument can be null. The argument must be an expression that returns a value of any built-in numeric data type.0. SELECT SQRT(:SQUARE) FROM SYSIBM. Example v Assume the host variable SQUARE is a DECIMAL(2. The data type of the result is double-precision floating point.

. Built-In Functions 299 . see “TRIM” on page 311. . For more information. BOTH B LEADING L TRAILING T . . Chapter 3. . The STRIP function is identical to the TRIM scalar function.STRIP STRIP STRIP ( string-expression . strip-character ) The STRIP function removes blanks or another specified character from the end and/or beginning of a string expression. .

SUBSTRING or SUBSTR SUBSTRING or SUBSTR SUBSTR ( string-expression . string-expression An expression that specifies the string from which the result is derived. If the resulting length is zero. start SUBSTRING SUBSTRING ( string-expression FROM start ) . If string-expression is a character string. the result is the empty string. If specified. start may be negative or zero. The data type of the result depends on the data type of string-expression and whether the function is a SUBSTR or SUBSTRING: 300 DB2 UDB for iSeries SQL Reference V5R2 . the result of the function is a graphic string. Hexadecimal zeroes are used as the padding character when string-expression is a binary string. A substring of string-expression is zero or more contiguous characters of string-expression. (The length attribute of a varying-length string is its maximum length. omission of length is an implicit specification of LENGTH(string-expression) . It may also be greater than the length attribute of string-expression. The SUBSTR function accepts mixed data strings. If string-expression is a graphic string. which is the number of characters (or bytes) from the start character (or byte) to the last character (or byte) of string-expression. If SUBSTRING is specified and length is explicitly specified. be the integer constant 0. the result of the function is a character string. If it is a graphic string. where n is the length attribute of string-expression . It must not. start An expression that specifies the position within string-expression of the first character (or byte) of the result. If SUBSTR is specified and length is explicitly specified. If string-expression is a fixed-length string. If it is a binary string. graphic. If string-expression is a character string or binary string. the result will not necessarily be a properly formed mixed data string.start + 1. If string-expression is a varying-length string. the result of the function is a binary string.start + 1. a character is a byte. or binary string. padding is not performed.start + 1. length ) FOR length | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The SUBSTR and SUBSTRING functions return a substring of a string. length must be an integer that is greater than or equal to 0 and less than or equal to n. omission of length is an implicit specification of zero or LENGTH(string-expression) . whichever is greater. however. because SUBSTR operates on a strict byte-count basis. It must be a binary integer. String-expression must be a character.) length An expression that specifies the length of the result. string-expression is effectively padded on the right with the necessary number of blank characters so that the specified substring of string-expression always exists. a character is a DBCS or UCS-2 character. However.

v Likewise. SELECT SUBSTR(:NAME.SYSDUMMY1 Chapter 3. the length attribute of the result is equal to the length attribute of string-expression. v If length is explicitly specified by an integer constant. 1) FROM SYSIBM. but string-expression is a fixed-length string and start is an integer constant. (Remember that if the actual length of string-expression is less than the value for start. The CCSID of the result is the same as that of string-expression. v If length is not explicitly specified. VARGRAPHIC.SYSDUMMY1 Returns the value 'AUSTIN'. :SURNAME_POS. v length is not explicitly specified. the result can be null. if: v length is explicitly specified by an integer constant.) | | If any argument of the SUBSTR function can be null. in all other cases. SELECT SUBSTR(:NAME.SUBSTRING or SUBSTR Data Type of the Result for SUBSTRING VARCHAR Data type of string-expression CHAR or VARCHAR Data Type of the Result for SUBSTR CHAR. In all other cases. v length is not explicitly specified. start. and the attributes of string-expression. If the SUBSTR function is specified and string-expression is not a LOB. the length attribute of the result is the same as the length attribute of string-expression. Examples v Assume the host variable NAME (VARCHAR(50)) has a value of 'KATIE AUSTIN' and the host variable SURNAME_POS (INTEGER) has a value of 7. but string-expression is a fixed-length string and start is an integer constant. DBCLOB BLOB DBCLOB BLOB DBCLOB BLOB If the SUBSTRING function is specified. the length attribute of the result is length. Built-In Functions 301 . the result is the null value.start + 1. if: v length is explicitly specified by an integer constant. VARCHAR. the length attribute of the result is LENGTH(string-expression) . :SURNAME_POS) FROM SYSIBM. in all other cases CLOB GRAPHIC or VARGRAPHIC CLOB VARGRAPHIC CLOB GRAPHIC. if any argument is null. the length attribute of the result depends on length. but string-expression is a fixed-length string and start is an integer constant. the actual length of the substring is zero.

v Select all rows from the PROJECT table for which the project name (PROJNAME) starts with the word 'OPERATION '.10) = ’OPERATION ’ The space at the end of the constant is necessary to preclude initial words such as 'OPERATIONS'.1. 302 DB2 UDB for iSeries SQL Reference V5R2 . SELECT * FROM PROJECT WHERE SUBSTR(PROJNAME.SUBSTRING or SUBSTR Returns the value 'A'.

the result is the null value. if the argument is null.SYSDUMMY1 Returns the approximate value 14. Chapter 3.1) host variable with a value of 1. The TAN and ATAN functions are inverse operations. Built-In Functions 303 . where the argument is an angle expressed in radians.5.TAN TAN TAN ( numeric-expression ) The TAN function returns the tangent of the argument. If the argument can be null. The argument must be an expression that returns the value of any built-in numeric data type. The data type of the result is double-precision floating point.10. the result can be null. SELECT TAN(:TANGENT) FROM SYSIBM. Example v Assume the host variable TANGENT is a DECIMAL(2.

The data type of the result is double-precision floating point. the result is the null value. The TANH and ATANH functions are inverse operations.TANH TANH TANH ( numeric-expression ) The TANH function returns the hyperbolic tangent of the argument. Example v Assume the host variable HTANGENT is a DECIMAL(2. 304 DB2 UDB for iSeries SQL Reference V5R2 . SELECT TANH(:HTANGENT) FROM SYSIBM. where the argument is an angle expressed in radians. the result can be null. if the argument is null. If the argument can be null. The argument must be an expression that returns the value of any built-in numeric data type.SYSDUMMY1 Returns the approximate value 0.1) host variable with a value of 1.5.90.

or a character string. For more information. that value is converted to adhere to the default CCSID for SBCS data before it is interpreted and converted to a time value. If expression is a character string. see “CAST Specification” on page 144. if the argument is null. The argument must be an expression that returns a value of one of the following built-in data types: a time. see “String Representations of Datetime Values” on page 68. For the valid formats of string representations of dates and timestamps. a timestamp.TIME TIME TIME ( expression ) The TIME function returns a time from a value. that value is converted to adhere to the default CCSID for mixed data before it is interpreted and converted to a time value. The result of the function is a time. v If the argument is a timestamp: The result is the time part of the timestamp. The other rules depend on the data type of the argument: v If the argument is a time: The result is that time. the result is the null value. When a string representation of a time is mixed data with a CCSID that is not the same as the default CCSID for mixed data. Built-In Functions 305 . v If the argument is a character string: The result is the time or time part of the timestamp represented by the character string. Note Syntax alternatives: The CAST specification should be used for maximal portability. If the argument can be null. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. Example v Select all notes from the IN_TRAY sample table that were received at least one hour later in the day (any day) than the current time. When a string representation of a time is SBCS with a CCSID that is not the same as the default CCSID for SBCS data. SELECT * FROM IN_TRAY WHERE TIME(RECEIVED) >= CURRENT TIME + 1 HOUR Chapter 3. the result can be null.

The result of the function is a timestamp. the result can be null. expression ) The TIMESTAMP function returns a timestamp from its argument or arguments. The microsecond part of the timestamp is zero. and nnn are digits between 001 and 366 denoting a day of that year. If either argument can be null.TIMESTAMP TIMESTAMP TIMESTAMP ( expression . For the valid formats of string representations of dates and timestamps. The second argument must be an expression that returns a value of one of the following built-in data types: a time or a character string. v If only one argument is specified and it is a character string: The result is the timestamp represented by that character string. it must not be a CLOB and its value must be one of the following: – A valid character-string representation of a date or timestamp. If expression is a character string. If the argument is a character string of length 14. where yyyy is year. If the first expression is a character string. – A character string with an actual length of 7 that represents a valid date in the form yyyynnn. mm is minute. it must not be a CLOB and its value must be a valid character-string representation of a time. the result is the null value. v If only one argument is specified: The argument must be an expression that returns a value of one of the following built-in data types: a timestamp or a character string. hh is hour. see “String Representations of Datetime Values” on page 68. dd is day. xx is month. it must not be a CLOB and its value must be a valid character-string representation of a date. v If both arguments are specified: The first argument must be an expression that returns a value of one of the following built-in data types: a date or a character string. If the second expression is a character string. 306 DB2 UDB for iSeries SQL Reference V5R2 . The rules for the arguments depend on whether the second argument is specified. where yyyy are digits denoting a year. v If only one argument is specified and it is a timestamp: The result is that timestamp. The other rules depend on whether the second argument is specified: v If both arguments are specified: The result is a timestamp with the date specified by the first argument and the time specified by the second argument. For the valid formats of string representations of dates and times. and ss is seconds. – A character string with an actual length of 14 that represents a valid date and time in the form yyyyxxddhhmmss. the timestamp has a microsecond part of zero. if either argument is null. see “String Representations of Datetime Values” on page 68.

see “CAST Specification” on page 144. Chapter 3.TIMESTAMP When a string representation of a timestamp is SBCS data with a CCSID that is not the same as the default CCSID for SBCS data. that value is converted to adhere to the default CCSID for SBCS data before it is interpreted and converted to a timestamp value. the CAST specification should be used for maximal portability.12.SYSDUMMY1 Returns the value ’1988-12-25-17.12. Note Syntax alternatives: If only one argument is specified. TIME(’17. Built-In Functions 307 . that value is converted to adhere to the default CCSID for mixed data before it is interpreted and converted to a timestamp value. Example | | | | v Assume the following date and time values: SELECT TIMESTAMP( DATE(’1988-12-25’).30. For more information.000000’.30’) ) FROM SYSIBM. When a string representation of a timestamp is mixed data with a CCSID that is not the same as the default CCSID for mixed data.

The first argument must be a built-in data type of either INTEGER or SMALLINT. which is a timestamp duration. The result of the function is an integer. the result is 30. For example. This is because the difference between the timestamps is 1 month so the assumption of 30 days in a month applies.00’ and ’1997-02-01-00. to the interval type specified in the first argument. Valid values of interval (the first argument) are: 1 2 4 8 16 32 64 128 256 Fractions of a second Seconds Minutes Hours Days Weeks Months Quarters Years The second argument is the result of subtracting two timestamps types and converting the result to CHAR(22). SELECT TIMESTAMPDIFF(64. The returned estimate may vary by a number of days.00’.00. the result is the null value. The following assumptions may be used in estimating the difference: v there are 365 days in a year v there are 30 days in a month v there are 24 hours in a day v there are 60 minutes in an hour v there are 60 seconds in a minute These assumptions are used when converting the information in the second argument. if the number of days (interval 16) is requested for a difference in timestamps for ’1997-03-01-00.00. if either argument is null. based on the difference between two timestamps. Example v Estimate the age of employees in months. If either argument can be null. the result can be null. character-expression ) The TIMESTAMPDIFF function returns an estimated number of intervals of the type defined by the first argument. CAST(CURRENT_TIMESTAMP-CAST(BIRTHDATE AS TIMESTAMP) AS CHAR(22))) AS AGE_IN_MONTHS FROM EMPLOYEE 308 DB2 UDB for iSeries SQL Reference V5R2 .TIMESTAMPDIFF TIMESTAMPDIFF TIMESTAMPDIFF ( numeric-expression .

The string must be a character string constant. pad A string that specifies the character with which to pad to-string if its length is less than from-string. When a character in from-string is found. the SBCS characters of the argument are converted to uppercase. no other arguments may be specified. string-expression An expression that specifies the string to be converted string-expression must be a character string or a UCS-2 graphic string. If the first argument is a UCS-2 graphic string. Built-In Functions 309 . pad ) The TRANSLATE function returns a value in which one or more characters in string-expression may have been converted into other characters. If only the first argument is specified. The string must be a character string constant. and characters with diacritical marks are converted to their uppercase equivalent. If the length attribute of the to-string is less than the length attribute of the from-string. the character in string-expression is converted to the character in to-string that is in the corresponding position of the character in from-string. Only SBCS characters are converted. from-string A string that specifies the characters that if found in string-expression are to be converted. Chapter 3. to-string A string that specifies the characters to which certain characters in string-expression are to be converted. the extra characters in to-string are ignored without warning. the alphabetic UCS-2 characters are converted to uppercase. the first one scanning from the left is used and no warning is issued. The string must be a character string constant with a length of 1. Refer to the UCS-2 level 1 mapping tables section of the Globalization topic in the iSeries Information Center for a description of the monocasing tables that are used for this conversion. If there are duplicate characters in from-string. if any. to-string . This string is sometimes called the input translation table. A character string argument must have an actual length that is not greater than 256.TRANSLATE TRANSLATE TRANSLATE ( string-expression . then the to-string is padded to the longer length using either the pad character if it is specified or a blank if a pad character is not specified. If the length attribute of the to-string is greater than the length attribute of the from-string. The default value for from-string is a string starting with the character X’00’ and ending with the character X’FF’ (decimal 255). If the first argument is UCS-2 graphic. based on the CCSID of the argument. The default is an SBCS blank. This string is sometimes called the output translation table. A character string argument must not have an actual length that is not greater than 256. from-string . The characters a-z are converted to A-Z.

the result can be null.SYSDUMMY1 Returns the value ’ABCDEF’. if used improperly. 310 DB2 UDB for iSeries SQL Reference V5R2 . may result in an invalid mixed string. ’Place’. the same character is searched for in from-string. If to-string is less than n characters long. SELECT TRANSLATE(:SITE. the result string is built character by character from string-expression.TRANSLATE If more than one argument is specified. ’L’) FROM SYSIBM. converting characters in from-string to the corresponding character in to-string. SELECT TRANSLATE(:SITE. If the character is found to be the nth character in from-string. the resulting string will contain the pad character.SYSDUMMY1 Returns the value ’Pivabiska $ake P$ace’. Examples v Monocase the string ’abcdef’. If the character is not found in from-string.SYSDUMMY1 Returns the value ’Pivabiska $ake Place’. ’pLA’. ’. ’$’.’. the result is the null value. actual length.SYSDUMMY1 Returns the value ’pivAbiskA LAk. ’Ll’) FROM SYSIBM. The result of the function has the same data type. length attribute. Conversion is done on a byte basis and. SELECT TRANSLATE(’abcdef’) FROM SYSIBM. ’$$’. pLA.’) FROM SYSIBM. If the argument is null. it is moved to the result string unconverted. If the first argument can be null.SYSDUMMY1 ) Returns the value v Given that the host variable SITE is a varying-length character string with a value of ’Pivabiska Lake Place’. the resulting string will contain the nth character from to-string. v Monocase the mixed character string.. For each character in string-expression. SELECT TRANSLATE(:SITE. The SRTSEQ attribute does not apply to the TRANSLATE function. and CCSID as the argument. SELECT TRANSLATE( FROM SYSIBM.

v Otherwise. If string-expression is a DBCS graphic or DBCS-only string. SBCS. then the default strip character is a hexadecimal zero (X’00’). the second argument must be a graphic constant consisting of a single DBCS character. The actual length of the result is the length of the expression minus the number of bytes removed. the default strip character is an SBCS blank. If string-expression is a binary string. or DBCS character that is to be removed. the result is the null value.TRIM TRIM TRIM ( BOTH FROM B LEADING L TRAILING T strip-character string-expression ) The TRIM function removes blanks or another specified character from the end or beginning of a string expression. If the first argument is not specified. v If string-expression is a UCS-2 graphic string. then the default strip character is a UCS-2 blank. if the first argument is null. Built-In Functions 311 . if specified. The data type of the result depends on the data type of string-expression: Data type of expression CHAR or VARCHAR GRAPHIC or VARGRAPHIC BLOB CLOB DBCLOB Data type of the Result VARCHAR VARGRAPHIC BLOB CLOB DBCLOB The length attribute of the result is the same as the length attribute of string-expression. the second argument must be a binary string constant. If all characters are removed. If the first argument can be null. v If string-expression is a DBCS graphic string. is a single-character constant that indicates the binary. The second argument. The first argument. then the characters are removed from both the end and the beginning of the string. then the default strip character is a DBCS blank. The string-expression must be a string expression. If the second argument is not specified then: v If string-expression is a binary string. if specified. the result can be null. indicates whether characters are removed from the end or beginning of the string. the result is an empty string. Chapter 3.

SELECT TRIM( L ’0’ FROM :BALANCE ) FROM SYSIBM. The SRTSEQ attribute does not apply to the TRIM function. v Assume the host variable BALANCE of type CHAR(9) has a value of ’000345.SYSDUMMY1 Results in ’Hello’ and ’ Hello’ respectively.50’ v Assume the string to be stripped contains mixed data. Examples v Assume the host variable HELLO of type CHAR(9) has a value of ’ Hello’.TRIM The CCSID of the result is the same as that of the string.50’. SELECT TRIM(:HELLO).SYSDUMMY1 Results in: 312 DB2 UDB for iSeries SQL Reference V5R2 .SYSDUMMY1 Results in: ’345. TRIM( TRAILING FROM :HELLO) FROM SYSIBM. SELECT TRIM( BOTH FROM ) FROM SYSIBM.

000 0870.726. the result is 0. If numeric-expression–2 is negative. -2. -2). If the absolute value of numeric-expression–2 is larger than the number of digits to the left of the decimal point. Truncate the result to two places to the right of the decimal point. the example returns the value 4395. v Calculate the number 873. and -3 decimal places respectively.83. Examples v Calculate the average monthly salary for the highest paid employee. The absolute value of integer specifies the number of places to the right of the decimal point for the result if numeric-expression–2 is not negative.726. TRUNCATE(873. numeric-expression–1 is truncated to the absolute value of (numeric-expression–2+1) number of places to the left of the decimal point.726. TRUNCATE(873. 2). or to left of the decimal point if numeric-expression–2 is negative.TRUNCATE TRUNCATE or TRUNC TRUNCATE TRUNC ( numeric-expression-1 .-4) = 0. SELECT TRUNCATE(873. TRUNCATE(873. TRUNCATE(873. numeric-expression–1 is truncated to the numeric-expression–2 number of places to the right of the decimal point.000 0000.726. -1. TRUNCATE(748. The data type and length attribute of the result are the same as the data type and length attribute of the first argument. the result can be null.00 per year. TRUNCATE(873.700 0873.000 v Calculate both positive and negative numbers. 1). 1. -3) FROM SYSIBM. 0. Chapter 3. If numeric-expression–2 is not negative. 2) FROM EMPLOYEE Because the highest paid employee in the sample employee table earns $52750.000 0800. If either argument can be null.726 truncated to 2.SYSDUMMY1 Returns the following values respectively: 0873. Built-In Functions 313 . If either argument is null. numeric-expression1 An expression that returns a value of any built-in numeric data type. 0). numeric-expression-2 ) The TRUNCATE function returns numeric-expression–1 truncated to some number of places to the right or left of the decimal point. For example. the result is the null value.58.726.726.720 0873. SELECT TRUNCATE(MAX(SALARY/12. -1). numeric-expression2 An expression that returns a small or large integer.

0).TRUNCATE SELECT TRUNCATE( 3. 0). TRUNCATE(-3. TRUNCATE(-3.SYSDUMMY1 This example returns: 3.0 respectively. 0). 314 DB2 UDB for iSeries SQL Reference V5R2 .1. TRUNCATE( 3.5.5. 0) FROM SYSIBM.0 -3.1.0 3.0 -3.

The UCASE function is identical to the UPPER function. Built-In Functions 315 . based on the CCSID of the argument. Chapter 3. For more information. see “UPPER” on page 316.UCASE | | | UCASE ( string-expression ) UCASE | | | | The UCASE function returns a string in which all the characters have been converted to uppercase characters.

and characters with diacritical marks are converted to their uppercase equivalent. the result is the null value.SYSDUMMY1 Returns the value: ) 316 DB2 UDB for iSeries SQL Reference V5R2 . SELECT UPPER( FROM SYSIBM. SELECT UPPER(’abcdef’) FROM SYSIBM. length attribute. if the argument is null. actual length. Note Syntax alternatives: UCASE is a synonym for UPPER. based on the CCSID of the argument. and CCSID as the argument. Refer to the UCS-2 level 1 mapping tables section of the Globalization topic in the iSeries Information Center for a description of the monocasing tables that are used for this translation. v Uppercase the mixed character string using the UPPER scalar function.SYSDUMMY1 Returns the value ’ABCDEF’. the result can be null. Only SBCS and UCS-2 graphic characters are converted. The result of the function has the same data type. String-expression must be a character or UCS-2 graphic string.UPPER UPPER UPPER ( string-expression ) The UPPER function returns a string in which all the characters have been converted to uppercase characters. If the argument can be null. if any. string-expression An expression that specifies the string to be converted. The characters a-z are converted to A-Z. Examples v Uppercase the string ’abcdef’ using the UPPER scalar function.

Built-In Functions 317 . expression ) The VALUE function returns the value of the first non-null expression. Chapter 3. see “COALESCE” on page 202.VALUE VALUE VALUE ( expression . The VALUE function is identical to the COALESCE scalar function. For more information.

length DEFAULT . integer ) Graphic to Varchar VARCHAR ( graphic-expression . integer ) Integer to Varchar VARCHAR ( integer-expression ) Decimal to Varchar VARCHAR ( decimal-expression . If the first argument can be null. or BIGINT v A decimal number if the first argument is a packed or zoned decimal number v A double-precision floating-point number if the first argument is a DOUBLE or REAL v A character string if the first argument is any type of character string v A graphic string if the first argument is a UCS-2 graphic string The result of the function is a varying-length string. Character to Varchar character-expression An expression that returns a value that is a built-in CHAR. The value must be between 1 and 32740 (32739 if nullable). the result can be null. decimal-character ) Floating-point to Varchar VARCHAR ( floating-point-expression . decimal-character ) The VARCHAR function returns a character-string representation of: v An integer number if the first argument is a SMALLINT. if the first argument is null. length Specifies the length attribute for the resulting varying length character string. INTEGER. the second argument cannot be less than 4. 318 DB2 UDB for iSeries SQL Reference V5R2 .VARCHAR VARCHAR Character to Varchar VARCHAR ( character-expression . VARCHAR. the result is the null value. length DEFAULT . If the first argument is mixed data. or CLOB data type.

then the result is mixed data. The actual length of the result is the minimum of the length attribute of the result and the actual length of graphic-expression. The CCSID of the result is the same as the CCSID of the first argument. It must not be DBCS-graphic data. truncation is performed. If the third argument is not specified then: v If the first argument is SBCS data. then the result is SBCS data. the second argument cannot be less than 4. If the third argument is a mixed CCSID. If the third argument is an SBCS CCSID. A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. | | | | | | | | | | | | | | | | length Specifies the length attribute for the resulting varying length character string. The value must be between 1 and 32740 (32739 if nullable). the length attribute of the result is 1. v If the result is SBCS data. mixed data CCSID. integer Specifies the CCSID of the result. The third argument cannot be 65535. the length attribute of the result is 1. truncation is performed. then the first argument cannot be a DBCS-either or DBCS-only string. If the third argument is 65535. If the first argument contains DBCS data. The actual length of the result is the minimum of the length attribute of the result and the actual length of character-expression. v If the result is mixed data. Built-In Functions 319 . the length attribute of the result is the same as the length attribute of the first argument. If the length of the character-expression is greater than the length attribute of the result. If the second argument is not specified or DEFAULT is specified. and DBCLOB data type. The CCSID of the result is the same as the CCSID of the first argument. or 65535 (bit data). then the result is mixed data. If the third argument is a mixed CCSID. integer Specifies the CCSID of the result. then the result is SBCS data. VARGRAPHIC. If the third argument is a SBCS CCSID. then the result is bit data. Chapter 3. the result length is n. then the result is SBCS data. v Otherwise. It must be a valid SBCS CCSID or mixed data CCSID. DBCS-only. the result length is (2. If the length of the character-expression is greater than the length attribute of the result. then the result is mixed data. If the third argument is an SBCS CCSID. or DBCS-either).VARCHAR If the second argument is not specified or DEFAULT is specified: v If the character-expression is an empty string constant. v If the first argument is mixed data (DBCS-open. It must be a valid SBCS CCSID. Graphic to Varchar graphic-expression An expression that returns a value that is a GRAPHIC.5*(n-1)) + 4. A warning (SQLSTATE 01004) is returned unless the truncated characters were all blanks. the length attribute of the result is determined as follows (where n is the length attribute of the first argument): v If the graphic-expression is the empty graphic string constant.

the first character is a digit. | | | | | decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string. the CCSID of the result is the default CCSID at the current server. For more information. If the default CCSID is mixed data. v If the argument is a small integer. The result is a varying-length character string representation of the argument. Trailing zeros are returned. where p is the precision of the decimal-expression with a preceding minus sign if the argument is negative. see “Decimal Point” on page 103. Floating-point to Varchar floating-point expression An expression that returns a value that is a floating-point data type (DOUBLE or REAL). The character must be a period or comma. The result is a varying-length character string of the argument in the form of an SQL integer constant. INTEGER. The actual length of the result is the smallest number of characters that can be used to represent the value of the argument.VARCHAR If the third argument is not specified. or BIGINT). If the default CCSID is SBCS data. the result begins with a digit. then the result is SBCS data. the result begins with a minus sign. Leading zeroes are not included. Integer to Varchar integer-expression An expression that returns a value that is an integer data type (either SMALLINT. v If the argument is a large integer. then the result is mixed data. The CCSID of the result is the default SBCS CCSID at the current server. If the argument is negative. Leading zeros are not returned. Otherwise. Decimal to Varchar decimal-expression An expression that returns a value that is a packed or zoned decimal data type (either DECIMAL or NUMERIC). The length attribute of the result is 2+p where p is the precision of the decimal-expression. It is left justified. If the second argument is not specified. the length attribute of the result is 11. 320 DB2 UDB for iSeries SQL Reference V5R2 . the length attribute of the result is 6. the first character of the result is a minus sign. The actual length of the result is the smallest number of characters that can be used to represent the result. the decimal point is the default decimal point. Otherwise. The result includes a decimal character and up to p digits. v If the argument is a big integer. except that trailing characters are included. Leading zeros are not included. If a different precision and scale is desired. The result consists of n characters that are the significant digits that represent the value of the argument with a preceding minus sign if the argument is negative. If the argument is negative. the length attribute of the result is 20. The CCSID of the result is the default SBCS CCSID at the current server. the DECIMAL scalar function can be used to make the change.

If the argument is negative. The character must be a period or comma. the CAST specification should be used for maximal portability. For more information. If the argument is zero.VARCHAR | | | | | decimal-character Specifies the single-byte character constant that is used to delimit the decimal digits in the result character string. Built-In Functions 321 . The length attribute of the result is 24. If the second argument is not specified. The CCSID of the result is the default SBCS CCSID at the current server. otherwise. see “CAST Specification” on page 144. Note Syntax alternatives: If the length attribute is specified. the first character of the result is a minus sign. see “Decimal Point” on page 103. the result is 0E0. Example v Make EMPNO varying-length with a length of 10. the first character is a digit. SELECT VARCHAR(EMPNO.10) INTO :VARHV FROM EMPLOYEE Chapter 3. For more information. the decimal point is the default decimal point. The result is a varying-length character string representation of the argument in the form of a floating-point constant. The actual length of the result is the smallest number of characters that can represent the value of the argument such that the mantissa consists of a single digit other than zero followed by the decimal-character and a sequence of digits.

The CCSID cannot be 65535. If integer is not specified then the CCSID of the result is determined by a mixed CCSID. length DEFAULT . integer Specifies the CCSID of the result. If the expression is an empty string or the EBCDIC string X’0E0F’. Each character of the argument determines a character of the result. It must be a DBCS or UCS-2 CCSID. truncation is performed and no warning is returned. If the CCSID represents UCS-2 graphic data. integer ) The VARGRAPHIC function returns a graphic string representation of a string expression. the length attribute of the result is the same as the length attribute of the first argument. the length attribute of the result is 1. If the expression can be null. Let M denote that mixed CCSID. length Specifies the length attribute of the result and must be an integer constant between 1 and 16370 if the first argument is not nullable or between 1 and 16369 if the first argument is nullable. Character to Graphic character-expression Specifies a character string expression. The result of the function is a varying-length graphic string (VARGRAPHIC).VARGRAPHIC VARGRAPHIC Character to Graphic VARGRAPHIC ( character-expression . In the following rules. The nth character of the result is the UCS-2 equivalent of the nth character of the argument. integer ) Graphic to Graphic VARGRAPHIC ( graphic-expression . except if the expression is an empty string or the EBCDIC string X’0E0F’. the result can be null. The actual length of the result depends on the number of characters in the argument. S denotes one of the following: 322 DB2 UDB for iSeries SQL Reference V5R2 . each character of the argument determines a character of the result. the result is an empty string. If the second argument is not specified. or if DEFAULT is specified. the result is the null value. It cannot be a CHAR or VARCHAR bit data. length DEFAULT . If the length attribute of the resulting varying-length string is less than the actual length of the first argument. If the expression is null.

the nth character of the result is that DBCS character. S is that string expression. v If the nth character of the argument is an SBCS character that does not have an equivalent DBCS character. – Otherwise the operation is not allowed. the length attribute of the result is 1. length Specifies the length attribute of the result and must be an integer constant between 1 and 16370 if the first argument is not nullable or between 1 and 16369 if the first argument is nullable. M is determined as follows: v If the CCSID of S is a mixed CCSID. the nth character of the result is the DBCS substitution character. v If the CCSID of S is an SBCS CCSID: – If the CCSID of S has an associated mixed CCSID. or if DEFAULT is specified. Built-In Functions 323 . M 930 933 935 937 939 5026 5035 Result CCSID 300 834 837 835 300 4396 4396 Description Japanese EBCDIC Korean EBCDIC S-Chinese EBCDIC T-Chinese EBCDIC Japanese EBCDIC Japanese EBCDIC Japanese EBCDIC DBCS Substitution Character X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ X’FEFE’ The equivalence of SBCS and DBCS characters depends on M. S is the result of the expression after converting the data to a CCSID in a native encoding scheme. and every single-byte code point in the argument is considered an SBCS character with the exception of the EBCDIC mixed data shift codes X’0E’ and X’0F’. Regardless of the CCSID. v If the nth character of the argument is an SBCS character that has an equivalent DBCS character. v If the nth character of the argument is a DBCS character. If the second argument is not specified. Graphic to VarGraphic graphic-expression An expression that returns a value that is a graphic string.VARGRAPHIC v If the string expression is a host variable containing data in a foreign encoding scheme. the nth character of the result is that equivalent DBCS character.) v If the string expression is data in a native encoding scheme. M is that CCSID. M is that CCSID. (See “Character Conversion” on page 32 for more information. the length attribute of the result is the same as the length attribute of the first argument. except if the expression is an empty string. every double-byte code point in the argument is considered a DBCS character. The following table summarizes the result CCSID based on M. Chapter 3.

SELECT VARGRAPHIC(FIRSTNME) INTO :VAR_DESC FROM EMPLOYEE WHERE EMPNO = ’000050’ 324 DB2 UDB for iSeries SQL Reference V5R2 . set the host variable VAR_DESC (VARGRAPHIC(24)) to the VARGRAPHIC equivalent of the first name (FIRSTNME) for employee number (EMPNO) ’000050’. Note Syntax alternatives: If the first argument is graphic-expression and the length attribute is specified. see “CAST Specification” on page 144.VARGRAPHIC The actual length of the result depends on the number of characters in graphic-expression. Example v Using the EMPLOYEE table. the result is truncated and no warning is returned. If the length of graphic-expression is greater than the length specified. It must be a DBCS or UCS-2 CCSID. If integer is not specified then the CCSID of the result is the CCSID of the first argument. For more information. integer Specifies the CCSID of the result. The CCSID cannot be 65535. the CAST specification should be used for maximal portability.

WEEK WEEK WEEK ( expression ) The WEEK function returns an integer between 1 and 54 that represents the week of the year. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. Built-In Functions 325 . the result is the null value. The argument must be an expression that returns a value of one of the following built-in data types: a date. see “String Representations of Datetime Values” on page 68. For the valid formats of string representations of dates and timestamps. If the argument can be null. SELECT WEEK(PRENDATE) INTO :WEEK FROM PROJECT WHERE PROJNO = ’PL2100’ Results in WEEK being set to 38. WEEK(DATE_1) FROM X Results in the following list shows what is returned by the WEEK function for various dates. Example v Using the PROJECT table. If expression is a character string. v Assume that table X has a DATE column called DATE_1 with various dates from the list below. 1997-12-28 1997-12-31 1998-01-01 1999-01-01 1999-01-04 1999-12-31 2000-01-01 2000-01-03 53 53 1 1 2 53 1 2 Chapter 3. if the argument is null. SELECT DATE_1. and January 1 is always in the first week. a timestamp. the result can be null. set the host variable WEEK (INTEGER) to the week that project (‘PL2100’) ended. The result of the function is a large integer. The week starts with Sunday. or a character string.

set the host variable WEEK (INTEGER) to the week that project (‘AD2100’) ended. The result of the function is a large integer. it is possible to have up to 3 days at the beginning of the year appear as the last week of the previous year or to have up to 3 days at the end of a year appear as the first week of the next year. For the valid formats of string representations of dates and timestamps. SELECT DATE_1. If expression is a character string. WEEK_ISO(DATE_1) FROM X Results in the following: 1997-12-28 1997-12-31 1998-01-01 1999-01-01 1999-01-04 1999-12-31 2000-01-01 2000-01-03 52 1 1 53 1 52 52 1 326 DB2 UDB for iSeries SQL Reference V5R2 . Thus. The argument must be an expression that returns a value of one of the following built-in data types: a date. a timestamp. SELECT WEEK_ISO(PRENDATE) INTO :WEEK FROM PROJECT WHERE PROJNO = ’AD3100’ Results in WEEK being set to 5. which is equivalent to the first week containing January 4. Week 1 is the first week of the year to contain a Thursday. the result is the null value. the result can be null. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp.WEEK_ISO WEEK_ISO WEEK_ISO ( expression ) The WEEK_ISO function returns an integer between 1 and 53 that represents the week of the year. Examples v Using the PROJECT table. v Assume that table X has a DATE column called DATE_1 with various dates from the list below. if the argument is null. see “String Representations of Datetime Values” on page 68. or a character string. If the argument can be null. The week starts with Monday.

the result is a fixed-length string of length n. SELECT XOR(:L3. If an argument can be null. if necessary.:L3) FROM SYSIBM. expression ) The XOR function returns a string that is the logical XOR of the argument strings. The arguments must be character strings but cannot be LOBs. The arguments cannot be mixed data character strings or graphic strings.SYSDUMMY1 Returns the value X’1111400F’. the shorter results are padded with blanks (X’40’). so the logical XOR result differs from the result in the following example. SELECT XOR(:L1. If an argument is encountered that is shorter than the previous result. the result is the null value. v If any argument is a varying-length string.:L2. it is padded with blanks. This function takes the first argument string. does an XOR comparison with the next string. host variable L2 is a CHARACTER(3) host variable with a value of X’F0F000’. The arguments are converted.:L1) FROM SYSIBM. Example v Assume the host variable L1 is a CHARACTER(2) host variable with a value of X’E1E1’. to the attributes of the result. Built-In Functions 327 . where n is the length of the longest argument. the result is a varying-length string with length attribute n. where n is the length attribute of the argument with greatest length attribute. The CCSID of the result is 65535.XOR XOR XOR ( expression . where m is the actual length of the longest argument.SYSDUMMY1 Returns the value X’1111404F’. the result can be null. Chapter 3. In this case. and host variable L3 is a CHARACTER(4) host variable with a value of X’0000000F’. if an argument is null. and then continues to do XOR comparisons for each successive argument using the previous result. The attributes of the result are determined as follows: v If all the arguments are fixed-length strings.:L2. The actual length of the result is m.

v If expression is a number. Examples v Select all the projects in the PROJECT table that are scheduled to start (PRSTDATE) and end (PRENDATE) in the same calendar year. For the valid formats of datetime durations. The other rules depend on the data type of the argument: v If the argument is a date or a timestamp or a valid character-string representation of a date or timestamp: The result is the year part of the value.YEAR YEAR YEAR ( expression ) The YEAR function returns the year part of a value. The argument must be an expression that returns a value of one of the following built-in data types: a date. A nonzero result has the same sign as the argument. a timestamp. For the valid formats of string representations of dates and timestamps. if the argument is null. SELECT * FROM PROJECT WHERE YEAR(PRSTDATE) = YEAR(PRENDATE) v Select all the projects in the PROJECT table that are scheduled to take less than one year to complete. or a numeric data type. see “String Representations of Datetime Values” on page 68. a character string. which is an integer between −9999 and 9999. If the argument can be null. SELECT * FROM PROJECT WHERE YEAR(PRENDATE . see “Datetime Operands and Durations” on page 135. v If the argument is a date duration or timestamp duration: The result is the year part of the value. which is an integer between 1 and 9999. v If expression is a character string. the result is the null value. it must be a date duration or timestamp duration. the result can be null. it must not be a CLOB and its value must be a valid character-string representation of a date or timestamp. The result of the function is a large integer.PRSTDATE) < 1 328 DB2 UDB for iSeries SQL Reference V5R2 .

the result is the null value. The default for precision depends on the data type of the numeric-expression: v v v v 15 for floating point. An error occurs if the number of significant decimal digits required to represent the whole part of the number is greater than p-s. Numeric to Zoned Decimal numeric-expression An expression that returns a value of any built-in numeric data type. where p and s are the second and third arguments. scale-integer ) Character to Zoned Decimal ZONED ( character-expression . numeric. decimal. Built-In Functions 329 .ZONED ZONED Numeric to Zoned Decimal ZONED ( numeric-expression . if the first argument is null. precision An integer constant with a value greater than or equal to 1 and less than or equal to 31. the default is 0. precision . or nonzero scale binary 19 for big integer 11 for large integer 5 for small integer scale An integer constant that is greater than or equal to 0 and less than or equal to precision. The result is the same number that would occur if the first argument were assigned to a decimal column or variable with a precision of p and a scale of s. If the first argument can be null. decimal-character ) The ZONED function returns a zoned decimal representation of: v A number v A character string representation of an integer v A character string representation of a decimal number v A character string representation of a floating-point number The result of the function is a zoned decimal number with precision of p and scale of s. Character to Zoned Decimal Chapter 3. scale . precision-integer . If not specified. the result can be null.

For more information. see “Decimal Point” on page 103.SYSDUMMY1 Returns the value 1. SELECT ZONED(:Z1. Note Syntax alternatives: When the precision is specified. The character must be a period or comma. 330 DB2 UDB for iSeries SQL Reference V5R2 .14) FROM SYSIBM. Examples v Assume the host variable Z1 is a decimal host variable with a value of 1. v Likewise.SYSDUMMY1 Returns the value 1123. If not specified.00. Leading and trailing blanks are eliminated and the resulting string must conform to the rules for forming an integer or decimal constant. An error occurs if the number of significant digits to the left of the decimal-character (the whole part of the number) in character-expression is greater than p-s. Digits are truncated from the end if the number of digits to the right of the decimal-character is greater than the scale s. The default decimal separator character is not valid in the substring if the decimal-character argument is specified.SYSDUMMY1 Returns the value 1123. v Assume the host variable Z1 is a decimal host variable with a value of 1123. the decimal point is the default decimal separator character. For more information. precision An integer constant that is greater than or equal to 1 and less than or equal to 31. SELECT ZONED(:Z1. The expression must not be a CLOB. SELECT ZONED(:Z1. the default is 0. scale An integer constant that is greater than or equal to 0 and less than or equal to precision.12300000000000.ZONED character-expression An expression that must contain a character-string representation of a number.2) FROM SYSIBM. see “CAST Specification” on page 144.s)). If not specified. If the second argument is not specified.11. the default is 15. | | | | | | decimal-character Specifies the single-byte character constant that was used to delimit the decimal digits in character-expression from the whole part of the number. the CAST specification should be used for maximal portability.123.4) FROM SYSIBM. The result is the same number that would result from CAST(character-expression AS NUMERIC(p.15.

2002 331 . or v It has been granted the system authorities of *OBJOPR and *READ on the view and the system authority *READ on all tables and views on which this view is directly or indirectly dependent. A query is a component of certain SQL statements. v It has been granted the SELECT privilege on the view. or v It has been granted the system authorities of *OBJOPR and *EXECUTE on the function. and – The system authority *EXECUTE on the library containing the table or view v Administrative authority The authorization ID of the statement has the SELECT privilege on a table when: v It is the owner of the table. 1998.” Authorization For any form of a query. all tables and views referenced in its definition. See also.Chapter 4. v It has been granted the EXECUTE privilege on the function. That is. the privileges held by the authorization ID of the statement must include at least one of the following: v For each table or view identified in the statement. © Copyright IBM Corp. Queries A query specifies a result table or an intermediate result table. the authorization ID of the statement must include at least one of the following for each user-defined function: v The EXECUTE privilege on the function v Administrative authority The authorization ID of the statement has the EXECUTE privilege on a function when: v It is the owner of the function. and if a view is referenced. and so forth. v It has been granted the SELECT privilege on the table. or v It has been granted the system authorities of *OBJOPR and *READ on the table The authorization ID of the statement has the SELECT privilege on a view when: v It is the owner of the view. – The SELECT privilege on the table or view. There are three forms of a query: v The subselect v The fullselect v The select-statement Another form of select is described under “SELECT INTO” on page 728. “Authorization. If an expression includes a function. all tables and views referenced in the view definition.

The derivation can be described as a sequence of operations in which the result of each operation is input for the next. HAVING clause 5. which in turn. then the null value is returned. (This is only a way of describing the subselect.subselect subselect select-clause from-clause where-clause group-by-clause having-clause The subselect is a component of the fullselect and the CREATE VIEW statement. enclosed in parentheses. | | | | A scalar-subselect is a subselect. If the result of the subselect is no rows.) The sequence of the (hypothetical) operations is: 1. The method used to perform the derivation may be quite different from this description. are components of a subselect. SELECT clause 332 DB2 UDB for iSeries SQL Reference V5R2 . WHERE clause 3. A subselect specifies a result table derived from the tables or views identified in the FROM clause. GROUP BY clause 4. that returns a single result row and a single result column. An error is returned if there is more than one row in the result. It is also a component of certain predicates. FROM clause 2.

Two rows are duplicates of one another only if each value in the first row is equal to the corresponding value in the second row. For example. R is the result of that WHERE clause. if the only clauses specified are SELECT. The column values are produced by the application of the select list to R. Each column-name in the expression must unambiguously identify a column of R. ALL Selects all rows of the final result table and does not eliminate duplicates. * does not identify any columns that have been added to a table after the statement has been prepared. expression Specifies the values of a result column. Hence. The name must not be qualified and does not have to be unique. and R is the result of the previous operation of the subselect.* The SELECT clause specifies the columns of the final result table. view name. FROM.* Represents a list of names that identify the columns of name in the order the columns are produced by the FROM clause. This is the default. Queries 333 . DISTINCT is not allowed if the select list contains a LOB or DATALINK column. Chapter 4. The name can be a table name.select-clause select-clause ALL SELECT DISTINCT * . the second name in the list identifies the second column of the table or view.* correlation-name. DISTINCT Eliminates all but one of each set of duplicate rows of the final result table. Select List Notation * Represents a list of names that identify the columns of table R in the order the columns are produced by the FROM clause. or correlation name. The first name in the list identifies the first column of the table or view. name. expression AS column-name table-name. (For determining duplicate rows. and must designate a table or view named in the FROM clause. two null values are considered equal.) Sort sequence is also used for determining distinct values.* view-name. and so on. and WHERE. column-name or AS column-name Names or renames the result column. The list of names is established when the statement containing the SELECT clause is prepared. The select list is the names or expressions specified in the SELECT clause.

the list of names is not re-established. In either case the nth column of the result contains the values specified by applying the nth expression in the operational form of the select list. there are four cases where the list of names is established again and the number of columns can change: v When an SQL program or SQL package is saved and then restored on an iSeries system that is not the same release as the system from which it was saved. v If the select list is a list of column functions. If neither GROUP BY nor HAVING is used: v The select list must not include any column functions. and NODENUMBER functions cannot be specified in the select list.select-clause The list of names is established when the statement containing the SELECT clause is prepared. v When an SQL statement is executed for the first time after the install of a more recent release of OS/400. Therefore. the select list may apply additional operators to the column name. v The select list is applied to each group of R. or it must be entirely a list of column functions. the select list may contain C1+1. the select list may contain C1+1. When the select list is applied to a group of R. when SQL statements are implicitly rebound. Hence. The result of a subquery must be a single expression. v When the SELECT * occurs in the subselect of an INSERT statement or in a subselect within a predicate. * does not identify any columns that have been added to a table after the statement has been prepared. the number of columns returned by the statement does not change. The number of columns in the result of SELECT is the same as the number of expressions in the operational form of the select list (that is. For example. Applying the Select List The results of applying the select list to R depend on whether or not GROUP BY or HAVING is used: If GROUP BY or HAVING is used: v Each expression that contains a column-name in the select list must identify a grouping expression or be specified within a column function: – If the grouping expression is a column name. NODENAME. unless the subquery is used in the EXISTS predicate. and cannot exceed 8000. Normally. and the result contains as many rows as there are groups in R. if the grouping expression is a column C1. v When SQL naming is specified for an SQL program or package and the owner of the program has changed since the SQL program or package was created. However. the list established at prepare time). the select list is applied to each row of R and the result contains as many rows as there are rows in R. – If the grouping expression is not a column name. PARTITION. R is the source of the arguments of the functions and the result of applying the select list is one row. but not (C1+1)/8. For example. that group is the source of the arguments of the column functions in the select list. and a table or view referenced in the subselect has been deleted and recreated with additional columns. if the grouping expression is C1+1. v If the select list does not include column functions. 334 DB2 UDB for iSeries SQL Reference V5R2 . the select list may not apply additional operators to the expression. v The RRN.

INTEGER or BIGINT (if the value of the constant is outside the range of INTEGER. The same as the data type of the column. If the data type of the variable is not identical to an SQL data type (for example. For a built-in function. v All other result columns are unnamed. the name of the result column is the corresponding name in the correlation column list. the name of the result column is the name specified on the AS clause. When the expression is: the name of any numeric column an integer constant a decimal or floating-point constant The data type of the result column is: The same as the data type of the column. v If neither an AS clause nor a column list in the correlation clause is specified and the result column is derived only from a single column (without any functions or operators). Queries 335 .select-clause Null attributes of result columns | Result columns allow null values if they are derived from: v Any column function but COUNT and COUNT_BIG v v v v Any column that allows null values A scalar function or expression with an operand that allows null values A host variable that has an indicator variable A result of a UNION if at least one of the corresponding items in the select list is nullable | | v An arithmetic expression v A scalar subselect v A user-defined scalar or table function Names of result columns v If the AS clause is specified. For a user-defined function. The data type of the result of the function. with the same variable precision and scale for decimal variables. the result column is decimal. | | | | | any function the name of any string column Chapter 4. with the same precision and scale for decimal constants. an expression The same as the data type of the result. DISPLAY SIGN LEADING SEPARATE in COBOL). see Chapter 3 to determine the data type of the result. but within the range of BIGINT). with the same precision and scale for decimal columns. then the result column name is the unqualified name of that column. the name of any numeric host The same as the data type of the variable. the data type of the result is what was defined in the CREATE FUNCTION statement for the function. Data types of result columns Each column of the result of SELECT acquires a data type from the expression from which it is derived. with the same length attribute. with the same precision and scale for decimal results as described under “Expressions” on page 130. v If a column list is specified in the correlation clause. The same as the data type of the constant.

VARCHAR(n) VARGRAPHIC(n) The same as the data type of the column or host variable. or an ILE RPG compiler or ILE COBOL compiler datetime host variable | | | | the name of a datalink column the name of a row ID column or a row ID host variable the name of a distinct type column A datalink.select-clause When the expression is: the name of any string host variable The data type of the result column is: The same as the data type of the variable. 336 DB2 UDB for iSeries SQL Reference V5R2 . precision. the result column is a varying-length string. ROWID the same as the distinct type of the column. with the same length. If the data type of the variable is not identical to an SQL data type (for example. and scale attributes. if any. with a length attribute equal to the length of the variable. a NUL-terminated string in C). with the same length attribute. a character-string constant of length n a graphic-string constant of length n the name of a datetime column.

and so on.from-clause from-clause . the intermediate result table is simply the result of that table-reference. table-reference single-table nested-table-expression table-function joined-table single-table: table-name view-name correlation-clause nested-table-expression: ( fullselect order-by-clause fetch-first-clause ) correlation-clause table-function: TABLE ( function-name ( . If only one table-reference is specified. If more than one table-reference is specified in the FROM clause. Queries 337 . the intermediate result table consists of all possible combinations of the rows of the specified table-references (the Cartesian product). ( column-name ) Chapter 4. expression ) ) correlation-clause correlation-clause: AS correlation-name . Each row of the result is a row from the first table-reference concatenated with a row from the second table-reference. The number of rows in the result is the product of the number of rows in all the individual table-references. FROM table-reference The FROM clause specifies an intermediate result table. concatenated in turn with a row from the third.

column-names can also be specified to give names to the columns of the table-name. a table-name that is not followed by a correlation-name. v If a joined-table is specified. For more information. The exposed names of all table references should be unique. Unless given column names in the correlation-clause. nested-table-expressions and table-functions can be specified in any from-clause. see “Correlation Names” on page 109. uses the function name and the arguments to determine the exact function to use. An exposed name is a correlation-name. the intermediate result table is simply that table or view. v If a function-name is specified. Each correlation-name is defined as a designator of the intermediate result table specified by the immediately preceding table-reference. together with the types of its arguments. When a correlation-name is specified. which is described on “Function resolution” on page 125. This is analogous to the column names of a table. The list of names in the FROM clause must conform to these rules: v Each table-name and view-name must name an existing table or view at the current server or the table-name of a common-table expression (see “common-table-expression” on page 352) defined preceding the subselect containing the table-reference. | | | | | | | | v Each function-name. Columns from the nested table expressions and table functions can be referenced in the select list and in the rest of the subselect using the correlation | | 40. For more information. The correlation-name is used to qualify references to the columns of the table or view. A correlation name must be specified for a nested table expression and a table function. v If a single table or view is identified. v The exposed names must be unique. which are defined in the CREATE TABLE.from-clause A table-reference specifies an intermediate result table. view. at least one specification should be followed by a correlation-name. If a column list is specified. v A fullselect in parentheses in a WITH clause is called a nested table expression. view-name. see “joined-table” on page 340. the intermediate result table is the result of one or more join operations. In general. An algorithm called function resolution. there must be a name in the column list for each column in the table or view and for each result column in the nested-table-expression or table-function.40 If a nested table expression is specified. A nested table expression is also called a derived table. the result table is the result of that nested table expression. The columns of the result do not need unique names. or table function must use the exposed name. or a view-name that is not followed by a correlation-name. must resolve to a table function that exists at the current server. but a column with a non-unique name cannot be explicitly referenced. An exposed name is: v A correlation-name v A table-name or view-name that is not followed by a correlation-name | | | | | | | | | | Any qualified reference to a column for a table. 338 DB2 UDB for iSeries SQL Reference V5R2 . the intermediate result table is the set of rows returned by the table function. the column names for a table function are those specified on the RETURNS clause of the CREATE FUNCTION statement. If the same table name or view name is specified twice. nested-table-expression or table-function. nested table expression.

Otherwise.SALARY) AS AVGSAL.c3 = z.DEPTNO = E. z. (SELECT AVG(E.EMPCOUNT FROM DEPARTMENT D. D.COUNT (*) AS EMPCOUNT FROM EMPLOYEE E WHERE E.WORKDEPT = (SELECT X.c1. Example 1: The following example is valid: SELECT D. only references to higher levels in the hierarchy of subqueries is allowed. TABLE(tf3 (t.c1. z.DEPTNO.WORKDEPT = D. t WHERE t.c2 is for a table that is to the right of the table function in the FROM clause: SELECT t.AVGSAL. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Correlated References in table-references: Correlated references can be used in nested table expressions. EMPINFO.DEPTNO ) AS EMPINFO Example 2: The following example of a table function is valid: SELECT t.DEPTNO in the WHERE clause of the nested-table-expression attempts to reference a table that is outside the hierarchy of subqueries: SELECT D.c3 = z.c4 The following example is not valid because the reference to t. EMPINFO.c5 FROM TABLE(tf6 (t.DEPTNO FROM DEPARTMENT X WHERE X.WORKDEPT ) ) AS EMPINFO The following example is not valid because the reference to D.c5 FROM t.EMPCOUNT FROM DEPARTMENT D. Queries 339 . (SELECT AVG(E.c2 ) ) AS z. For more information see “Column Name Qualifiers to Avoid Ambiguity” on page 111 A table function can contain one or more correlated references to other tables in the same FROM clause if the referenced tables precede the reference in the left-to-right order of the tables in the FROM clause. D.DEPTNAME. The basic rule that applies is that the correlated reference must be from a table-reference at a higher level in the hierarchy of subqueries.from-clause name which must be specified.c4 Chapter 4. EMPINFO. A nested table expression can be used: v In place of a view to avoid creating the view (when general use of the view is not required) v When the desired result table is based on host variables.SALARY) AS AVGSAL.AVGSAL.c2 ) ) AS z WHERE t. The scope of this correlation name is the same as correlation names for other table or view names in the FROM clause.COUNT (*) AS EMPCOUNT FROM EMPLOYEE E WHERE E. EMPINFO.DEPTNO.DEPTNAME.

v Right outer. v Right exception. LEFT OUTER. outer.C1 LEFT JOIN TB3 LEFT JOIN TB4 ON TB3. For example: TB1 LEFT JOIN TB2 ON TB1. INNER is implicit. RIGHT OUTER. Includes only the rows from the left table that were missing from the inner join.C1 An inner join combines each row of the left table with every row of the right table keeping only the rows where the join-condition is true. or EXISTS subquery. Outer joins include the rows produced by the inner join as well as the missing rows. The order of processing for joins is generally from left to right. Includes only the rows from the right table that were missing from the inner join. v Left exception. Includes the rows from the right table that were missing from the inner join. IN predicate with a subselect.C1=TB4. A joined table can be used in any context in which any form of the SELECT statement is used.C1 ON TB1.C1=TB3. | | 340 DB2 UDB for iSeries SQL Reference V5R2 . or exception join.C1=TB2. LEFT EXCEPTION. cross. but based on the position of the required join-condition. Includes the rows from the left table that were missing from the inner join. RIGHT EXCEPTION or CROSS to its operands.from-clause joined-table INNER table-reference OUTER LEFT RIGHT LEFT EXCEPTION RIGHT CROSS JOIN table-reference ( joined-table ) JOIN table-reference ON join-condition A joined-table specifies an intermediate result table that is the result of either an inner. the result table may be missing rows of from either or both of the joined tables.C1) ON TB1. Join Condition: The join-condition is a search-condition that must conform to these rules: v It cannot contain a quantified subquery. If a join-operator is not specified. The order in which multiple joins are performed can affect the result.C1) LEFT JOIN (TB3 LEFT JOIN TB4 ON TB3. Thus. It can contain basic predicate subqueries and scalar-subselects. Exception joins include only the missing rows.C1=TB2. depending on the type of outer join. Joins can be nested within other joins. depending on the type of exception join as follows: v Left outer.C1 is the same as (TB1 LEFT JOIN TB2 ON TB1. The table is derived by applying one of the join operators: INNER.C1=TB4. Parentheses are recommended to make the order of nested joins more readable. A view or a cursor is read-only if its SELECT statement includes a joined table.C1=TB3.

The null row of a table consists of a null value for each column of the table. for each unpaired row of T1. a row in the result consists of the values of that row of T1 concatenated with the values of that row of T2. CROSS JOIN is also known as cartesian product. For all possible combinations of rows of T1 and T2. RIGHT JOIN or RIGHT OUTER JOIN The result of T1 RIGHT OUTER JOIN T2 consists of their paired rows and. All columns derived from T1 allow null values. CROSS JOIN The result of T1 CROSS JOIN T2 consists of each row of T1 paired with each row of T2. a row of T1 is paired with a row of T2 if the join-condition is true. Using the INNER JOIN syntax with a join-condition will produce the same result as specifying the join by listing two tables in the FROM clause separated by commas and using the where-clause to provide the condition. All columns derived from T1 allow null values. where T1 and T2 are the left and right operand tables of the JOIN operator of the join-condition. In the case of OUTER joins. All columns derived from T2 allow null values. LEFT EXCEPTION JOIN and EXCEPTION JOIN The result of T1 LEFT EXCEPTION JOIN T2 consists only of each unpaired row of T1. INNER JOIN or JOIN The result of T1 INNER JOIN T2 consists of their paired rows. the concatenation of that row with the null row of T1. RIGHT EXCEPTION JOIN The result of T1 RIGHT EXCEPTION JOIN T2 consists only of each unpaired row of T2. the execution might involve the generation of a null row. regardless of whether the columns allow null values. the concatenation of that row with the null row of T1. column references in an expression of the join-condition are resolved using the rules for resolution of column name qualifiers specified in “Column Names” on page 109 before any rules about which tables the columns must belong to are applied.from-clause v Each column name must unambiguously identify a column in one of the tables in the from-clause. the concatenation of that row with the null row of T2. For any type of join. Chapter 4. Join Operations: A join-condition specifies pairings of T1 and T2. for each unpaired row of T2. All columns derived from T2 allow null values. When a row of T1 is joined with a row of T2. LEFT JOIN or LEFT OUTER JOIN The result of T1 LEFT OUTER JOIN T2 consists of their paired rows and. the concatenation of that row with the null row of T2. Queries 341 . v Column functions cannot be used in the expression.

If a sort sequence other than *HEX is in effect when the statement that contains the WHERE clause is executed and if the search-condition contains predicates that have SBCS. A subquery with no correlated reference is typically executed just once. The weighted values are derived by applying the sort sequence to the operands of the predicate. The search-condition must conform to the following rules: v Each column-name must unambiguously identify a column of R or be a correlated reference. view. common table expression. R is the result of the FROM clause of the statement. or nested table expression identified in an outer subselect. Any subquery in the search-condition is effectively executed for each row of R and the results are used in the application of the search-condition to the given row of R. or UCS-2 data. A column-name is a correlated reference if it identifies a column of a table. A subquery is executed for each row of R if it includes a correlated reference to a column of R. 342 DB2 UDB for iSeries SQL Reference V5R2 . v A column function must not be specified unless the WHERE clause is specified in a subquery of a HAVING clause and the argument of the function is a correlated reference to a group. mixed. then the comparison for those predicates is done using weighted values.where-clause where-clause WHERE search-condition The WHERE clause specifies an intermediate result table that consists of those rows of R for which the search-condition is true.

Each column name included in a grouping-expression must unambiguously identify a column of R. Because every row of a group contains the same value of any grouping-expression. but the value for a group is chosen arbitrarily from the available set of values. a grouping-expression of SALARY*.10 but will not match HAVING . the rows are placed into groups using the weighted Chapter 4. If a sort sequence other than *HEX is in effect when the statement that contains the GROUP BY clause is executed. all null values for a grouping-expression are considered equal. NODENAME. or the RRN.group-by-clause group-by-clause . The grouping-expression specified in these clauses must exactly match the grouping-expression in the GROUP BY clause. The result of the GROUP BY clause is a set of groups of rows. Thus. the reference specifies only one value for each group. In that case. LOB and DataLink columns cannot be used in a grouping-expression. R is the result of the previous clause of the subselect. or NODENUMBER functions. In each case. the actual length of the result value is unpredictable. GROUP BY grouping-expression The GROUP BY clause specifies an intermediate result table that consists of a grouping of the rows of R. PARTITION. in the SELECT clause. all values of each grouping-expression are equal.10)+100 If the grouping-expression contains varying-length strings with trailing blanks. grouping-expressions can be used in a search condition in a HAVING clause. The length attribute of each grouping-expression must not be more than 2000.10 will match the expression in a having-clause of HAVING SALARY*. For grouping. A grouping-expression cannot include a function that is non-deterministic. and all rows with the same set of values of the grouping-expressions are in the same group. or 1999 if the expression is nullable. the values in the group can differ in the number of trailing blanks and may not all have the same length. Queries 343 . For example. except that blanks are not significant. a reference to the grouping-expression still specifies only one value for each group. A grouping-expression is an expression used in defining the grouping of R. or in a sort-key-expression of an ORDER BY clause (see “order-by-clause” on page 353 for details). In each group of more than one row.10 *SALARY or HAVING (SALARY*. where n is the number of grouping-expressions specified that allow nulls. The number of grouping-expressions must not exceed 120 and the sum of their length attributes must not exceed 2000−n bytes.

The weighted values are derived by applying the sort sequence to the SBCS data grouping-expressions. and to UCS-2 data grouping-expressions. to the SBCS data of mixed data grouping-expressions. 344 DB2 UDB for iSeries SQL Reference V5R2 .group-by-clause values.

common table expression. and NODENUMBER functions cannot be specified in the HAVING clause unless it is within a column function. If a sort sequence other than *HEX is in effect when the statement that contains the HAVING clause is executed and if the search-condition contains predicates that have SBCS. except for any function whose argument is a correlated reference. If this clause is not GROUP BY. mixed. NODENAME. For an illustration of the difference. the subquery is executed for each group only if it contains a correlated reference. The weighted values are derived by applying the sort sequence to the operands in the predicate. A column-name is a correlated reference if it identifies a column of a table. any column name in the select list must appear within a column function. The RRN. v Be specified within a column function. v Be a correlated reference. When HAVING is used without GROUP BY. see examples 6 and 7 under “Examples of a subselect” on page 346.having-clause having-clause HAVING search-condition The HAVING clause specifies an intermediate result table that consists of those groups of R for which the search-condition is true. and the results used in applying the search condition. the comparison for those predicates is done using weighted values. or nested table expression identified in an outer subselect. Chapter 4. In actuality. the subquery can be thought of as being executed each time the search condition is applied to a group of R. See ″Functions″ in Chapter 3 for restrictions that apply to the use of column functions. A group of R to which the search condition is applied supplies the argument for each column function in the search condition. or UCS-2 data. PARTITION. A correlated reference to a group of R must either identify a grouping column or be contained within a column function. If the search condition contains a subquery. view. R is the result of the previous clause of the subselect. Queries 345 . Each expression that contains a column-name in the search condition must do one of the following: v Unambiguously identify a grouping expression of R. R is considered a single group with no grouping expressions.

SELECT EMPNO. SELECT JOB. select all the columns from the EMPPROJACT table and add the employee’s surname (LASTNAME) from the EMPLOYEE table to each row of the result.*. department number (WORKDEPT in the EMPLOYEE table and DEPTNO in the DEPARTMENT table) and department name (DEPTNAME) of all employees who were born (BIRTHDATE) earlier than 1930. MIN(SALARY). DEPTNAME FROM EMPLOYEE. WORKDEPT. (Employee department numbers are shown in the EMPLOYEE table. EMPLOYEE WHERE EMPPROJACT. select the employee number (EMPNO).) SELECT * FROM EMPPROJACT WHERE EMPNO IN (SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT = ’E11’) Example 6 From the EMPLOYEE table.EMPNO = EMPLOYEE. LASTNAME. SELECT EMPPROJACT. but only for groups with more than one row and with a maximum salary greater than or equal to 27000. WORKDEPT. MAX(SALARY) FROM EMPLOYEE GROUP BY JOB HAVING COUNT(*) > 1 AND MAX(SALARY) >= 27000 Example 5 Select all the rows of EMPPROJACT table for employees (EMPNO) in department (WORKDEPT) ‘E11’. DEPTNAME FROM EMPLOYEE INNER JOIN DEPARTMENT ON WORKDEPT = DEPTNO WHERE YEAR(BIRTHDATE) < 1930 Example 4 Select the job (JOB) and the minimum and maximum salaries (SALARY) for each group of rows with the same job code in the EMPLOYEE table. LASTNAME. LASTNAME FROM EMPPROJACT. select the department number (WORKDEPT) and maximum departmental salary (SALARY) for all departments whose maximum salary is less than the average salary for all employees. employee surname (LASTNAME).EMPNO Example 3 Join the EMPLOYEE and DEPARTMENT tables. DEPARTMENT WHERE WORKDEPT = DEPTNO AND YEAR(BIRTHDATE) < 1930 This subselect could also be written as follows: SELECT EMPNO.having-clause Examples of a subselect Example 1 Select all columns and rows from the EMPLOYEE table. SELECT * FROM EMPLOYEE Example 2 Join the EMPPROJACT and EMPLOYEE tables. 346 DB2 UDB for iSeries SQL Reference V5R2 .

select all of the employees and their project numbers. SELECT WORKDEPT. the subquery in the HAVING clause would need to be executed for each group. Example 7 Using the EMPLOYEE table. SELECT EMPLOYEE.having-clause SELECT WORKDEPT.EMPNO Any employee in the EMPLOYEE table that does not have a project number in the EMPPROJACT table will return one row in the result table containing the EMPNO value and the null value in the PROJNO column. MAX(SALARY) FROM EMPLOYEE EMP_COR GROUP BY WORKDEPT HAVING MAX(SALARY) < (SELECT AVG(SALARY) FROM EMPLOYEE WHERE NOT WORKDEPT = EMP_COR.WORKDEPT) In contrast to example 6. PROJNO FROM EMPLOYEE LEFT OUTER JOIN EMPPROJACT ON EMPLOYEE. Queries 347 . MAX(SALARY) FROM EMPLOYEE GROUP BY WORKDEPT HAVING MAX(SALARY) < (SELECT AVG(SALARY) FROM EMPLOYEE) The subquery in the HAVING clause would only be executed once in this example.EMPNO. Return even those employees that do not have a project number currently assigned.EMPNO = EMPPROJACT. Chapter 4. select the department number (WORKDEPT) and maximum departmental salary (SALARY) for all departments whose maximum salary is less than the average salary in all other departments. Example 8 Join the EMPLOYEE and EMPPROJACT tables.

(For determining duplicates. with duplicate rows eliminated.) If a sort sequence other than *HEX is in effect when the statement that contains the UNION keyword is executed and if the result tables contain columns that have SBCS. two null values are considered equal. a subquery can be used in a search condition. If the nth column of R1 and the nth column of R2 do not have the same names. In either case. If UNION is specified without the ALL option. operations are performed in left-to-right order. Both UNION and UNION ALL are associative operations. the result is the set of all rows in either R1 or R2. UCS-2. However. or mixed data. A fullselect specifies a result table. the result of the fullselect is the result of the specified subselect. the comparison for those columns is done using weighted values. however. A fullselect used that is enclosed in parenthesis is called a subquery. UNION DISTINCT or UNION ALL Derives a result table by combining two other result tables (R1 and R2). when UNION and UNION ALL are used in the same statement. Rules for Columns R1 and R2 must have the same number of columns. 348 DB2 UDB for iSeries SQL Reference V5R2 . Two rows are duplicates if each value in the first is equal to the corresponding value of the second. For example. If UNION is not used. When the order is not specified by parentheses. each row of the UNION table is either a row from R1 or a row from R2. If the nth column of R1 and the nth column of R2 have the same result column name. then the nth column of the result table has the result column name. If UNION ALL is specified. The weighted values are derived by applying the sort sequence to each value. Operations within parenthesis are performed first. Character-string values are not compatible with datetime values. and the data type of the nth column of R1 must be compatible with the data type of the nth column of R2. then the result column is unnamed. the result consists of all rows in R1 and R2.fullselect fullselect subselect (fullselect) UNION DISTINCT ALL subselect (fullselect) The fullselect is a component of the select-statement and the CREATE VIEW statement. the result depends on the order in which the operations are performed.

For more information see “Rules for Result Data Types” on page 94. Queries 349 . The attributes of the result columns are determined using the rules for result columns.fullselect The nth column of the result of UNION and UNION ALL is derived from the nth columns of R1 and R2. Chapter 4. no column can be a LOB or DATALINK column. If UNION is specified.

SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT LIKE ’E%’ UNION SELECT EMPNO FROM EMPPROJACT WHERE PROJNO IN(’MA2100’. ’MA2112’) Example 3 Make the same query as in example 2. SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT LIKE ’E%’ UNION ALL SELECT EMPNO FROM EMPPROJACT WHERE PROJNO IN(’MA2100’. ’MA2112’) Example 4 Make the same query as in example 2. Unlike the result from example 2. SELECT EMPNO. 'MA2110'.fullselect Examples of a fullselect Example 1 Select all columns and rows from the EMPLOYEE table. ’empprojact’ FROM EMPPROJACT WHERE PROJNO IN(’MA2100’. only use UNION ALL so that no duplicate rows are eliminated. SELECT * FROM EMPLOYEE Example 2 List the employee numbers (EMPNO) of all employees in the EMPLOYEE table whose department number (WORKDEPT) either begins with 'E' or who are assigned to projects in the EMPPROJACT table whose project number (PROJNO) equals 'MA2100'. ’MA2112’) 350 DB2 UDB for iSeries SQL Reference V5R2 . ’MA2110’. this query may return the same EMPNO more than once. ’emp’ FROM EMPLOYEE WHERE WORKDEPT LIKE ’E%’ UNION SELECT EMPNO. and. ″tag″ the rows from the EMPLOYEE table with ’emp’ and the rows from the EMPPROJACT table with ’empprojact’. ’MA2110’. in addition. identifying which table it came from by the associated ″tag″. or 'MA2112'. ’MA2110’.

select-statement select-statement fullselect . or directly specified in an SQLJ assignment clause. WITH common-table-expression order-by-clause (1) (2) fetch-first-clause update-clause read-only-clause optimize-clause isolation-clause Notes: 1 2 The update-clause and read-only-clause cannot both be specified in the same select-statement. It can also be issued interactively. Each clause may be specified only once. prepared and then referenced in a DECLARE CURSOR statement. In any case. causing a result table to be displayed at your work station. the table specified by a select-statement is the result of the fullselect. Queries 351 . The select-statement is the form of a query that can be directly specified in a DECLARE CURSOR statement. Chapter 4. using the interactive facility (STRSQL command).

the common table expression is a recursive table expression. If these column names are not specified. the names are derived from the select list of the subselect used to define the common table expression. A table-name of a common table expression overrides any existing table. 352 DB2 UDB for iSeries SQL Reference V5R2 .common-table-expression common-table-expression table-name . Each column-name must be unique and unqualified. The table-name must be unqualified. A common table expression table-name can be specified as a table name in any FROM clause throughout the fullselect. | | A common-table-expression is also optional prior to the fullselect in the CREATE VIEW and INSERT statements. If more than one common table expression is defined in the same statement. view. The table-name of a common table expression must be different from any other common table expression table-name in the same statement. ( AS ( fullselect order-by-clause fetch-first-clause column-name ) ) A common-table-expression permits defining a result table with a table-name that can be specified as a table name in any FROM clause of the fullselect that follows. A cyclic reference occurs when two common table expressions dt1 and dt2 are created such that dt1 refers to dt2 and dt2 refers to dt1. Each common table expression specified can also be referenced by name in the FROM clause of subsequent common table expressions. cyclic references between the common table expressions are not permitted. A common-table-expression can be used: v In place of a view to avoid creating the view (when general use of the view is not required and positioned updates or deletes are not used v When the desired result table is based on host variables v When the same result table needs to be shared in a fullselect | | | If a fullselect of a common table expression contains a reference to itself in a FROM clause. or alias (in the catalog) with the same qualified name. | | | | If a list of columns is specified. it must consist of as many names as there are columns in the result table of the fullselect. Multiple common table expressions can be specified following the single WITH keyword. Recursive common table expressions are not supported in DB2 UDB for iSeries.

order-by-clause order-by-clause . If the fullselect includes a UNION operator. the rows are ordered by the values of the first identified sort specification. If a sort sequence other than *HEX is in effect when the statement that contains the ORDER BY clause is executed and if the ORDER BY clause involves sort specifications that have SBCS. If the fullselect includes a UNION or UNION ALL. A named column in the select list may be identified by a sort-key that is a integer or a column-name. If more than one sort specification is identified. and so on. the comparison for those sort specifications is done using weighted values. or mixed data. the rows of the result table have an arbitrary order. | | | | | | | | | column-name Must unambiguously identify a column of the result table. The number of sort-keys must not exceed 10000-n and the sum of their length attributes must not exceed 10000-n bytes (where n is the number of sort-keys specified that allow nulls). Ordering is performed in accordance with the comparison rules described in Chapter 2. If your ordering specification does not determine a complete ordering. The column-name may also identify a column name of a table. If the ORDER BY clause is not specified. rows with duplicate values of the last identified sort-key have an arbitrary order. “Names of result columns” on page 335 defines when result columns are unnamed. Queries 353 . the rows are ordered by the values of that specification. or nested-table-expression identified in the FROM clause if the query is a subselect. If a single sort specification (one sort-key with associated ascending or descending ordering specification) is identified. see “fullselect” on page 348 for the rules on named columns in a fullselect. the column name cannot be qualified. Chapter 4. in some cases by a sort-key-expression that matches the expression in the select list (see details of sort-key-expression). An unnamed column in the select list may be identified by a integer or. view. UCS-2. The weighted values are derived by applying the sort sequence to the values of the sort specifications. See “Column Name Qualifiers to Avoid Ambiguity” on page 111 for more information. then by the values of the second identified sort specification. The rules for unambiguous column references are the same as in the other clauses of the fullselect. The null value is higher than all other values. The column must not be a LOB or DATALINK column. ASC ORDER BY sort-key DESC sort-key: column-name integer sort-key-expression The ORDER BY clause specifies an ordering of the rows of the result table.

ASC Uses the values of the column in ascending order. If the subselect is grouped. DESC Uses the values of the column in descending order. The integer n identifies the nth column of the result table. The result of the sort-key-expression must not be a LOB or DATALINK. integer Must be greater than 0 and not greater than the number of columns in the result table. The identified column must not be a LOB or DATALINK column. sort-key-expression An expression that is not simply a column name or an unsigned integer constant. or NODENUMBER if the fullselect includes a UNION or UNION ALL. NODENAME. the sort-key-expression can be an expression in the select list of the subselect or can include a grouping-expression from the GROUP BY clause of the subselect.order-by-clause | | An error occurs if the subselect includes a column function in the select list and the column-name is not a grouping-expression. 354 DB2 UDB for iSeries SQL Reference V5R2 . | | | The sort-key-expression cannot contain RRN. The query to which ordering is applied must be a subselect to use this form of sort-key. PARTITION. This is the default.

fetch-first-clause fetch-first-clause 1 FETCH FIRST integer ROW ROWS ONLY The fetch-first-clause sets a maximum number of rows that can be retrieved. The database manager will cease processing the query once it has determined the first integer rows. The fetch-first-clause cannot appear in a statement containing an UPDATE clause. If both the order-by-clause and fetch-first-clause are specified. An attempt to fetch beyond integer rows is handled the same way as normal end of data (SQLSTATE 02000). It lets the database manager know that only integer rows should be made available to be retrieved. Limiting the result table to the first integer rows can improve performance. Queries 355 . The value of integer must be a positive integer (not zero). Chapter 4. regardless of how many rows there might be in the result table when this clause is not specified. Specification of the fetch-first-clause in a select-statement makes the result table read-only. A read-only result table must not be referred to in an UPDATE or DELETE statement. the FETCH FIRST operation is always performed on the ordered data.

The clause must not be specified if the result table of the fullselect is read-only. The FOR UPDATE OF clause must not be specified if the result table of the fullselect is read-only (for more information see “DECLARE CURSOR” on page 577). Positioned UPDATE statements identifying the cursor associated with a select-statement can update all updateable columns. if the FOR READ ONLY clause is used.update-clause update-clause FOR UPDATE . 356 DB2 UDB for iSeries SQL Reference V5R2 . all updateable columns of the table or view identified in the first FROM clause of the fullselect are included. If the UPDATE clause is specified without column names. OF column-name The UPDATE clause identifies the columns that can be updated in a subsequent positioned UPDATE statement. Each column-name must be unqualified and must identify a column of the table or view identified in the first FROM clause of the fullselect. or if the SCROLL keyword is specified without the DYNAMIC keyword on the DECLARE CURSOR statement. if: v The select-statement does not contain one of the following: – An UPDATE clause – A FOR READ ONLY clause – An ORDER BY clause v The DECLARE CURSOR statement does not contain a SCROLL keyword without the DYNAMIC keyword.

For result tables in which updates and deletes are allowed. in programs that contain dynamic SQL statements without the FOR READ ONLY or ORDER BY clause. (For example. the database manager might open cursors that have not specified SCROLL without the DYNAMIC keyword as if the UPDATE clause was specified. For example. A read-only result table must not be referred to in an UPDATE or DELETE statement. Queries 357 .read-only-clause read-only-clause FOR READ ONLY The FOR READ ONLY or FOR FETCH ONLY clause indicates that the result table is read-only and therefore the cursor cannot be used for Positioned UPDATE and DELETE statements. whether it is read-only by nature or specified as FOR READ ONLY. but the specification has no effect. Chapter 4. Syntax Alternatives: FOR FETCH ONLY can be specified in place of FOR READ ONLY. a table based on a read-only view). Some result tables are read-only by nature. specifying FOR READ ONLY can possibly improve the performance of FETCH operations by allowing the database manager to do blocking and avoid exclusive locks. FOR READ ONLY can still be specified for such tables.

optimize-clause optimize-clause OPTIMIZE FOR integer ALL ROW ROWS The optimize-clause tells the database manager to assume that the program does not intend to retrieve more than integer rows from the result table. Any number of rows can be fetched. or with the keyword ALL. 358 DB2 UDB for iSeries SQL Reference V5R2 . the database manager assumes that all rows of the result table are to be retrieved. but performance can possibly degrade after integer fetches. The database manager will optimize the query based on the specified number of rows. Without this clause. Optimizing for integer rows can improve performance. The clause does not change the result table or the order in which the rows are fetched. The value of integer must be a positive integer (not zero).

read locks are released when the next row is read. The KEEP LOCKS clause is only allowed on an SQL SELECT. v RR . or DECLARE CURSOR statement.Repeatable Read v RS . v The keyword CHG can be used as a synonym for UR. the locks will be held until the completion of the SQL statement. It is not allowed on updateable cursors. Keyword Synonyms: The following keywords are synonyms supported for compatibility to prior releases. Chapter 4. Queries 359 .Cursor Stability The KEEP LOCKS clause specifies that any read locks acquired will be held for a longer duration. v UR . SELECT INTO. Normally. the locks will be held until the cursor is closed or until a COMMIT or ROLLBACK statement is executed. v The keyword ALL can be used as a synonym for RS. See “Isolation Level” on page 21 for a description of how the default is determined.Read Stability v CS . Otherwise.Uncommitted Read v NC .isolation-clause isolation-clause WITH NC UR CS KEEP LOCKS RS RR The isolation-clause specifies an isolation level at which the select statement is executed. the default isolation is used with the exception of a default isolation level of uncommitted read. These keywords are non-standard and should not be used: v The keyword NONE can be used as a synonym for NC.No Commit If isolation-clause is not specified. If the isolation clause is associated with a cursor.

the program can retrieve more than 2 rows from the result table. Example 5 Select items from a table with an isolation level of Repeatable Read (RS). list the average salary of the department with the highest average salary. SELECT NAME. AVG(SALARY) FROM EMPLOYEE GROUP BY WORKDEPT ORDER BY AVGSAL Example 4 Declare a cursor named UP_CUR.isolation-clause Examples of a select-statement Example 1 Select all columns and rows from the EMPLOYEE table. 360 DB2 UDB for iSeries SQL Reference V5R2 . PRSTDATE. PRENDATE OPTIMIZE FOR 2 ROWS . However. SELECT WORKDEPT. that updates the start date (PRSTDATE) and the end date (PRENDATE) columns in the PROJECT table. PRENDATE FROM PROJECT ORDER BY PRENDATE DESC Example 3 Select the department number (WORKDEPT) and average departmental salary (SALARY) for all departments in the EMPLOYEE table. Also. EXEC SQL DECLARE UP_CUR CURSOR FOR SELECT PROJNO. Order the result table by the end date with the most recent dates appearing first. PRSTDATE. start date (PRSTDATE). and end date (PRENDATE) from the PROJECT table. SELECT PROJNAME. SALARY FROM PAYROLL WHERE DEPT = 704 WITH RS Example 6 This example names the expression SAL+BONUS+COMM as TOTAL_PAY: SELECT SALARY+BONUS+COMM AS TOTAL_PAY FROM EMPLOYEE ORDER BY TOTAL_PAY Example 7 Determine the employee number and salary of sales representatives along with the average salary and head count of their departments. when more than 2 rows are retrieved. The declaration specifies that the access path for the query be optimized for the retrieval of a maximum of 2 rows. to be used in a C program. PRENDATE FROM PROJECT FOR UPDATE OF PRSTDATE. The program must receive both of these values together with the project number (PROJNO) value for each row. SELECT * FROM EMPLOYEE Example 2 Select the project name (PROJNAME). performance could possibly degrade. Even so. Arrange the result table in ascending order by average departmental salary.

WORKDEPT).EMPNO. DINFO. Queries 361 . DINFO. DINFOMAX WHERE THIS_EMP.isolation-clause Using a common table expression for this case saves the overhead of creating the DINFO view as a regular view. DINFOMAX AS (SELECT MAX(AVGSALARY) AS AVGMAX FROM DINFO) SELECT THIS_EMP. EMPCOUNT) AS (SELECT OTHERS.AVGMAX FROM EMPLOYEE THIS_EMP.JOB = ’SALESREP’ AND THIS_EMP.SALARY). DINFOMAX. COUNT(*) FROM EMPLOYEE OTHERS GROUP BY OTHERS.EMPCOUNT. DINFO.SALARY. THIS_EMP.WORKDEPT. Because of the context of the rest of the fullselect.WORKDEPT = DINFO. AVG(OTHERS. AVGSALARY. WITH DINFO (DEPTNO.DEPTNO Chapter 4.AVGSALARY. only the rows for the department of the sales representatives need to be considered by the view.

isolation-clause 362 DB2 UDB for iSeries SQL Reference V5R2 .

function. parameter. procedure. column. type or view Creates an alias Creates a distinct type Creates a user-defined function Creates an external scalar function Creates an external table function Creates a user-defined function based on another existing scalar or column function Creates an SQL scalar function Creates an SQL table function Creates an index on a table Page 372 405 CREATE ALIAS CREATE DISTINCT TYPE CREATE FUNCTION CREATE FUNCTION (External Scalar) 426 429 436 440 456 470 479 488 497 501 502 513 522 526 557 570 630 653 656 663 665 | | CREATE FUNCTION (External Table) CREATE FUNCTION (Sourced) CREATE FUNCTION (SQL Scalar) CREATE FUNCTION (SQL Table) CREATE INDEX CREATE PROCEDURE Creates a procedure. table. package. function. Statements This chapter contains syntax diagrams. (SQL) CREATE SCHEMA CREATE TABLE CREATE TRIGGER CREATE VIEW DROP GRANT (Distinct Type Privileges) GRANT (Function or Procedure Privileges) GRANT (Package Privileges) GRANT (Table Privileges) Creates a schema and a set of objects in that schema Creates a table Creates a trigger Creates a view of one or more tables or views Drops an alias. table. trigger. 1998. index. schema. and examples of the use of the SQL statements listed in the following table. 2002 363 .Chapter 5. rules. CREATE PROCEDURE Creates an external procedure. type. (External) CREATE PROCEDURE Creates an SQL procedure. or view Grants privileges on a distinct type Grants privileges on a function or procedure Grants privileges on a package Grants privileges on a table or view © Copyright IBM Corp. Table 33. SQL Schema Statements SQL Statement ALTER TABLE COMMENT Description Alters the description of a table Replaces or adds a comment to the description of an alias. index. package. procedure. semantic descriptions.

Specifies a result table of no more than one row and assigns the values to host variables.Statements Table 33. view. package. or view Renames a table. SQL Schema Statements (continued) SQL Statement LABEL RENAME Description Replaces or adds a label on the description of an alias. Page 682 704 707 709 716 718 REVOKE (Distinct Type Revokes the privilege to use a distinct type Privileges) REVOKE (Function or Procedure Privileges) REVOKE (Package Privileges) REVOKE (Table Privileges) Revokes privileges on a function or procedure Revokes the privilege to execute statements in a package Revokes privileges on a table or view Table 34. SQL Data Change Statements SQL Statement DELETE INSERT UPDATE Description Deletes one or more rows from a table Inserts one or more rows into a table Updates the values of one or more columns in one or more rows of a table Page 613 674 763 Table 35. can also assign values from one or more rows of the result table to host variables Page Table 34 403 577 646 FREE LOCATOR Removes the association between a LOB locator 652 variable and its value Allows a LOB locator variable to retain its 670 association with a value beyond a unit of work Either prevents concurrent processes from changing a table or prevents concurrent processes from using a table Opens a cursor Executes a query Assigns values to host variables Assigns values to a transition variable Assigns values to a host variable Provides a method to invoke a user-defined function from a trigger. SQL Data Statements SQL Statement Description All SQL Data Change statements CLOSE DECLARE CURSOR FETCH Closes a cursor Defines an SQL cursor Positions a cursor on a row of the result table. column. table. 685 | | HOLD LOCATOR LOCK TABLE OPEN SELECT SELECT INTO 687 727 728 759 761 772 774 | | SET transition-variable SET variable VALUES VALUES INTO 364 DB2 UDB for iSeries SQL Reference V5R2 . or index.

SQL Session Statements SQL Statement Description Defines a declared global temporary table Page 584 | | DECLARE GLOBAL TEMPORARY TABLE SET PATH Assigns a value to the CURRENT PATH special 748 register Assigns a value to the CURRENT SCHEMA special register 754 | | SET SCHEMA Table 40. SQL Transaction Statements SQL Statement COMMIT Description Ends a unit of work and commits the database changes made by that unit of work Page 414 703 721 725 756 | RELEASE SAVEPOINT Releases a savepoint within a unit of work ROLLBACK Ends a unit of work and backs out the database changes made by that unit of work Sets a savepoint within a unit of work Changes the isolation level for the current unit of work | SAVEPOINT SET TRANSACTION Table 37. Statements 365 .Statements Table 36. SQL Embedded Host Language Statements SQL Statement BEGIN DECLARE SECTION Description Marks the beginning of an SQL declare section Page 395 Chapter 5. SQL Dynamic Statements SQL Statement DESCRIBE DESCRIBE TABLE EXECUTE EXECUTE IMMEDIATE PREPARE Description Describes the result columns of a prepared statement Obtains information about a table or view Executes a prepared SQL statement Prepares and executes an SQL statement Prepares an SQL statement for execution Page 619 624 641 644 692 Table 39. SQL Connection Statements SQL Statement CONNECT (Type 1) CONNECT (Type 2) Description Connects to a server and establishes the rules for remote unit of work Connects to a server and establishes the rules for application-directed distributed unit of work Immediately ends one or more connections Page 417 422 DISCONNECT 628 701 731 RELEASE (Connection) Places one or more connections in the release-pending state SET CONNECTION Establishes the server of the process by identifying one of its existing connections Table 38.

SQL Control Statements SQL Statement assignment-statement CALL CASE compound-statement FOR GET DIAGNOSTICS GOTO IF ITERATE LEAVE LOOP REPEAT RESIGNAL RETURN SIGNAL WHILE Description Assigns a value to an output parameter or to a local variable Calls a procedure Selects an execution path based on multiple conditions Groups other statements together in an SQL routine Executes a statement for each row of a table Obtains information about the previous SQL statement that was executed Page 784 397 788 790 797 799 Branches to a user-defined label within an SQL 802 routine or trigger Provides conditional execution based on the truth value of a condition Causes the flow of control to return to the beginning of a labelled loop 804 806 Continues execution by leaving a block or loop 807 Repeats the execution of a statement Repeats the execution of a statement Resignals an error or warning condition Returns from a routine Signals an error or warning condition Repeats the execution of a statement while a specified condition is true 808 809 811 814 816 819 See also: v “How SQL Statements Are Invoked” on page 367 v “SQL Return Codes” on page 369 366 DB2 UDB for iSeries SQL Reference V5R2 . SQL Embedded Host Language Statements (continued) SQL Statement DECLARE PROCEDURE DECLARE STATEMENT DECLARE VARIABLE END DECLARE SECTION INCLUDE SET RESULT SET SET OPTION WHENEVER Description Defines an external procedure Declares the names used to identify prepared SQL statements Declares a subtype or CCSID other than the default for a host variable Marks the end of an SQL declare section Inserts declarations into a source program Identifies the result sets in a procedure Establishes the options for processing SQL statements Page 599 608 610 640 672 751 734 Defines actions to be taken on the basis of SQL 777 return codes Table 41.Statements Table 40.

This means that a statement within a loop is executed every time the loop is executed. CRTSQLRPG. CRTSQLCPPI. each embedded statement must be preceded by the keyword EXECSQL. A nonexecutable statement can only be embedded in an application program. The Invocation section in the description of each statement tells you which methods can be used. CRTSQLCI. each embedded statement must be preceded by the keywords EXEC and SQL. v In REXX. COBOL FORTRAN. Such statements are said to be embedded in the program. v In Java. and a statement within a conditional construct is executed only when the condition is satisfied. or CRTSQLRPGI commands. Executable statements An executable statement embedded in an application program is executed every time a statement of the host language would be executed if specified in the same place. The Invocation section in the description of each statement indicates whether or not the statement is executable. Statements 367 . CRTSQLCBLI. and RPG. Each embedded statement must be preceded by a keyword (or keywords) to indicate that the statement is an SQL statement: v In C. Embedding a Statement in an Application Program | | | | | | | | | | | | SQL statements can be included in a source program that will be submitted to the precompiler by using the CRTSQLCBL.Statements v “SQL Comments” on page 370 How SQL Statements Are Invoked The SQL statements described in this chapter are classified as executable or nonexecutable. Depending on the statement. PL/I. you can use some or all of these methods. An embedded statement can be placed anywhere in the program where a host language statement is allowed. CRTSQLPLI. each embedded statement must be preceded by the keywords #sql. An embedded statement can contain references to host variables. CRTSQLFTN. An executable statement can be invoked in any of the following ways: v Embedded in an application program v Dynamically prepared and executed v Issued interactively Note: Statements embedded in REXX or processed using RUNSQLSTM are prepared and executed dynamically. A host variable referenced in this way can be used in two ways: v As input (the current value of the host variable is used in the execution of the statement) v As output (the variable is assigned a new value as a result of executing the statement) Chapter 5.

Parameter markers are not allowed in EXECUTE IMMEDIATE. it can be executed several times with different values of host variables.Statements In particular. Alternatively. PL/I. All executable statements should be followed by a test of an SQL return code. In C. that is. When the prepared statement is executed. It can contain parameter markers instead. and acts as a no-operation if placed among executable statements of the application program. The SQL return code should be checked as described above for embedded statements. Therefore. all references to host variables in expressions and predicates are effectively replaced by current values of the variables. See “EXECUTE” on page 641 for rules concerning this replacement. such statements should not be followed by a test of an SQL return code. the statement can be prepared for execution by means of the Statement. the successful or unsuccessful execution of the statement is handled by Java Exceptions. After a statement is prepared. REXX. 368 DB2 UDB for iSeries SQL Reference V5R2 . The precompiler reports any errors encountered in such a statement. the statement is built from some data available to the program (for example. PreparedStatement. See the topic “SQL Return Codes” on page 369 for more information. input from a work station). Static Invocation of a select-statement A select-statement can be included as a part of the (nonexecutable) statement DECLARE CURSOR. Alternatively. the (embedded) statement EXECUTE IMMEDIATE can be used to prepare and execute a statement in one step. and RPG. In general. the parameter markers are effectively replaced by the current values of the host variables specified in the EXECUTE statement. Dynamic Preparation and Execution An application program can dynamically build an SQL statement in the form of a character string placed in a host variable. The statement is never executed. After the cursor is open. the successful or unsuccessful execution of the statement is indicated by the setting of an SQL return code in the SQLCA after the EXECUTE (or EXECUTE IMMEDIATE) statement. In Java. COBOL FORTRAN. and CallableStatement classes. See “PREPARE” on page 692 for rules concerning the parameter markers. Such a statement is executed every time the cursor is opened by means of the (embedded) statement OPEN. The treatment of other references is described individually for each statement. the variables are used as input. In Java. the result table can be retrieved one row at a time by successive executions of the FETCH statement or multiple rows at a time by using the multiple-row FETCH statement. and executed by means of their respective execute() methods. the WHENEVER statement (which is itself nonexecutable) can be used to change the flow of control immediately after the execution of an embedded statement. Nonexecutable statements An embedded nonexecutable statement is processed only by the precompiler. Objects referenced in SQL statements need not exist when the statements are prepared. A statement that is dynamically prepared must not contain references to host variables. The statement can be prepared for execution using the (embedded) statement PREPARE and executed by the (embedded) statement EXECUTE.

Statements 369 . the Start Query Manager (STRQM) command. and the SQL Script support of iSeries Navigator for this facility. neither a stand-alone SQLSTATE or SQLCODE can be provided. DISCONNECT. The statement is then executed every time the cursor is opened by means of the (embedded) statement OPEN. In general. Chapter 5. A statement entered in this way is said to be issued interactively. Interactive Invocation A capability for entering SQL statements from a work station is part of the architecture of the database manager. – A stand-alone integer variable named SQLCODE (SQLCOD in FORTRAN). After the cursor is open. – A stand-alone CHAR(5) (CHAR(6) in C) variable named SQLSTATE (SQLSTA or SQLSTATE in FORTRAN). A stand-alone SQLSTATE should be used to conform with the SQL 1999 Core stamndard. It can instead contain parameter markers. Dynamic Invocation of a select-statement An application program can dynamically build a select-statement in the form of a character string placed in a host variable. FORTRAN. Other products are also available. with the exception of connection management statements (CONNECT. and SET CONNECTION). The SQLCA includes a character-string variable named SQLSTATE (SQLSTT in FORTRAN) and an integer variable named SQLCODE (SQLCOD in FORTRAN) . the statement is built from some data available to the program (for example. and PL/I. the select-statement must not contain references to host variables. Both a stand-alone SQLSTATE and SQLCODE may be provided. because these make sense only in the context of an application program. A statement issued interactively must be an executable statement that does not contain parameter markers or references to host variables. See “PREPARE” on page 692 for rules concerning the parameter markers. COBOL. the result table can be retrieved one row at a time by successive executions of the FETCH statement or multiple rows at a time by using the multiple-row FETCH statement.Statements Used in this way. An SQLCA can be obtained by using the INCLUDE SQLCA statement. The DB2 UDB for iSeries licensed program provides the Start Structured Query Language (STRSQL) command. A stand-alone SQLSTATE or SQLCODE must not be declared in a host structure. If an SQLCA is provided. RELEASE. an application program containing executable SQL statements must provide at least one of the following: – A structure named SQLCA. Used in this way. The parameter markers are effectively replaced by the values of the host variables specified in the OPEN statement. These references are effectively replaced by the values that the variables have at the moment of executing OPEN. See “OPEN” on page 687 for rules concerning this replacement. the select-statement can contain references to host variables. a query obtained from a work station). SQL Return Codes Each host language provides a mechanism for handling SQL return codes: v In C. A statement that cannot be dynamically prepared cannot be issued interactively.

for error conditions. For example. execution was successful with a warning. SQLSTATE Regardless of whether the application program provides an SQLCA or a stand-alone variable. v If SQLCODE = 0 and SQLWARN0 = ’W’. Dynamic SQL statements can include SQL comments. A complete list of SQLSTATE classes and SQLSTATEs associated with each SQLCODE is supplied in the SQL Messages and Codes book in the iSeries Information Center. v In COBOL. no data was found. bracketed comments Bracketed comments are introduced by /* and end with */. The scheme is the same for all database managers and is based on the proposed ISO/ANSI standard. v Simple comments can be started wherever a space is valid (except within a delimiter token or between 'EXEC' and 'SQL'). v If SQLCODE = 100. v If SQLCODE < 0. a FETCH statement returned no data. These rules apply to the use of simple comments: v The two hyphens must be on the same line and must not be separated by a space. v If SQLCODE > 0 and not = 100. Thus. execution was successful with a warning. SQLSTATE provides application programs with common codes for common error conditions. the getSQLState method can be used to get the SQLSTATE and the getErrorCode method can be used to get the SQLCODE. execution was successful. SQLCODE The SQLCODE is also set by the database manager after each SQL statement is executed as follows: v If SQLCODE = 0 and SQLWARN0 is blank. execution was not successful. There are two types of SQL comments: simple comments Simple comments are introduced by two consecutive hyphens. These rules apply to the use of bracketed comments: 370 DB2 UDB for iSeries SQL Reference V5R2 . SQL Comments Static SQL statements can include host language or SQL comments. Furthermore. an SQLCA is provided automatically. application programs can check the execution of SQL statements by testing SQLSTATE instead of SQLCODE. v In REXX and RPG. v Simple comments cannot be continued to the next line. because the cursor was positioned after the last row of the result table. A complete listing of DB2 UDB for iSeries SQLCODEs and their corresponding SQLSTATEs is provided in the SQL Messages and Codes book in the iSeries Information Center.Statements v In Java. SQLSTATE is designed so that application programs can test for specific errors or classes of errors. the hyphens must be preceded by a space. SQLSTATE is also set by the database manager after execution of each SQL statement.

NUMBER AND NAME OF PROJECT -. v Bracketed comments can be continued to the next line. v Bracketed comments can be started wherever a space is valid (except within a delimiter token or between 'EXEC' and 'SQL'). Statements 371 .Statements v The /* must be on the same line and not separated by a space. PROJNAME FROM PROJECT WHERE DEPTNO = ’E21’ AND PRSTAFF > 1 /* PROJECTS WITH MOST SUPPORT PERSONNEL /* NUMBER AND NAME OF PROJECT /* SYSTEMS SUPPORT DEPT CODE */ */ */ Chapter 5. v The */ must be on the same line and not separated by a space. v Bracketed comments can be nested within other bracketed comments.PROJECTS WITH MOST SUPPORT PERSONNEL -. PROJNAME FROM PROJECT WHERE DEPTNO = ’E21’ AND PRSTAFF > 1 -. Example 1: This example shows how to include simple comments in a statement: CREATE VIEW PRJ_MAXPER AS SELECT PROJNO.SYSTEMS SUPPORT DEPT CODE Example 2: This example shows how to include bracketed comments in a statement: CREATE VIEW PRJ_MAXPER AS SELECT PROJNO.

v It was granted the ALTER privilege to the table. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type. 372 DB2 UDB for iSeries SQL Reference V5R2 .ALTER TABLE ALTER TABLE | The ALTER TABLE statement alters the definition of a table. v It was granted the system authorities of either *OBJALTER or *OBJMGT to the table. v It was granted the system authorities of either *OBJREF or *OBJMGT to the table. and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v For the table identified in the statement. v It was granted the USAGE privilege to the distinct type. To define a foreign key. the privileges held by the authorization ID of the statement must include at least one of the following on the parent table: v The REFERENCES privilege or object management authority for the table v The REFERENCES privilege on each column of the specified parent key v Ownership of the table v Administrative authority The authorization ID of the statement has the REFERENCES privilege on a table when one of the following is true: v It is the owner of the table. the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: – The USAGE privilege on the distinct type. It is an executable statement that can be dynamically prepared. – The ALTER privilege on the table. If a distinct type is referenced. and – The system authority *EXECUTE on the library containing the table v Administrative authority The authorization ID of the statement has the ALTER privilege on the table when one of the following is true: v It is the owner of the table. v It was granted the REFERENCES privilege to the table. Invocation This statement can be embedded in an application program or issued interactively.

Chapter 5.ALTER TABLE Syntax COLUMN ALTER TABLE table-name ADD COLUMN ALTER DROP ADD column-alteration CASCADE column-name RESTRICT unique-constraint referential-constraint check-constraint COLUMN CASCADE DROP PRIMARY KEY UNIQUE FOREIGN KEY CHECK CONSTRAINT constraint-name RESTRICT column-definition column-definition: column-name COLUMN FOR system-column-name data-type | (3) default-clause GENERATED ALWAYS GENERATED BY DEFAULT (2) datalink-options NOT NULL column-constraint Notes: (1) identity-options | 1 | 2 3 GENERATED can be specified only if the column has a ROWID data type (or a distinct type that is based on a ROWID data type). The datalink-options can only be specified for DATALINKs and distinct-types sourced on DATALINKs. Statements 373 . or the column is an identity column. The same clause must not be specified more than once.

0 ( integer .ALTER TABLE data-type: built-in-type distinct-type-name built-in-type: | SMALLINT INTEGER INT BIGINT (5.0) DECIMAL DEC NUMERIC ( 52 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( 1 ) CHARACTER CHAR CHARACTER CHAR VARCHAR ( integer ) VARYING ( integer ) allocate-clause ( 1M CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ) ) K M G allocate-clause FOR SBCS DATA FOR MIXED DATA CCSID integer FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer . integer ) ( integer ( 1 ) GRAPHIC ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( CCSID integer ) allocate-clause ) allocate-clause 1M ) ) K M G allocate-clause integer DATE ( 0 ) TIME ( 6 TIMESTAMP ( DATALINK ( ROWID integer ) allocate-clause CCSID integer 200 ) ) allocate-clause: ALLOCATE (integer) 374 DB2 UDB for iSeries SQL Reference V5R2 .

( 1 numeric-constant 1 INCREMENT BY numeric-constant NO MINVALUE MINVALUE numeric-constant NO MAXVALUE MAXVALUE numeric-constant NO CYCLE CYCLE CACHE 20 NO CACHE CACHE integer NO ORDER ORDER START WITH (1) ) datalink-options: LINKTYPE URL NO LINK CONTROL FILE LINK CONTROL file-link-options MODE DB2OPTIONS Notes: 1 Each clause may be specified only once.ALTER TABLE default-clause: WITH DEFAULT constant USER NULL CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP cast-function-name ( constant USER CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP ) identity-options: | AS IDENTITY . Chapter 5. Statements 375 .

Each clause may be specified only once.ALTER TABLE file-link-options: (1) INTEGRITY ALL READ PERMISSION FS READ PERMISSION DB WRITE PERMISSION FS WRITE PERMISSION BLOCKED RECOVERY NO ON UNLINK RESTORE ON UNLINK DELETE column-alteration: (3) column-name SET DATA TYPE data-type default-clause GENERATED ALWAYS GENERATED BY DEFAULT NOT NULL (4) DEFAULT NOT NULL IDENTITY identity-alteration DROP (2) identity-alteration: | SET INCREMENT BY numeric-constant NO MINVALUE MINVALUE numeric-constant NO MAXVALUE MAXVALUE numeric-constant NO CYCLE CYCLE NO CACHE CACHE integer NO ORDER ORDER RESTART WITH numeric-constant Notes: 1 2 3 4 5 All five file-link-options must be specified. Each clause may be specified only once. GENERATED can be specified only if the column has a ROWID data type (or a distinct type that is based on a ROWID data type). Each clause may be specified only once. but they can be specified in any order. or the column is an identity column. (5) 376 DB2 UDB for iSeries SQL Reference V5R2 .

constraint-name (without the CONSTRAINT keyword) may be specified following FOREIGN KEY. (1) FOREIGN KEY CONSTRAINT constraint-name ( column-name ) references-clause references-clause: REFERENCES table-name . The ON DELETE and ON UPDATE clauses may be specified in either order. Statements 377 . check-condition ) Chapter 5.ALTER TABLE column-constraint: PRIMARY KEY UNIQUE references-clause CHECK ( check-condition ) CONSTRAINT constraint-name unique-constraint: . ( column-name ) ON DELETE NO ACTION ON DELETE RESTRICT CASCADE SET NULL SET DEFAULT ON UPDATE NO ACTION ON UPDATE RESTRICT (2) check-constraint: CHECK ( CONSTRAINT constraint-name Notes: 1 2 For compatibility with other products. PRIMARY KEY UNIQUE ( column-name ) CONSTRAINT constraint-name referential-constraint: .

32740. the ordinality of the new column is n+1. If the system-column-name is not specified. the data type of the corresponding column of the parent key must have the same distinct type. data-type Specifies the data type of the column. 378 DB2 UDB for iSeries SQL Reference V5R2 . if a LOB is specified. if a VARCHAR or VARGRAPHIC column is specified. a catalog table. and the column-name is not a valid system-column-name. If the column is to be used in the definition of the foreign key of a referential constraint. Do not use the same name for more than one column-name or system-column-name of the table. Additionally. see “Notes” on page 551. and scale of the source type of the distinct type. If the table has rows. Do not qualify column-name. column-name Names the column to be added to the table. For more information about how system column names are generated. the sum of the byte counts of the columns must not be greater than 3 758 096 383 at the time of insert or update. See “CREATE TABLE” on page 526 for a description of built-in types. built-in-type Specifies a built-in data type. A table can have only one ROWID column. precision and scale of the column are respectively the length. ADD column-definition Adds a column to the table. If a distinct type name is specified without a schema name. unless the column is a ROWID column or an identity column (a column that is defined AS IDENTITY). precision. or a global temporary table. The table-name must identify a table that exists at the current server. The data type can be a built-in data type or a distinct type. A DataLink column with FILE LINK CONTROL cannot be added to a table that is a dependent in a referential constraint with a delete rule of CASCADE. see “Rules for Column Name Generation” on page 554. FOR COLUMN system-column-name Provides an OS/400 name for the column. The length. distinct-type-name Specifies the data type of a column is a distinct type. Do not use the same name for more than one column of the table or for a system-column-name of the table. the distinct type name is resolved by searching the schemas on the SQL path. every value of the column is set to its default value. You cannot add an identity column to a table that already has an identity column. If the table previously had n columns. The value of n+1 must not exceed 8000.ALTER TABLE Description | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | table-name Identifies the table you want to be altered. a system column name is generated. Adding a new column must not make the sum of the row buffer byte counts of the columns be greater than 32766 or. It must not be a view. The database manager generates default values for ROWID columns and identity columns. For information on the byte counts of columns according to data type.

If NOT NULL is specified. DEFAULT NULL must not be specified within the same column-definition. constant Specifies the constant as the default for the column. Time Timestamp Datalink Distinct type Omission of NOT NULL and DEFAULT from a column-definition is an implicit specification of DEFAULT NULL. DECIMAL. and 0 seconds. The default value of the corresponding source type of the distinct type. or NUMERIC column. the current date.ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | DEFAULT Specifies a default value for the column. NULL Specifies null as the default for the column. A value corresponding to DLVALUE(’’. For existing rows. BIGINT. DEFAULT cannot be specified for a ROWID column or an identity column (a column that is defined AS IDENTITY).’’). This clause cannot be specified more than once in the same column-definition. A floating-point constant must not be used for a SMALLINT. the current time. then: v if the column is nullable. A decimal constant must not contain more digits to the right of the decimal point than the specified scale of the column. Chapter 5. The data type of the column must be CHAR or VARCHAR with a length attribute that is greater than or equal to the length attribute of the USER special register. a date corresponding to 1 January 0001 and a time corresponding to 0 hours. INTEGER. For added rows. the default depends on the data type of the column: Data type Numeric Fixed-length string Varying-length string Date Default value 0 Blanks A string length of 0 For existing rows. The database manager generates default values for ROWID columns and identity columns. The specified constant must represent a value that could be assigned to the column in accordance with the rules of assignment as described in “Assignments and Comparisons” on page 81. a date corresponding to 1 January 0001. For added rows. If a value is not specified following the DEFAULT keyword. the current timestamp. the default value is the null value. For existing rows. 0 seconds. the value is that of the USER special register at the time the ALTER TABLE statement is processed. 0 minutes. and 0 microseconds. For existing rows. a time corresponding to 0 hours. Statements 379 . 0 minutes.’URL’. v if the column is not nullable. USER Specifies the value of the USER special register at the time of INSERT or UPDATE as the default value for the column. For added rows.

TIME. CLOB. or DBCLOB * DATE. the constant must be a string constant. or TIMESTAMP Cast Function Name BLOB. TIME. CLOB. If CURRENT_TIMESTAMP is specified. The following table describes the allowed uses of these cast-functions. DATE. the data type of the column must be TIME or a distinct type based on a TIME. Data Type Distinct type N based on a BLOB. The data type of the source type of the distinct type of the column must be CHAR or VARCHAR with a length attribute that is greater than or equal to the length attribute of USER. or TIMESTAMP * Notes: * The name of the function must match the name of the data type (or the source type of the distinct type) with an implicit or explicit schema name of QSYS2. or DBCLOB * N (the user-defined cast function that was generated when N was created) ** or DATE. TIME. or TIMESTAMP * Distinct type N based on other data types N (the user-defined cast function that was generated when N was created) ** BLOB. the data type of the column must be DATE or a distinct type based on a DATE. CURRENT_TIME Specifies the current time as the default for the column. or DBCLOB BLOB. or TIMESTAMP DATE. 380 DB2 UDB for iSeries SQL Reference V5R2 . For existing rows. cast-function-name This form of a default value can only be used with columns defined as a distinct type. If CURRENT_TIME is specified. DBCLOB. TIME. USER Specifies the value of the USER special register at the time of INSERT or UPDATE as the default value for the column. it must be the same as the schema name for the distinct type. CLOB. the schema name from function resolution must be the same as the schema name for the distinct type. or DBCLOB Distinct type N based on a DATE.ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CURRENT_DATE Specifies the current date as the default for the column. For BLOB. The constant must conform to the rules of a constant for the source type of the distinct type or for the data type if not a distinct type. or TIMESTAMP data types. DBCLOB. the value is that of the USER special register at the time the ALTER TABLE statement is processed. CLOB. CLOB. CURRENT_TIMESTAMP Specifies the current timestamp as the default for the column. If CURRENT_DATE is specified. ** The name of the function must match the name of the distinct type for the column. TIME. and TIMESTAMP functions. the data type of the column must be TIMESTAMP or a distinct type based on a TIMESTAMP. constant Specifies a constant as the argument. If not qualified. DATE. If qualified with a schema name. TIME. CLOB. BLOB.

For a ROWID column. If CURRENT_TIME is specified. If a value is not explicitly specified when the identity column is defined. CURRENT_TIME Specifies the current time as the default for the column. The value can be any positive or negative value that could be assigned to the column without non-zero digits existing to the right of the decimal point. the database manager inserts a specified value but does not verify that it is a unique value for the column unless the identity column has a unique constraint or a unique index that solely specifies the identity column. CURRENT_TIMESTAMP Specifies the current timestamp as the default for the column. If a value is specified. BIGINT. This value is not necessarily the value that a sequence would cycle to after reaching the maximum or Chapter 5. GENERATED must be specified if the column is to be considered an identity column (defined with the AS IDENTITY clause). An identity column is implicitly NOT NULL. For an identity column. the database manager uses a specified value. It may also be specified if the data type of the column is a ROWID (or a distinct type that is based on a ROWID). Statements 381 . START WITH numeric-constant Specifies the first value that is generated for the identity column. AS IDENTITY can be specified only if the data type for the column is an exact numeric type with a scale of zero (SMALLINT. If CURRENT_TIMESTAMP is specified. A table can have only one identity column. the data type of the source type of the distinct type of the column must be DATE. it must not be specified. If CURRENT_DATE is specified. ALWAYS is the recommended value. the data type of the source type of the distinct type of the column must be TIMESTAMP. the data type of the source type of the distinct type of the column must be TIME. or a distinct type based on one of these types). an error is returned. ALWAYS Specifies that the database manager will always generate a value for the column when a row is inserted into the table. the default is the MINVALUE for an ascending sequence and the MAXVALUE for a descending sequence. AS IDENTITY Specifies that the column is an identity column for the table. INTEGER. DECIMAL or NUMERIC with a scale of zero.ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CURRENT_DATE Specifies the current date as the default for the column. Otherwise. but it must be a valid unique row ID value that was previously generated by DB2 UDB for OS/390 and z/OS or DB2 UDB for iSeries. BY DEFAULT Specifies that the database manager will generate a value for the column when a row is inserted only if a value is not specified for the column. the database manager uses that value. If the value specified is not valid. GENERATED Specifies that the database manager generates values for the column.

the sequence of values descends. MAXVALUE numeric-constant Specifies the numeric constant that is the maximum value that is generated for this identity column. If the value is positive. MINVALUE numeric-constant Specifies the numeric constant that is the minimum value that is generated for this identity column. the sequence of values for the identity column ascends. If the value is negative. the value specified for CACHE also represents the maximum number of values for the identity column that could be lost during a system failure. The minimum value that can be specified is 2. this is the maximum value of the data type (and precision. if DECIMAL) for a descending sequence. CYCLE Specifies that values continue to be generated for this column after the 382 DB2 UDB for iSeries SQL Reference V5R2 . During a system failure. for an ascending sequence. If a value is not explicitly specified when the identity column is defined. The default is 20. CYCLE or NO CYCLE Specifies whether this identity column should continue to generate values after reaching either the maximum or minimum value of the sequence. and thus. or the minimum value of the data type (and precision. and could be assigned to the column without any non-zero digits existing to the right of the decimal point. or 1 if START WITH was not specified. if DECIMAL) for an ascending sequence. NO CACHE Specifies that values for the identity column are not preallocated. The value can be any positive or negative value that is not 0. The range used for cycles is defined by MINVALUE and MAXVALUE. will never be used. The START WITH clause can be used to start a sequence outside the range that is used for cycles. This value can be any positive or negative value that could be assigned to this column. CACHE integer Specifies the number of values of the identity column sequence that the database manager preallocates and keeps in memory. does not exceed the value of a large integer constant. INCREMENT BY numeric-constant Specifies the interval between consecutive values of the identity column. but the value must be less than the maximum value. Therefore. but the value must be greater than the minimum value. The default is 1. Preallocating and storing values in the cache improves the performance of inserting rows into a table. This value can be any positive or negative value that could be assigned to this column. If a value is not explicitly specified when the identity column is defined. this is the START WITH value. or -1 if START WITH was not specified. CACHE or NO CACHE Specifies whether to keep some preallocated values in memory.ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | minimum value of the sequence. or the START WITH value. all cached identity column values that are yet to be assigned are lost. for a descending sequence. and the maximum is the largest value that can be represented as an integer.

then DEFAULT must also be specified. datalink-options Specifies the options associated with a DATALINK column. ORDER or NO ORDER Specifies whether the identity values must be generated in order of request. The maximum and minimum values for the column determine the range that is used for cycling. an error occurs. After a descending sequence reaches its minimum value of the sequence. a unique constraint name is generated by the database manager. duplicate values can be generated by the database manager for an identity column. ORDER Specifies that the values are generated in order of request. if PRIMARY KEY is specified in the definition of column C. NO CYCLE Specifies that values will not be generated for the identity column once the maximum or minimum value for the sequence has been reached. CONSTRAINT constraint-name Names the constraint. This is the default. This is the default. column-constraint The column-constraint of a column-definition provides a shorthand method of defining a constraint composed of a single column.ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | maximum or minimum value has been reached. PRIMARY KEY Provides a shorthand method of defining a primary key composed of a single column. Omission of NOT NULL implies that the column can contain null values. the effect is the same as if the PRIMARY KEY(C) clause is specified as a separate clause. after an ascending sequence reaches the maximum value of the sequence. Thus. it generates its maximum value. The column must not be a LOB or DataLink column. the effect is the same as if that constraint were specified as a unique-constraint. referential-constraint or check-constraint in which C is the only identified column. if a column-constraint is specified in the definition of column C. Chapter 5. If a unique constraint or unique index exists on the identity column. Thus. Statements 383 . NO ORDER Specifies that the values do not need to be generated in order of request. If the clause is not specified. it generates its minimum value. NOT NULL Prevents the column from containing null values. If NOT NULL is specified in the column definition. See “CREATE TABLE” on page 526 for a description of datalink-options. When CYCLE is in effect. A constraint-name must not identify a constraint that already exists at the current server. If this option is used. This clause must not be specified in more than one column-definition and must not be specified at all if the UNIQUE clause is specified in the column definition. and a non-unique value is generated for it.

if CHECK is specified in the column definition of column C. Thus. if a references-clause is specified in the definition of column C. Only the attributes specified will be altered. truncation or numeric conversion errors may occur. The column must not be a LOB or DataLink column. the existing default value must represent a value that could be assigned to the column in accordance with the rules for assignment as described in “Assignments and Comparisons” on page 81. If the specified column has a default value and a new default value is not specified. and scale. The new data type must be compatible with the existing data type of the column. This clause cannot be specified more than once in a column definition and must not be specified if PRIMARY KEY is specified in the column-definition. a CHECK constraint is implicitly added to enforce the rule that the NULL value is not allowed in the column that makes up the primary key. However. or the same as the existing length. For additional restrictions see. The specified length. smaller. precision. SET DATA TYPE data-type Specifies the new data type of the column to be altered. column-name Identifies the column to be altered. changing a datetime data type to a character-string data type is not allowed. precision. The effect is the same as if the check constraint were specified as a separate clause. Thus. precision. The name must not identify a column that is being added or dropped in the same ALTER TABLE statement. and scale may be larger. The name must identify an existing column of the specified table. UNIQUE Provides a shorthand method of defining a unique key composed of a single column. the effect is the same as if that references-clause were specified as part of a FOREIGN KEY clause in which C is the only identified column. Others will remain unchanged. ALTER column-alteration Alters the definition of a column. no columns other than C can be referenced in the check-condition of the check constraint. if the new length. For more information about the compatibility of data types see “Assignments and Comparisons” on page 81. 384 DB2 UDB for iSeries SQL Reference V5R2 .ALTER TABLE | | | | | | | | | | | | | | | | | | | | | | | | | | When a primary key is added. Thus. ROWID or DATALINK with FILE LINK CONTROL columns cannot be referenced in a CHECK constraint. the effect is the same as if the UNIQUE (C) clause is specified as a separate clause. However. “ADD check-constraint” on page 389. references-clause The references-clause of a column-definition provides a shorthand method of defining a foreign key composed of a single column. CHECK(check-condition) Provides a shorthand method of defining a check constraint whose check-condition only references a single column. The name must not be qualified. if UNIQUE is specified in the definition of column C. or scale is smaller.

the existing default value must not be NULL. the new default value is the null value. the new sum of the lengths of the columns of the keys must not exceed 2000-n. numeric-constant must be an exact numeric constant. WITH numeric-constant Specifies that numeric-constant will be used as the next value for the column. SET default-clause Specifies the new default value of the column to be altered. Chapter 5. For a description of the attributes. DROP IDENTITY is not allowed if the column is not an identity column. DROP NOT NULL is not allowed if the column is specified in the primary key of the table. SET NOT NULL Specifies that the column cannot contain null values. Statements 385 . SET NOT NULL is not allowed if the column is identified in the foreign key of a referential constraint with a DELETE rule of SET NULL and no other nullable columns exist in the foreign key. RESTART Specifies the next value for an identity column. The column must be an identity column. DROP NOT NULL Drops the NOT NULL attribute of the column. The specified column must have a default value and must not have NOT NULL as the null attribute. If a default value is not specified or does not already exist. SET GENERATED ALWAYS or GENERATED BY DEFAULT Specifies that the database manager generates values for the column. The column must be an identity column. Changing the attributes will cause any existing values in the column to be converted to the new column attributes according to the rules for assignment to a column. where n is the number of columns specified that allow nulls. making the column a simple numeric data type column. it must not be specified. Otherwise. It can be any positive or negative value that could be assigned to this column as long as there are no nonzero digits to the right of the decimal point.ALTER TABLE If the column is specified in a unique. except that string values will be truncated. see 381. allowing the column to have the null value. The new default value is the null value. If the specified column has a default value and a new default value is not specified. or foreign key. primary. All values for this column in existing rows of the table must be not null. identity-alteration Alters the identity attributes of the column. DROP DEFAULT Drops the current default for the column. GENERATED must be specified if the column is to be considered an identity column (defined with the AS IDENTITY clause) or the data type of the column is a ROWID (or a distinct type that is based on a ROWID). DROP IDENTITY Drops the identity attributes of the column. If WITH numeric-constant is not specified the sequence is restarted at the value specified implicitly or explicitly as the starting value when the identity column was originally created. The specified default value must represent a value that could be assigned to the column in accordance with the rules for assignment as described in “Assignments and Comparisons” on page 81.

CASCADE Specifies that any views.. not as a separate system logical file. If a unique index already exists on the identified columns. The same column must not be identified more than once. The column name must not be qualified. UNIQUE (column-name. and the sum of their lengths must not exceed 2000.ALTER TABLE DROP COLUMN Drops the identified column from the table. RESTRICT does not prevent the drop. The name must not identify a column that was already added or altered in this ALTER TABLE statement. and the sum of their lengths must not exceed 2000-n. The column must not be a LOB or DATALINK column. The same column must not be identified more than once. The column must not be a LOB or DATALINK column. 41 RESTRICT Specifies that the column cannot be dropped if any views.. Otherwise. where n is the number of columns specified that allow nulls. 386 DB2 UDB for iSeries SQL Reference V5R2 . The number of identified columns must not exceed 120..A) or PRIMARY KEY (A. indexes. ADD unique-constraint CONSTRAINT constraint-name Names the constraint. a unique index is created to support the uniqueness of the unique key. Each column-name must be an unqualified name that identifies a column of the table. The constraint-name must be unique within a schema. column-name Identifies the column to be dropped. If not specified. 41. The name must not identify the only column of a table. Each column-name must be an unqualified name that identifies a column of the table.B) already exists on the table. A constraint-name must not identify a constraint that already exists at the current server. The table must not already have a primary key.) Defines a primary key composed of the identified columns. Any existing nonnull values in the set of columns must be unique. The set of identified columns cannot be the same as the set of columns specified in another UNIQUE constraint or PRIMARY KEY on the table. triggers. A trigger is dependent on the column if it is referenced in the UPDATE OF column list or anywhere in the triggered action.. PRIMARY KEY (column-name. triggers. that index is designated as a unique constraint index...B) is not allowed if UNIQUE (B. UNIQUE (A.) Defines a unique key composed of the identified columns. a unique constraint name is generated by the database manager. For example. indexes. Multiple null values are allowed. or constraints are dependent on the column. The name must identify a column of the specified table. The number of identified columns must not exceed 120. or constraints that are dependent on the column being dropped are also dropped. The unique index is created as part of the system physical file. 41 If all the columns referenced in a constraint are dropped in the same ALTER TABLE statement.

ALTER TABLE The identified columns cannot be the same as the columns specified in another UNIQUE constraint on the table.. The list of column names must be identical to the list of column names in the primary key of T2 or a UNIQUE constraint that exists on T2..) The foreign key of the referential constraint is composed of the identified columns. (column-name. Each column-name must be an unqualified name that identifies a column of T2. Let T1 denote the table being altered. This table is referred to as the parent table in the constraint relationship. The Chapter 5. When a primary key is added. Statements 387 . The same column must not be identified more than once. Let T2 denote the identified parent table.) The parent key of the referential constraint is composed of the identified columns. A referential constraint is a duplicate if its foreign key. a CHECK constraint is implicitly added to enforce the rule that the NULL value is not allowed in any of the columns that make up the primary key. If a unique index already exists on the identified columns. FOREIGN KEY Defines a referential constraint. that index is designated as a primary index.B) is not allowed if UNIQUE (B. The column must not be a LOB or DATALINK column. where n is the number of columns specified that allow nulls. The number of the identified columns must not exceed 120. The unique index is created as part of the system physical file.. PRIMARY KEY (A. The column must not be a LOB or DATALINK column. and the sum of their lengths must not exceed 2000-n. and parent table are the same as the foreign key. | | | | | | | | | REFERENCES table-name The table-name specified in a REFERENCES clause must identify a base table that exists at the current server. and the sum of their lengths must not exceed 2000-n. not a separate system logical file. (column-name. For example. Each column-name must be an unqualified name that identifies a column of T1. Duplicate referential constraints are allowed. where n is the number of columns specified that allows nulls. parent key.. The same column must not be identified more than once. Otherwise. Any existing values in the set of columns must be unique.. A constraint-name must not identify a constraint that already exists at the current server. but it must not identify a catalog table or a global temporary table. a unique constraint name is generated by the database manager. and parent table of an existing referential constraint on the table. but not recommended. parent key. ADD referential-constraint CONSTRAINT constraint-name Names the constraint. If not specified.A) already exists on the table. a primary index is created to support the uniqueness of the primary key.. The number of identified columns must not exceed 120.

v If SET DEFAULT is specified. the delete operation is propagated to the dependents of p in T1. CASCADE must not be specified if T1 contains a DataLink column with FILE LINK CONTROL. v If RESTRICT or NO ACTION is specified. each nullable column of the foreign key of each dependent of p in T1 is set to null. an error occurs and no rows are deleted. For example. ON DELETE Specifies what action is to take place on the dependent tables when a row of the parent table is deleted. CASCADE must not be specified if T1 has a delete trigger. If a column name list is not specified then T2 must have a primary key. Therefore. The delete rule applies when a row of T2 is the object of a DELETE or propagated delete operation and that row has dependents in T1. There are five possible actions: v NO ACTION (default) v RESTRICT v CASCADE v SET NULL v SET DEFAULT SET NULL must not be specified unless some column of the foreign key allows null values.B) is specified. The referential constraint specified by the FOREIGN KEY clause defines a relationship in which T2 is the parent and T1 is the dependent. Values of the foreign key are validated during the execution of the ALTER TABLE statement. The description of the nth column of the foreign key and the nth column of the parent key must have identical data types and lengths. Let p denote such a row of T2. 388 DB2 UDB for iSeries SQL Reference V5R2 . Let p denote such a row of T2. ON UPDATE Specifies what action is to take place on the dependent tables when a row of the parent table is updated. the values of the foreign key must be validated before the table can be used. The update rule applies when a row of T2 is the object of an UPDATE or propagated update operation and that row has dependents in T1. Unless the table is empty. The specified foreign key must have the same number of columns as the parent key of T2. Omission of the column name list is an implicit specification of the columns of that primary key. SET NULL and SET DEFAULT must not be specified if T1 has an update trigger. v If SET NULL is specified.ALTER TABLE names may be specified in any order. each column of the foreign key of each dependent of p in T1 is set to its default value. if (A.A) would satisfy the requirement. every nonnull value of the foreign key must match some value of the parent key of T2. a unique constraint defined as UNIQUE (B. v If CASCADE is specified.

CURRENT TIME. except: v It can only refer to columns of the table and the column names must not be qualified. DLURLPATHONLY. The constraint-name must be unique within a schema. or DLURLSCHEME scalar functions – DLURLCOMPLETE scalar function (for DataLinks with an attribute of FILE LINK CONTROL and READ PERMISSION DB) For more information about search-condition. an error occurs and no rows are updated. CURDATE. RADIANS. DROP PRIMARY KEY Drops the definition of the primary key and all referential constraints in which the primary key is a parent key. and USER special registers – CURRENT DATE. and CURTIME scalar functions – NODENAME scalar function – ATAN2.ALTER TABLE v If RESTRICT or NO ACTION is specified. DLURLSERVER. CURRENT SCHEMA. CURRENT SERVER. v It must not contain any of the following: – Subqueries – Column functions – Host variables – Parameter markers – Complex expressions that contain LOBs (such as concatenation) – CURRENT TIMEZONE. Chapter 5. | | | | | | | | | | | | | | | | | | | | | | | | | | | | CHECK(check-condition) Defines a check constraint. v It cannot reference ROWID or DATALINK with FILE LINK CONTROL columns. The table must have a primary key. a unique constraint name is generated by the database manager. CURRENT PATH. The check-condition is a search-condition. The constraint-name must identify a referential constraint in which the table is a dependent. RAND. DLURLPATH. and SOUNDEX scalar functions – DLVALUE. see “Search Conditions” on page 162. FOREIGN KEY constraint-name Drops the referential constraint constraint-name. Statements 389 . The check-condition must be true or unknown for every row of the table. ADD check-constraint CONSTRAINT constraint-name Names the constraint. DIFFERENCE. If not specified. and CURRENT TIMESTAMP special registers – User-defined functions other than functions that were implicitly generated with the creation of a distinct type – NOW. A constraint-name must not identify a constraint that already exists at the current server.

that operation is logically done before any column definitions are added or altered. that same column can be referenced multiple times for adding or dropping constraints in the same ALTER TABLE statement. For example. If the constraint is a PRIMARY KEY or UNIQUE constraint. CHECK constraint-name Drops the check constraint constraint-name. If any columns are being dropped. referential. The constraint-name must identify a unique constraint on the table. | | | | | | | | 390 DB2 UDB for iSeries SQL Reference V5R2 . nor on dependent tables that reference the table being altered through a referential constraint. but no authority to those objects is required. Other objects may be accessed by the ALTER TABLE statement. QTEMP Considerations: Any views or logical files in another job’s QTEMP that are dependent on the table being altered will be dropped as a result of an ALTER TABLE statement. CASCADE Specifies for unique constraints that any referential constraints that are dependent on the constraint being dropped are also dropped. with one exception. However. or check constraint on the table. Notes Column References: A column can only be referenced once in an ADD. ALTER. DROP UNIQUE will not drop a PRIMARY KEY unique constraint. all referential constraints in which the primary key or unique key is a parent are also dropped. no authority is required on views that exist on the table being altered. The constraint-name must identify a unique. Order of Operations: The order of operations within an ALTER TABLE statement is: v drop constraints v drop columns for which the RESTRICT option was specified v alter all other column definitions – drop columns for which the CASCADE option was specified – add alter column attributes – add columns v add constraints Within each of these stages. The constraint-name must identify a check constraint on the table. RESTRICT Specifies for unique constraints that the constraint cannot be dropped if any referential constraints are dependent on the constraint. or DROP COLUMN clause in a single ALTER TABLE statement.ALTER TABLE UNIQUE constraint-name Drops the unique constraint constraint-name and all referential constraints dependent on this unique constraint. | | | | | CONSTRAINT constraint-name Drops the constraint constraint-name. Authority Checking: Authority checking is performed only on the table being altered. the order in which the user specifies the clauses is the order in which they are performed.

v Indexes may need to be rebuilt. – The allocated length of a VARGRAPHIC column is changing and the current and new allocated lengths are both less than or equal to 10. in the following cases: – The length attribute of a VARCHAR or VARGRAPHIC key is increasing. – DROP NOT NULL is specified. 44. Any indexes that need to be rebuilt are rebuilt asynchronously by database server jobs. but at least one nullable column will still exist in the table after the alter table is complete. Chapter 5. adding a column to a table does not cause the column to be added to any dependent views. a special copy that only requires approximately 16-32 megabytes of free storage is performed. – The default value is changing. – DROP DEFAULT is specified. Altering a column that is used in the key of an index or constraint usually requires the index to be rebuilt. if one CCSID is 65535. In cases where enough storage does not exist to make a complete copy. Dropping or altering a column may cause several cascaded effects. – The allocated length of a VARCHAR column is changing and the current and new allocated lengths are both less than or equal to 20. Cascaded Effects Adding a column has no cascaded effects to SQL views or most logical files. or dropping columns from a table: v The data in the table may be copied. even if those views were created with a SELECT * clause. The data does not need to be copied. 43. Altering a column usually requires the data to be copied. Table 42 on page 392 lists the cascaded effects of dropping a column. Performance Considerations: The following performance considerations apply to an ALTER TABLE statement when adding. For example. if the alter only includes the following changes: – The length attribute of a VARCHAR column is increasing and the current length attribute is greater than 20. however. A column will also be added to a logical file that shares its physical file’s format when a column is added to that physical file (unless that format is used again in the logical file with another based-on file). 42. – The length attribute of a VARGRAPHIC column is increasing and the current length attribute is greater than 10. Statements 391 . and the length of the default value is not greater than the current allocated length. For example.ALTER TABLE Backup Recommendation: It is strongly recommended that a current backup of the table and dependent views and logical files exist prior to altering a table.43 An index does not need to be rebuilt when columns are added to a table or when columns are dropped or altered and those columns are not referenced in the index key.44 For example. – The CCSID of a column is changing but no conversion is necessary between the old and new CCSID. if one CCSID is 65535.42 Adding and dropping columns require the data to be copied. no data conversion is necessary. – The CCSID of a column is changing but no conversion is necessary between the old and new CCSID. however. altering. The index does not need to be rebuilt.

the drop of the column Otherwise. and specifications. the drop of the column is not allowed.ALTER TABLE Table 42. (Hence. if column B is dropped and a referential constraint of FOREIGN KEY (A) exists. Otherwise. and v That format is not used again in v That format is not used again in the logical file with another the logical file with another based-on file. the operation is allowed. and the column is dropped from the logical file if: v The logical file shares a format with the file being altered. (Hence. The drop is allowed. (Hence. if column A is dropped. Drop of a column referenced in the key of an index Drop of a column referenced in a unique constraint The drop of the index is not allowed. and the column is dropped from the logical file if: v The logical file shares a format with the file being altered. the index used by the foreign key is also dropped). the drop of the column is not allowed. Cascaded effects of dropping a column Operation Drop of a column referenced by a view Drop of a column referenced by a non-view logical file RESTRICT Effect The drop of the column is not allowed. the index used to satisfy the constraint is also dropped. CASCADE Effect The view and all views dependent on that view are dropped. If all the columns referenced in the unique constraint are dropped in the same ALTER COLUMN statement and the unique constraint is not referenced by a referential constraint. The referential constraint is dropped. (Hence. Drop of a column referenced in a referential constraint If all the columns referenced in the referential constraint are dropped at the same time. the columns and the constraint are dropped. Otherwise. and The drop is allowed. For example. dropped. The unique constraint is dropped as are any referential constraints that refer to that unique constraint. based-on file. 392 DB2 UDB for iSeries SQL Reference V5R2 . Otherwise. and v The dropped column is not used v The dropped column is not used as a key field or in select/omit as a key field or in select or omit specifications. The index is dropped. the columns and the constraint are dropped.) For example. the logical file is is not allowed. the operation is allowed. the index used by the foreign key is also dropped). any indexes used by those constraints are also dropped). and a unique constraint of UNIQUE (A) or PRIMARY KEY (A) exists and no referential constraints reference the unique constraint.

precision. The new view column attributes will be used when recreating the views. the new column attributes will not be used when recreating the logical file. file and that format is not used again in the logical file with another based-on file. Cascaded effects of altering a column Operation Effect Alter of a column The alter is allowed. The constraint will be placed in a defined and check-pending state. (Alter of a column in the following chart means altering a data type. referential the alter is allowed and an attempt is made to put the constraint in constraint the enabled state. the attributes of the foreign keys no longer match the attributes of the unique constraint. referenced by a non-view logical The non-view logical files that are dependent on the table will be recreated. the index will usually be rebuilt. which is one character long. ALTER TABLE EMPLOYEE ADD PICTURE_THUMBNAIL VARCHAR(1000) FOR BIT DATA Example 3: Assume a new table EQUIPMENT has been created with the following columns: EQUIP_NO EQUIP_DESC INT VARCHAR(50) Chapter 5.) v If the referential constraint is in the enabled state. Alter of a column The alter is allowed. to the DEPARTMENT table.ALTER TABLE Table 43 lists the cascaded effects of altering a column. If the logical file shares a format with the file being altered.) referenced in the key of an index. ALTER TABLE DEPARTMENT ADD RATING CHAR Example 2: Add a new column named PICTURE_THUMBNAIL to the EMPLOYEE table. scale. Alter of a column The alter is allowed.) Table 43. the index used to satisfy the unique constraint will usually to be rebuilt. Otherwise. Create PICTURE_THUMBNAIL as a varying-length column with a maximum length of 1000 characters. the constraint is placed in the defined and check-pending state. length. (Hence. Alter of a column The alter is allowed. (Hence. referenced in a v If the referential constraint is in the defined but check-pending state. the index will usually be rebuilt. the new column attributes will be used when recreating the logical file.) referenced in a unique constraint If the unique constraint is referenced by a referential constraint. the current logical file attributes are used. Statements 393 . (Hence. Instead. referenced by a The views that are dependent on the table will be recreated. Examples Example 1: Add a new column named RATING. or nullability characteristic. Alter of a column The alter is allowed. The values of the column do not have an associated character set and therefore should not be converted.

indexes.ALTER TABLE LOCATION EQUIP_OWNER VARCHAR(50) CHAR(3) Add a referential constraint to the EQUIPMENT table so that the owner (EQUIP_OWNER) must be a department number (DEPTNO) that is present in the DEPARTMENT table. ALTER TABLE EQUIPMENT ADD COLUMN SUPPLIER INT DROP COLUMN LOCATION ADD UNIQUE SUPPLIER ADD PRIMARY KEY EQUIP_NO Notice that the column EQUIP_DESC is a variable length column. or constraints that are built on that column. ALTER TABLE EMPLOYEE ADD CONSTRAINT REVENUE CHECK (SALARY + COMM > 30000) Example 5: Alter EMPLOYEE table. ALTER TABLE EMPLOYEE ALTER COLUMN PHONENO SET DATA TYPE VARCHAR (20) 394 DB2 UDB for iSeries SQL Reference V5R2 . If a department is removed from the DEPARTMENT table. ALTER TABLE EQUIPMENT FOREIGN KEY DEPTQUIP (EQUIP_OWNER) REFERENCES DEPARTMENT ON DELETE SET NULL Change the default value for the EQUIP_OWNER column to ’ABC’. the following ALTER TABLE statement would not change that allocated length. Alter the column PHONENO to accept up to 20 characters for a phone number. and a primary key is built over the existing column EQUIP_NO. Also drop any views. a unique constraint over the new column SUPPLIER is added. If an allocated length of 25 was specified. Add the check constraint named REVENUE defined so that each employee must make a total of salary and commission greater than $30. Drop the constraint REVENUE which was previously defined. the owner (EQUIP_OWNER) values for all equipment owned by that department should become unassigned (or set to null). the existing column called LOCATION is dropped. Give the constraint the name DEPTQUIP. ALTER TABLE EQUIPMENT ALTER COLUMN EQUIP_OWNER SET DEFAULT ’ABC’ Drop the LOCATION column. ALTER TABLE EQUIPMENT DROP COLUMN LOCATION CASCADE Alter the table so that a new column called SUPPLIER is added.000. ALTER TABLE EMPLOYEE DROP CONSTRAINT REVENUE Example 6: Alter the EMPLOYEE table. ALTER TABLE EQUIPMENT ALTER COLUMN EQUIP_DESC SET DATA TYPE VARCHAR(60) Example 4: Alter the EMPLOYEE table.

If SQL declare sections are not specified in the program. | | | Invocation This statement can only be embedded in an application program. described in “END DECLARE SECTION” on page 640. It cannot be coded in the middle of a host structure declaration. and they are not declared at all in REXX. Statements 395 . An SQL declare section ends with an END DECLARE SECTION statement. Host variables are declared without the use of these statements in Java and RPG. the ADD keyword is optional. SQL declare sections are required for all host variables in C++. Chapter 5.BEGIN DECLARE SECTION BEGIN DECLARE SECTION The BEGIN DECLARE SECTION statement marks the beginning of an SQL declare section. Variables declared outside an SQL declare section should not have the same name as variables declared within an SQL declare section. Syntax alternatives: If an ADD constraint is the first clause of the ALTER TABLE statement. RPG. The BEGIN DECLARE SECTION and the END DECLARE SECTION statements must be paired and cannot be nested. so that the source program conforms to the IBM SQL standard of SQL. More than one SQL declare section can be specified in the program. SQL statements should not be included within a declare section. only the variables declared within the SQL declare sections can be used as host variables. Syntax BEGIN DECLARE SECTION Description The BEGIN DECLARE SECTION statement is used to indicate the beginning of an SQL declare section. Otherwise. but strongly recommended. It must not be specified in Java. It can be coded in the application program wherever variable declarations can appear in accordance with the rules of the host language. all variables in the program are eligible for use as host variables. The SQL declare section should appear before the first reference to the variable. other than RPG and REXX. Authorization None required. or REXX. SQL declare sections should be specified for host languages. with the exception of the DECLARE VARIABLE and INCLUDE statements. it is required. It is not an executable statement. If SQL declare sections are specified in the program.

} hv_vchar24. HV-VCHAR24 (varchar(24)). WORKING-STORAGE SECTION. static short hv_smint. char hv_vchar24_value[24]. static struct { short hv_vchar24_len. 49 HV-VCHAR24-VALUE PIC X(24). 01 HV-SMINT PIC S9(4) BINARY. static double hv_double.BEGIN DECLARE SECTION Examples Example 1: Define the host variables hv_smint (SMALLINT). EXEC SQL END DECLARE SECTION. EXEC SQL BEGIN DECLARE SECTION. 49 HV-VCHAR24-LENGTH PIC S9(4) BINARY. and HV-DEC72 (dec(7.2)) in a COBOL program. and hv_double (DOUBLE) in a C program. Example 2: Define the host variables HV-SMINT (smallint). hv_vchar24 (VARCHAR(24)). 396 DB2 UDB for iSeries SQL Reference V5R2 . 01 HV-DEC72 PIC S9(5)V9(2) PACKED-DECIMAL. EXEC SQL BEGIN DECLARE SECTION END-EXEC. 01 HV-VCHAR24. EXEC SQL END DECLARE SECTION END-EXEC.

or v It has been granted the system authorities of *OBJOPR and *EXECUTE on the procedure. the procedure is a Java external procedure: Read authority (*R) to the integrated file system file that contains the Java class. – – v If – The system authority *EXECUTE on the library containing the source file. v It has been granted the EXECUTE privilege on the procedure. v If the procedure is an external procedure. and – The system authority *EXECUTE on the library containing the program associated with the procedure v If the procedure is an SQL procedure: – The EXECUTE privilege on the procedure. and *EXECUTE on the source file associated with the procedure. *READ. | | | | | | Syntax CALL procedure-name host-variable Chapter 5. but not a REXX or Java external procedure: – The system authority *EXECUTE on the program associated with the procedure. It is an executable statement that can be dynamically prepared.CALL CALL | The CALL statement calls a procedure. and – The system authority *EXECUTE on the library containing the SQL procedure v Administrative authority The authorization ID of the statement has the EXECUTE privilege on a procedure when: v It is the owner of the procedure. Invocation This statement can be embedded in an application program or issued interactively. and The system authority *USE to the CL command. Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v If the procedure is a REXX external procedure: – The system authorities *OBJOPR. | | | | | | | | | – Read and execute authority (*RX) to all directories that must be accessed in order to find the integrated file system file. Statements 397 .

and calling convention. the language is assumed to be C. v The application requester assumes all parameters that are host variables or parameter markers are INOUT. If a host-variable is specified: v It must be a character-string variable or UCS-2 graphic-string. Otherwise. – If the program attribute information associated with the program identifies a recognizable language. and calling convention. language. v It must not include an indicator variable. 398 DB2 UDB for iSeries SQL Reference V5R2 . host-variable constant NULL special-register DLVALUE ( arguments ) cast-function-name ( constant host-variable USING DESCRIPTOR descriptor-name ) ) Description procedure-name or host-variable Identifies the procedure to call by the specified procedure-name or the procedure name contained in the host-variable. For more information see “Qualification of Unqualified Object Names” on page 53. then that language is used. language. v The procedure name that is contained within the host variable must be left-justified and must be padded on the right with blanks if its length is less than that of the host variable. v If the current server is DB2 UDB for iSeries: – The external program name is assumed to be the same as the external procedure name. Otherwise: v The current server determines the name of the external program. The identified procedure must exist at the current server. If the procedure name is unqualified. then: v The DECLARE PROCEDURE statement determines the name of the external program. v The attributes of the parameters of the procedure are defined by the DECLARE PROCEDURE statement. If the procedure-name identifies a procedure that was defined by a DECLARE PROCEDURE statement. and the current server is a DB2 UDB for iSeries server. All parameters that are not host variables are assumed to be IN. – The calling convention is assumed to be GENERAL.CALL ( . v The name of the procedure must be in uppercase unless it is a delimited name. it is implicitly qualified based on the path and number of parameters.

For an explanation of constant and host-variable. and path/file). see “Constants” on page 100 and “References to Host Variables” on page 115. host variable. The actual attributes of the parameters are determined by the current server. The following table describes the allowed uses of these cast-functions. The second and third arguments of DLVALUE must be constants or host-variables. leading zeroes are not significant. DLVALUE(arguments) Specifies the value for the parameter is the value resulting from a DLVALUE scalar function. cast-function-name This form of an argument can only be used with parameters defined as a distinct type. TIME. 45. DATE. TIME. Each parameter defined (using a CREATE PROCEDURE or DECLARE PROCEDURE statement) as OUT or INOUT must be specified as a host variable. The DLVALUE function requires a link value on insert (scheme. The first argument of DLVALUE must be a constant. CLOB. or TIMESTAMP * * The name of the function must match the name of the data type (or the source type of the distinct type) with an implicit or explicit schema name of QSYS2. Statements 399 . or DBCLOB Distinct type N based on a DATE. leading zeroes are significant when determining the attributes of the argument. Note that in the case of decimal constants. CLOB. 45 host-variable or constant or NULL or special-register Identifies a list of values to be passed as parameters to the procedure. or TIMESTAMP BLOB. TIME or TIMESTAMP data types. or DBCLOB * DATE. CLOB. CLOB. where it is assumed all parameters that are host variables are IN unless the mode is explicitly specified in the host variable reference. or TIMESTAMP * BLOB. or DBCLOB * DATE. CLOB. TIME. or TIMESTAMP Notes: Cast Function Name BLOB. NULL specifies the null value. or DBCLOB DATE. The nth value corresponds to the nth parameter in the procedure. The number of arguments specified must be the same as the number of parameters of a procedure defined at the current server with the specified procedure-name. server. see “Special Registers” on page 106. If the current server is a DB2 UDB for iSeries. A DLVALUE scalar function can only be specified for a DataLink parameter. or a typed parameter marker (CAST(? AS data-type)). BLOB. Normally. For a description of special-register. Chapter 5. the attributes of the parameters will be the same as the attributes of the arguments specified on the CALL statement. Parameter Type Distinct type N based on a BLOB. TIME. All parameters that are not host variables are assumed to be input parameters.CALL v The actual attributes of the parameters are determined by the current server. The application requester assumes all parameters that are host variables are INOUT parameters except for Java. DBCLOB.

DATE. the value of each of its parameters is assigned (using storage assignment) to the corresponding parameter of the procedure. host-variable Specifies a host variable as the argument. Control is passed to the procedure according to the calling conventions of the host language. The SQLDA must have enough storage to contain all SQLVAR occurrences. see “Assignments and Comparisons” on page 81. Notes Parameter assignments: When the CALL statement is executed. The constant must conform to the rules of a constant for the source type of the distinct type or for the data type if not a distinct type.” on page 847. The nth variable described by the SQLDA corresponds to the nth parameter marker in the prepared statement. For BLOB. The host variable must conform to the rules of a constant for the source type of the distinct type or for the data type if not a distinct type.) Note that RPG/400 does not provide the function for setting pointers.CALL constant Specifies a constant as the argument. TIME. you must set the following fields in the SQLDA. and TIMESTAMP functions. CLOB. Cursors and prepared statements in procedures: All cursors opened in the called procedure that are not result set cursors are closed and all statements prepared in the called procedure are destroyed when the procedure ends. Therefore. there must be two SQLVAR entries for each parameter marker and SQLN must be set to two times the number of parameter markers. the value of each parameter of the procedure is assigned (using storage assignment) to the corresponding parameter of the CALL statement defined as OUT or INOUT. It must be the same as the number of parameters in the CALL statement. “SQL Descriptor Area (SQLDA). (For a description of an SQLDA. If LOBs or distinct types are specified. For details on the assignment rules. Before the CALL statement is processed. you have to set these pointers outside your RPG/400 application. the value in SQLDABC must be greater than or equal to 16 + SQLN*(80). SQLD must be set to a value greater than or equal to zero and less than or equal to SQLN.) v SQLN to indicate the number of SQLVAR occurrences provided in the SQLDA v SQLDABC to indicate the number of bytes of storage allocated for the SQLDA v SQLD to indicate the number of variables used in the SQLDA when processing the statement v SQLVAR occurrences to indicate the attributes of the variables. For more information. 400 DB2 UDB for iSeries SQL Reference V5R2 . USING DESCRIPTOR descriptor-name Identifies an SQLDA that must contain a valid description of host variables. where 80 is the length of an SQLVAR occurrence. see the SQL Programming with Host Languages book. When execution of the procedure is complete. (The rules for REXX are different. the constant must be a string constant. Because the SQLDA uses pointers to locate the appropriate host variables. DBCLOB. see Appendix D.

an attribute is set for SQL data-access that was defined when the procedure was created. then the procedure must be declared using the CREATE PROCEDURE or DECLARE PROCEDURE statement. or trigger. When a procedure. Chapter 5. the SET RESULT SETS statement identifies the result sets. from the SQL Call Level Interface. or from JDBC. – If no cursors have specified a WITH RETURN clause. Statements 401 . Nesting CALL Statements: A program that is executing as a procedure. an error is issued if: v The invoked procedure possibly contains SQL and the invoking procedure does not allow SQL v The invoked procedure reads SQL data and the invoking procedure does not allow reading SQL data v The invoked procedure modifies SQL data and the invoking procedure does not allow modifying SQL data REXX procedures: If the external procedure to be called is a REXX procedure. For example. the call is considered to be nested. – If any cursors have specified a WITH RETURN clause. Only PROCA can access any result sets that PROCB returns. each cursor that is defined with the WITH RETURN clause that the procedure opens and leaves open when it returns identifies a result set. If a procedure returns any query result sets. When a result set is returned using an open cursor. a user-defined function.CALL Result Sets from procedures: Result sets are only returned from a procedure when the procedure is called from a client using the iSeries Access Open Database Connectivity (ODBC) driver. if a client program calls procedure PROCA. When an SQL or an external procedure is called. The possible values for the attribute are: NONE CONTAINS READS MODIFIES If a second procedure is invoked within the execution of the current procedure. user-defined function. There are three ways to return result sets from a procedure: v If a SET RESULT SETS statement is executed in the procedure. which in turn calls procedure PROCB. or trigger calls a procedure. The result sets are returned in the order in which the cursors are opened. The result sets are returned in the order in which the cursors are opened. If the SQL CALL statement is nested. but triggers can only be nested up to 300 levels deep. the rows are returned starting with the current cursor position. the result sets are visible only to the program that is at the previous nesting level. the result sets are returned to the caller of the procedure. There is no limit on how many levels procedures and functions can be nested. v If a SET RESULT SETS statement is not executed in the procedure. each cursor that the procedure opens and leaves open when it returns identifies a result set. The result sets are returned in the order specified on the SET RESULT SETS statement. or a trigger can issue a CALL statement. user-defined function. a client using the iSeries Access Optimized SQL API. the client program has no access to the query result sets.

This application code fragment will invoke the Java method onhand in class parts since the procedure-name specified on the CALL statement is found in the database and has the external name ’parts!onhand’... /* Setup code for SQLDA variables goes here */ CALL SALARY_PROC USING DESCRIPTOR :*INOUT_SQLDA. variable1. struct sqlda *INOUT_SQLDA. 402 DB2 UDB for iSeries SQL Reference V5R2 .CALL Host variables cannot be used in the CALL statement within a REXX procedure.2). #sql [ctx] . OUT QUANTITY INTEGER) LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME ’parts!onhand’. Examples Example 1: Call procedure PGM1 and pass two parameters. Example 3: A Java procedure is defined in the database using the following statement: CREATE PROCEDURE PARTS_ON_HAND (IN PARTNUM INTEGER.. Instead. :OUT variable3)}. variable2..:hv2) Example 2: In C. :OUT variable2. A Java application calls this procedure on the connection context ’ctx’ using the following code fragment: . int BigDecimal Integer ... {CALL PARTS_ON_HAND(:IN variable1. invoke a procedure called SALARY_PROCED using the SQLDA named INOUT_SQLDA. the CALL must be the object of a PREPARE and EXECUTE using parameter markers. OUT COST DECIMAL(7. CALL PGM1 (:hv1. variable3.

Notes Implicit cursor close: All cursors in a program are in the closed state when: v The program is called. all cursors are in the closed state only the first time the program is called in the job. see the SQL Programming Concepts book. | | | | Invocation This statement can only be embedded in an application program. that table is destroyed. For more information. – If CLOSQLCSR(*ENDSQL) is specified. The cursor-name must identify a declared cursor as explained in the DECLARE CURSOR statement. Syntax CLOSE cursor-name Description cursor-name Identifies the cursor to be closed. The closing of the files can be separate from the SQL CLOSE statement. It must not be specified in Java. all cursors are in the closed state the first time the module in the program is initiated within the activation group. the cursor must be in the open state. all cursors are in the closed state only the first time the program is called as long as one SQL program remains on the call stack. – If CLOSQLCSR(*ENDJOB) is specified. – If CLOSQLCSR(*ENDACTGRP) is specified. all cursors are in the closed state each time the program is called.CLOSE CLOSE The CLOSE statement closes a cursor. – If CLOSQLCSR(*ENDMOD) is specified. If a result table was created when the cursor was opened. Chapter 5. v A program starts a new unit of work by executing a COMMIT or ROLLBACK statement without a HOLD option. When the CLOSE statement is executed. Cursors declared with the HOLD option are not closed by a COMMIT statement. – If CLOSQLCSR(*ENDPGM) is specified. Note: The DB2 UDB for iSeries database manager will open files in order to implement queries. It is an executable statement that cannot be dynamically prepared. Authorization None required. Statements 403 . all cursors are in the closed state each time the module is initiated. See “DECLARE CURSOR” on page 577 for the authorization required to use a cursor.

77 PRJ PIC X(6). EMPTIME FROM EMPPROJACT OPEN C1 END-EXEC. Example In a COBOL program. :ACT. ACTNO. GET-REST-OF-ACTIVITY EXEC SQL FETCH C1 INTO :EMP. 404 DB2 UDB for iSeries SQL Reference V5R2 . . :TIM IF SQLSTATE = ’02000’ PERFORM DATA-NOT-FOUND ELSE PERFORM GET-REST-OF-ACTIVITY UNTIL SQLSTATE IS NOT EQUAL TO ’00000’. see “CALL” on page 397. :PRJ. Procedure considerations: Special rules apply to cursors within procedures that have not been closed before returning to the calling program. 77 TIM PIC S9(3)V9(2) PACKED-DECIMAL.CLOSE Close cursors for performance: Explicitly closing cursors as soon as possible can improve performance. . . PROJNO. END-EXEC. EXEC SQL CLOSE C1 END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. . :ACT. . close the cursor. 77 EMP PIC X(6). 77 ACT PIC S9(4) BINARY. END-EXEC. EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO. use the cursor C1 to fetch the values from the first four columns of the EMPPROJACT table a row at a time and put them in the following host variables: v EMP (CHAR(6)) v PRJ (CHAR(6)) v ACT (SMALLINT) v TIM (DECIMAL(5. :PRJ. For more information.2)) Finally. EXEC SQL EXEC SQL FETCH C1 INTO :EMP. :TIM . END-EXEC. EXEC SQL END DECLARE SECTION END-EXEC.

and – The system authority *EXECUTE on the library that contains the subject table v Administrative authority To comment on a function. alias. index. or package in the statement. view. distinct type. the privileges held by the authorization ID of the statement must include at least one of the following: v For the SYSFUNCS catalog view: – The UPDATE privilege on the view – The system authority *EXECUTE on library QSYS2 v Administrative authority To comment on a procedure. the privileges held by the authorization ID of the statement must include at least one of the following: v For the subject table of the trigger in the statement: – The ALTER privilege on the subject table. Authorization To comment on a table. alias.COMMENT COMMENT The COMMENT statement adds or replaces comments in the catalog descriptions of various database objects. index. distinct type. distinct type. or package. alias. alias. or v It has been granted the system authorities of either *OBJALTER or *OBJMGT to the table. alias. – The ALTER privilege on the table. index. or package. view. view. distinct type. the privileges held by the authorization ID of the statement must include at least one of the following: v For the table. index. view. index. view. alias. distinct type. It is an executable statement that can be dynamically prepared. distinct type. distinct type. view. or package v Administrative authority The authorization ID of the statement has the ALTER privilege on the table. column. alias. index. or package when: v It is the owner of the table. Statements 405 . or package v It has been granted the ALTER privilege to the table. Invocation This statement can be embedded in an application program or issued interactively. index. view. alias. the privileges held by the authorization ID of the statement must include at least one of the following: v For the SYSPROCS catalog view: – The UPDATE privilege on the view. and – The system authority *EXECUTE on the library that contains the table. and – The system authority *EXECUTE on library QSYS2 v Administrative authority Chapter 5. or package To comment on a trigger. or package. distinct type. view.

COMMENT To comment on a parameter. 406 DB2 UDB for iSeries SQL Reference V5R2 . the privileges held by the authorization ID of the statement must include at least one of the following: v For the SYSPARMS catalog table: – The UPDATE privilege on the table. and – The system authority *EXECUTE on library QSYS2 v Administrative authority The authorization ID of the statement has the UPDATE privilege on a table when any of these are true: v It is the owner of the table v It has been granted the UPDATE privilege on the table v It has been granted the system authorities of *OBJOPR and *UPD on the table.

parameter-type FUNCTION specific-name ROUTINE INDEX index-name PACKAGE package-name PARAMETER routine-name.column-name TYPE distinct-type-name DISTINCT FUNCTION function-name ROUTINE ( .column-name view-name.parameter-name SPECIFIC FUNCTION specific-name.parameter-name PROCEDURE ROUTINE PROCEDURE procedure-name ROUTINE ( ) .COMMENT Syntax COMMENT ON ALIAS alias-name COLUMN table-name. SPECIFIC parameter-type PROCEDURE ROUTINE TABLE table-name view-name TRIGGER trigger-name multiple-columns multiple-parameters SPECIFIC specific-name IS string-constant ) Chapter 5. Statements 407 .

( parameter-name IS string-constant ) parameter-type: data-type AS LOCATOR data-type: built-in-type distinct-type-name 408 DB2 UDB for iSeries SQL Reference V5R2 . COLUMN table-name view-name ( column-name IS string-constant ) multiple-parameters: PARAMETER SPECIFIC FUNCTION PROCEDURE ROUTINE specific-name ROUTINE routine-name FUNCTION PROCEDURE ( .COMMENT multiple-columns: . parameter-type ) .

Statements 409 . integer ) (1) GRAPHIC ( VARGRAPHIC GRAPHIC VARYING (1M) DBCLOB ( integer integer ( integer ) ) CCSID integer ) K M G (1M) ( integer CCSID integer AS LOCATOR BLOB BINARY LARGE OBJECT ) K M G AS LOCATOR DATE ( 0 ) TIME ( 6 ) TIMESTAMP (200) DATALINK ( integer ROWID ) CCSID integer Description ALIAS alias-name Identifies the alias to which the comment applies. Chapter 5.COMMENT built-in-type: SMALLINT INTEGER INT BIGINT (5.0) DECIMAL DEC NUMERIC (53) FLOAT ( integer ) REAL PRECISION DOUBLE (1) CHARACTER CHAR CHARACTER CHAR VARCHAR ( integer VARYING ( integer (1M) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer AS LOCATOR ) ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer ( integer . COLUMN Specifies that a comment will be added to or replaced for a column. The alias-name must identify an alias that exists at the current server.

If function-name () is specified. DISTINCT TYPE distinct-type-name Identifies the distinct type to which the comment applies.. FUNCTION function-name Identifies the function by its name.2). v If length. . If the data type is FLOAT. Synonyms for data types are considered a match.column-name Identifies the column to which the comment applies. use one of the following: v Empty parentheses indicate that the database manager ignores the attribute when determining whether the data types match. an error is returned.. The column-name must identify a column of that table or view.. (parameter-type. the database manager searches the SQL path to resolve the schema name for the distinct type.) Identifies the function by its function signature. . The distinct-type-name must identify a distinct type that exists at the current server. but must not identify a global temporary table.) Identifies the parameters of the function. FUNCTION or SPECIFIC FUNCTION Identifies the function on which the comment applies. the default attributes of the data type 410 DB2 UDB for iSeries SQL Reference V5R2 . The specified parameters must match the data types in the corresponding position that were specified when the function was created. The function must exist at the current server and it must be a user-defined function. the precision does not have to exactly match the value that was specified because matching is based on the data type (REAL or DOUBLE).. If an unqualified distinct type name is specified. function signature. For data types that have a length. precision. v If a specific value for a length. FLOAT cannot be specified with empty parenthesis because its parameter value indicates a specific data type (REAL or DOUBLE). For example. FUNCTION function-name (parameter-type. function-name Identifies the name of the function. which uniquely identifies the function. precision. or scale attribute is specified.) must identify a function with the specified function signature. and the logical concatenation of the data types is used to identify the specific function instance on which to comment. the value must exactly match the value that was specified (implicitly or explicitly) in the CREATE FUNCTION statement.COMMENT | | | | | table-name. the function identified must have zero parameters. The function-name must identify exactly one function.column-name or view-name.. or scale is not explicitly specified. The function can be identified by its name. The function may have any number of parameters defined for it. The table-name or view-name must identify a table or view that exists at the current server. The number of data types. or scale attribute. However. and empty parentheses are not specified. DEC() will be considered a match for a parameter of a function defined with a data type of DEC(7. If there is more than one function of the specified name in the specified or implicit schema. precision. or specific name. .. The function-name (parameter-type.

SPECIFIC FUNCTION specific-name Identifies the function by its specific name. an error is returned. Specifying the FOR DATA clause or CCSID clause is optional. If there is more than one procedure of the specified name in the specified or implicit schema. PROCEDURE procedure-name (parameter-type.. Omission of either clause indicates that the database manager ignores the attribute when determining whether the data types match.. The index-name must identify an index that exists at the current server. which uniquely identifies the procedure. INDEX index-name Identifies the index to which the comment applies. The specific-name must identify a specific function that exists at the current server. The parameter could be for a procedure or a function. PACKAGE package-name Identifies the package to which the comment applies. Chapter 5.) Identifies the procedure by its procedure signature.parameter-name Identifies the parameter to which the comment applies. PROCEDURE or SPECIFIC PROCEDURE Identifies the procedure on the comment applies. routine-name. the data type must be a LOB or a distinct type based on a LOB.. If AS LOCATOR is specified. and the logical concatenation of the data types is used to identify the specific procedure instance which is to be commented on. it must match the value that was implicitly or explicitly specified in the CREATE FUNCTION statement. If either clause is specified. . The procedure-name (parameter-type. and the parameter-name must identify a parameter of that procedure or function. The number of data types. The parameter could be for a procedure or a function.COMMENT are implied.) must identify a procedure with the specified procedure signature. . The procedure-name must identify exactly one procedure. The procedure-name must identify a procedure that exists at the current server.parameter-name Identifies the parameter to which the comment applies. Statements 411 . PARAMETER Specifies that a comment will be added to or replaced for a parameter. and the parameter-name must identify a parameter of that procedure or function. The implicit length must exactly match the value that was specified (implicitly or explicitly) in the CREATE FUNCTION statement. The specific-name must identify a procedure or function that exists at the current server. The specified parameters must match the data types in the corresponding position that were specified when the procedure was created. Synonyms for data types are considered a match. The procedure may have any number of parameters defined for it. The package-name must identify a package that exists at the current server. AS LOCATOR Specifies that the function is defined to receive a locator for this parameter. The routine-name must identify a procedure or function that exists at the current server.. PROCEDURE procedure-name Identifies the procedure by its name. specific-name.

precision. However. If AS LOCATOR is specified. AS LOCATOR Specifies that the procedure is defined to receive a locator for this parameter. it must match the value that was implicitly or explicitly specified in the CREATE PROCEDURE statement.. If an unqualified distinct type name is specified. use one of the following: v Empty parentheses indicate that the database manager ignores the attribute when determining whether the data types match. The specific-name must identify a specific procedure that exists at the current server. precision. v If length. 412 DB2 UDB for iSeries SQL Reference V5R2 . TRIGGER trigger-name Identifies the trigger to which the comment applies. For data types that have a length. precision. IS Introduces the comment that to be added or replaced. Omission of either clause indicates that the database manager ignores the attribute when determining whether the data types match. | | | | TABLE table-name or view-name Identifies the table or view to which the comment applies. (parameter-type. The table-name or view-name must identify a table or view that exists at the current server. but must not identify a global temporary table. SPECIFIC PROCEDURE specific-name Identifies the procedure by its specific name. v If a specific value for a length. The trigger-name must identify a trigger that exists at the current server. For example. procedure-name Identifies the name of the procedure.2).) Identifies the parameters of the procedure. FLOAT cannot be specified with empty parenthesis because its parameter value indicates a specific data type (REAL or DOUBLE). the precision does not have to exactly match the value that was specified because matching is based on the data type (REAL or DOUBLE). or scale attribute is specified. and empty parentheses are not specified. or scale is not explicitly specified. the data type must be a LOB or a distinct type based on a LOB. the procedure identified must have zero parameters. If either clause is specified. If the data type is FLOAT. DEC() will be considered a match for a parameter of a procedure defined with a data type of DEC(7. the default attributes of the data type are implied..COMMENT If procedure-name () is specified. Specifying the FOR DATA clause or CCSID clause is optional. the database manager searches the SQL path to resolve the schema name for the distinct type. the value must exactly match the value that was specified (implicitly or explicitly) in the CREATE PROCEDURE statement. . or scale attribute. The implicit length must exactly match the value that was specified (implicitly or explicitly) in the CREATE PROCEDURE statement.

The parameter name must not be qualified. or specific name. and that procedure or function must exist at the current server. COMMENT ON PACKAGE PAYROLL IS ’This package is used for distributed payroll processing. These keywords are non-standard and should not be used: v The keyword PROGRAM can be used as a synonym for PACKAGE. multiple-columns To comment on more than one column in a table or view. COMMENT ON TABLE EMP_VIEW1 IS ’View of the EMPLOYEE table without salary information’ Example 3: Insert a comment for the EDLEVEL column of the EMPLOYEE table. COMMENT ON TABLE EMPLOYEE IS ’Reflects first quarter 2000 reorganization’ Example 2: Insert a comment for the EMP_VIEW1 view.COMMENT string-constant Can be any character-string constant of up to 2000 characters.. each name must identify a column of the specified table or view. and then. Examples Example 1: Insert a comment for the EMPLOYEE table. Statements 413 . a list of the form: column-name IS string-constant.. specify the procedure name.EDLEVEL IS ’Highest grade level passed in school’ Example 4: Enter comments on two columns in the DEPARTMENT table. The column name must not be qualified. . COMMENT ON DEPARTMENT (MGRNO IS ’EMPLOYEE NUMBER OF DEPARTMENT MANAGER’. . and that table or view must exist at the current server. a list of the form: parameter-name IS string-constant. v The keyword DATA can be used as a synonym for DISTINCT. ADMRDEPT IS ’DEPARTMENT NUMBER OF ADMINISTERING DEPARTMENT’) Example 5: Insert a comment for the PAYROLL package.. function name. in parenthesis.’ Chapter 5. column-name IS string-constant. each name must identify a parameter of the specified procedure or function. parameter-name IS string-constant. specify the table or view name and then. multiple-parameters To comment on more than one parameter in a procedure or function. in parenthesis.. Notes | | | | | Keyword Synonym: The following keywords are synonyms supported for compatibility to prior releases. COMMENT ON COLUMN EMPLOYEE.

Connections in the release-pending state are ended. WORK COMMIT WORK has the same effect as COMMIT. Locks on specific rows and objects implicitly acquired during the unit of work are released. COMMIT is not allowed in a procedure if the procedure is called on a remote server. All implicitly acquired locks are released. a portable application should explicitly execute a COMMIT or ROLLBACK before execution ends in those environments where explicit COMMIT or ROLLBACK is permitted. Syntax WORK COMMIT HOLD Description | | | | | The COMMIT statement ends the unit of work in which it is executed and starts a new unit of work. It commits all changes made by SQL schema statements (except DROP SCHEMA) and SQL data change statements during the unit of work. except for object level locks required for the cursors that are not closed. If specified. Notes Recommended coding practices: An explicit COMMIT or ROLLBACK statement should be coded at the end of an application process. COMMIT is not allowed in a trigger if the trigger program and the triggering program run under the same commitment definition. For information on SQL schema statements and SQL data change statements see Table 33 on page 363 and Table 34 on page 364. currently open cursors are not closed and all resources acquired during the unit of work are held. 414 DB2 UDB for iSeries SQL Reference V5R2 .COMMIT COMMIT The COMMIT statement ends a unit of work and commits the database changes that were made by that unit of work. Either an implicit commit or rollback operation will be performed at the end of an application process depending on the application environment. It is an executable statement that can be dynamically prepared. | | All locators that are not held are released. Invocation This statement can be embedded in an application program or issued interactively. HOLD Specifies a hold on resources. Thus. Authorization None required. see “HOLD LOCATOR” on page 670. For more information on held locators.

or SET DEFAULT referential integrity delete rule. Note that this is true even when the locators are associated with LOB values retrieved via a cursor that has the WITH HOLD property. v All LOB locators are freed. v For the default activation group: – An implicit COMMIT is not performed when applications that run in the default activation group end. – In order to commit work. except for those required for the cursors that were not closed. Unless you specified COMMIT(*CHG) or COMMIT(*CS). and this statement is not. the commitment definition is implicitly committed.COMMIT An implicit COMMIT or ROLLBACK may be performed under the following circumstances. v Regardless of the type of activation group. COMMIT(*CS). although a FETCH statement is required before a Positioned UPDATE or Positioned DELETE statement can be executed. an implicit commit is never performed. and rows inserted. Chapter 5. or updated as part of INSERT. This limit also includes: v Any rows accessed or changed through files opened under commitment control through high-level language file processing v Any rows deleted. v For non-default activation groups when the scope of the commitment definition is to the activation group: – If the activation group ends normally. DELETE. 47. you must issue a COMMIT. Effect of commit: Commit without HOLD causes the following to occur: v Connections in the release-pending state are ended. Interactive SQL. Row lock limit: A unit of work can include the processing of up to 4 million rows. Query Manager. – If the activation group ends abnormally. allowed in an application program that also specifies COMMIT(*CHG). if the scope of the commitment definition is the job. Commitment definition use: The commitment definition used by SQL is determined as follows: 46. Statements 415 . or inserted as a result of a trigger or CASCADE. or COMMIT(*RR). the commitment definition is implicitly rolled back. COMMIT(*ALL). All implicitly acquired locks are released. therefore. including rows retrieved during a SELECT or FETCH statement46. in which case these rows are not included in this total. updated. – all open cursors that were declared without the WITH HOLD clause are closed. SET NULL. deleted.47 Unaffected statements: The commit and rollback operations do not affect the DROP SCHEMA statement. v All locks acquired by the LOCK TABLE statement are released. and UPDATE statements. For existing connections: – all open cursors that were declared with the WITH HOLD clause are preserved and their current position is maintained. and non-ILE programs are examples of programs that run in the default activation group.

EXEC SQL UPDATE EMPLOYEE SET COMM = COMM . v If the activation group of the program calling SQL is not currently using a commitment definition but the job commitment definition is started. then SQL uses the job commitment definition. STRSQL. decimal(5.:AMOUNT WHERE EMPNO = :FROM_EMPNO. then SQL uses that commitment definition. v If the activation group of the program calling SQL is using the job level commitment definition. then SQL implicitly starts a commitment definition. EXEC SQL WHENEVER SQLERROR GOTO SQLERR. the LCKLVL parameter is based on the commit option in the SET OPTION statement. Use the COMMIT statement to ensure that no permanent changes are made to the database until both operations are completed successfully.2) AMOUNT.. transfer a certain amount of commission (COMM) from one employee (EMPNO) to another in the EMPLOYEE table. char FROM_EMPNO[7]. EXEC SQL UPDATE EMPLOYEE SET COMM = COMM + :AMOUNT WHERE EMPNO = :TO_EMPNO.. EXEC SQL END DECLARE SECTION.COMMIT v If the activation group of the program calling SQL is already using an activation group level commitment definition. Subtract the amount from one row and add it to the other. } WHENEVER SQLERROR CONTINUE.. v If the activation group of the program calling SQL is not currently using a commitment definition and the job commitment definition is not started.. In REXX. ROLLBACK WORK. /* continue if error on rollback */ 416 DB2 UDB for iSeries SQL Reference V5R2 . or RUNSQLSTM commands. char TO_EMPNO[7]. void main () { EXEC SQL BEGIN DECLARE SECTION. FINISHED: EXEC SQL COMMIT WORK. return. SQL uses the Start Commitment Control (STRCMTCTL) command with: – A CMTSCOPE(*ACTGRP) parameter – A LCKLVL parameter based on the COMMIT option specified on either the CRTSQLxxx. Example In a C program. SQLERR: . then SQL uses the job level commitment definition. EXEC SQL INCLUDE SQLCA. . EXEC SQL EXEC SQL return.

v TCP/IP is used with a server authorization entry for the server. Statements 417 . UNLESS: v User is specified. or a procedure if the procedure is called on a remote server. the USER clause must specify a valid user profile on the server system. In this case. Refer to “Application-Directed Distributed Unit of Work” on page 29 for more information about connection states. It is an executable statement that cannot be dynamically prepared. the server authorization entry must specify a valid user profile on the server system. Differences between the two types of statements are described in “CONNECT (Type 1) and CONNECT (Type 2) Differences” on page 845. a function. In this case. CONNECT is not allowed in a trigger. | | | | | | Invocation This statement can only be embedded within an application program or issued interactively. v It must not be followed by an indicator variable.CONNECT (Type 1) CONNECT (Type 1) The CONNECT (TYPE 1) statement connects an activation group within an application process to the identified server using the rules for remote unit of work. Authorization The privileges held by the authorization ID of the statement must include communications-level security. This server is then the current server for the activation group. This type of CONNECT statement is used if RDBCNNMTH(*RUW) was specified on the CRTSQLxxx command. (See the section about security in the Distributed Database Programming book. Chapter 5. It must not be specified in Java or REXX. Syntax CONNECT TO RESET server-name host-variable authorization authorization: USER authorization-name host-variable USING password host variable Description TO server-name or host-variable Identifies the server by the specified server name or the server name contained in the host variable.) If the server is DB2 UDB for iSeries. If a host variable is specified: v It must be a character-string variable. the user profile of the person issuing the statement must also be a valid user profile on the server system.

v If the length of the authorization name is less than the length of the host variable. which contains the password for the authorization-name that will be used to start the remote job. USING password or host-variable Identifies the password by the specified password or a host-variable. The authorization name must be left-justified within the host variable and must conform to the rules of forming an authorization name. It must not be followed by an indicator variable. If the length of the password is less than that of the host variable. it must be padded on the right with blanks. all prepared statements are destroyed. If v v v v a host-variable is specified. It must be a character-string variable. it must be padded on the right with blanks. 418 DB2 UDB for iSeries SQL Reference V5R2 . It must not be followed by an indicator variable. RESET CONNECT RESET is equivalent to CONNECT TO x where x is the local server name. If the server-name is a local relational database and an authorization-name is specified. an error occurs and the application is left in the unconnected state. If password is specified as a literal. it must be the authorization-name of the job. and all locks are released from the current connection. If the specified authorization-name is different than the authorization-name of the job. it must be a character string. The password must be left-justified within the host variable. it must be padded on the right with blanks. The maximum length is 128 characters. the specified server name or the server name contained in the host variable must identify a server described in the local directory and the activation group must be in the connectable state. or locks. When the CONNECT statement is executed. Notes | | Successful connect: If the CONNECT statement is successful: v All open cursors are closed. prepared statements. open cursors. USER authorization-name or host-variable Identifies the authorization-name by the specified authorization-name or a host-variable which contains the authorization name that will be used to start the remote job. It must be a character string variable. It must be left justified. If v v v a host-variable is specified. v If the length of the server name is less than the length of the host variable. The information is returned in the SQLCA as described above. CONNECT with no operand This form of the CONNECT statement returns information about the current server and has no effect on connection states. v The value of the server name must not contain lowercase characters.CONNECT (Type 1) v The server name must be left-justified within the host variable and must conform to the rules for forming an ordinary identifier.

If the CONNECT statement is unsuccessful because the activation group is not in the connectable state. and connected to the identified server. The SQLERRD(4) field of the SQLCA contains values indicating whether the server allows commitable updates to be performed. and all locks are released from all current and dormant connections. v Additional information about the connection is placed in the SQLERRMC field of the SQLCA. where: – ppp identifies the product as follows: ARI for DB2 for VM and VSE DSN for DB2 UDB for OS/390 and z/OS QSQ for DB2 UDB for iSeries SQL for all other DB2 UDB products – vv is a two-digit version identifier such as '07' – rr is a two-digit release identifier such as '01' – m is a one-digit modification level such as '0' For example. 48. The value 1 indicates that commitable updates can be performed. Statements 419 . An application in a connectable but unconnected state can only execute the CONNECT or SET CONNECTION statements. but unconnected state v All open cursors are closed. if the server is Version 7 of DB2 UDB for OS/390 and z/OS. and the connection: – Uses an unprotected conversation. all prepared statements are destroyed.” on page 825 Unsuccessful connect: If the CONNECT statement is unsuccessful. the SQLERRP field of the SQLCA is set to the name of the module at the application requester that detected the error. To reduce the possibility of confusion between network connections and SQL connections.CONNECT (Type 1) v The activation group is disconnected from all current and dormant connections. Chapter 5. the value of SQLERRP is 'DSN07010'. the connection state of the activation group is unchanged. the SQL program implicitly connects to a remote relational database when: – The activation group is in a connectable state. If the CONNECT statement is unsuccessful for any other reason: v The activation group remains in a connectable. even though it formally applies only to APPC connections. or – Is a local connection using the *RUW connection method. if the application requester is DB2 UDB UWO for NT the first three characters are ’SQL’. For example. “SQL Communication Area. If the server is an IBM relational database product. Refer to Appendix B. Implicit connect: v When running in the default activation group.48 or – Is a connection to an application requester driver program using the *RUW connection method. in this book the term ’conversation’ will be used to apply to network connections over TCP/IP as well as over APPC. if any. v The name of the server is placed in the CURRENT SERVER special register. For a CONNECT (Type 1) statement SQLERRD(4) will always contain the value 1. the information in the SQLERRP field has the form pppvvrrm. v Information about the server is placed in the SQLERRP and SQLERRD(4) fields of the SQLCA. Note that the first three characters of the module name identify the product.

the remote authorization-name and password to be used in connecting to a given RDB. Note: It is a good practice for the first SQL statement executed by an activation group to be the CONNECT statement. or ROLLBACK. In order for the password to be stored with the ADDSVRAUTE or CHGSVRAUTE command. When using these commands for DRDA connection. See the Distributed Database Programming book for more details. the password. CONNECT cannot execute successfully when it is preceded by any SQL statement other than CONNECT. SET CONNECTION. a 420 DB2 UDB for iSeries SQL Reference V5R2 . an implicit connect is not bound by the above restrictions. an explicit connect statement must be used. Consecutive CONNECT statements can be executed successfully because CONNECT does not remove the activation group from the connectable state. for a given user under which the implicit (or explicit) CONNECT is done. then the CONNECT statement is executed like any other CONNECT statement. implicit connect always sends the authorization-name of the application requester job and does not send passwords. execute a commit or rollback operation before a CONNECT statement is executed. RELEASE. v When running in a non-default activation group. To avoid an error.CONNECT (Type 1) – The first SQL statement in the first SQL program on the program stack is executed. If the authorization-name of the server job is different. If any previous current or dormant connections were established using protected conversations. DISCONNECT. prepared statements are not destroyed. When APPC is used for connecting to an RDB. Cursors are not closed. v If the connection identified by the server-name was established using a CONNECT (Type 2) statement. A CONNECT to either a current or dormant connection in the application group is executed as follows: v If the connection identified by the server-name was established using a CONNECT (Type 1) statement. it is very important to realize that the value of the RDB name entered into the SERVER parameter must be in UPPER CASE. the QRETSVRSEC system value must be set to ’1’ rather than the default of ’0’. refer to the SQL Programming Concepts book. For more information about implicit connect. see Example 2 under Type 2 CONNECT. and locks are not released. For more information. the SQL program implicitly connects to a remote relational database when the first SQL statement in the first SQL program for that activation group is executed. Once a connection to a relational database for a user profile is established. Use of the ADDSVRAUTE and other -SVRAUTE commands allows one to specify. then no action is taken. Connection states: For a description of connection states. When TCP/IP is used for connecting to an RDB. Either. may not be validated again on subsequent connections to the same relational database with the same user profile. see “Remote Unit of Work Connection Management” on page 27. COMMIT. or if a password must be sent. if specified. then the CONNECT (Type 1) statement will fail. Revalidation of the password depends on if the conversation is still active.

Example 2: In a C program. Examples Example 1: In a C program. EXEC SQL CONNECT TO TOROLAB. void main () { char product[4] = " ". 5) ) { strncpy(product. char userpass[129]. strcpy(userpass."TOROLAB"). see the SQL Programming Concepts book and the Distributed Database Programming book. if (strncmp(SQLSTATE. copy the 3 character product identifier of the application server to the host variable PRODUCT (CHAR(3)). Following a successful connection.sqlerrp. connect to the application server TOROLAB.CONNECT (Type 1) CONNECT (Type 2) statement must be used. EXEC SQL CONNECT TO :APP_SERVER USER :username USING :userpass. For more information about connecting to a remote relational database and the local directory."JOE")."XYZ1". EXEC SQL BEGIN DECLARE SECTION. or the connections using protected conversations must be ended by releasing the connections and successfully committing.. "00000". char APP_SERVER[19]. EXEC SQL END DECLARE SECTION.. } Chapter 5. EXEC SQL INCLUDE SQLCA. Statements 421 .3). char username[11]. strcpy(APP_SERVER. } . strcpy(username. connect to an application server whose name is stored in the host variable APP_SERVER (VARCHAR(18)). return.sqlca.

a function. the USER clause must specify a valid user profile on the server system. CONNECT is not allowed in a trigger. (See the section about security in the Distributed Database Programming book. Syntax CONNECT TO RESET server-name host-variable authorization authorization: USER authorization-name host-variable USING password host variable Description TO server-name or host-variable Identifies the server by the specified server name or the server name contained in the host variable. UNLESS: v USER is specified. Differences between the two types of statements are described in “CONNECT (Type 1) and CONNECT (Type 2) Differences” on page 845. If this is the case. This server is then the current server for the activation group. If USER is specified. Refer to “Application-Directed Distributed Unit of Work” on page 29 for more information about connection states.) If the server is DB2 UDB for iSeries. This type of CONNECT statement is used if RDBCNNMTH(*DUW) was specified on the CRTSQLxxx command. or a procedure if the procedure is called on a remote server.CONNECT (Type 2) CONNECT (Type 2) The CONNECT (Type 2) statement connects an activation group within an application process to the identified server using the rules for application directed distributed unit of work. It is an executable statement that cannot be dynamically prepared. If a host variable is specified: v It must be a character-string variable. Authorization The privileges held by the authorization ID of the statement must include communications-level security. It must not be specified in Java or REXX. the server authorization entry must specify a valid user profile on the server system. v It must not be followed by an indicator variable 422 DB2 UDB for iSeries SQL Reference V5R2 . the profile ID of the person issuing the statement must also be a valid user profile on the server system. | | | | | | Invocation This statement can only be embedded in an application program or issued interactively. v TCP/IP is used with a server authorization entry for the server.

the specified server name or the server name contained in the host variable must identify a server described in the local directory. it must be a character string. RESET CONNECT RESET is equivalent to CONNECT TO x where x is the local server name.CONNECT (Type 2) v The server name must be left-justified within the host variable and must conform to the rules for forming an ordinary identifier v If the length of the server name is less than the length of the host variable. If the length of the password is less than that of the host variable. it must be padded on the right with blanks. v The value of the server name must not contain lowercase characters. It will have one of the following values: 1 . the SQLERRD(3) field of the SQLCA will indicate the status of connection for this unit of work. open cursors.No commitable updates can be performed on the connection for this unit of work. v 2 . Statements 423 . which contains the password for the authorization-name that will be used to start the remote job. CONNECT with no operand This form of the CONNECT statement returns information about the current server and has no effect on connection states. Let S denote the specified server name or the server name contained in the host variable. prepared statements. The maximum length is 128 characters. If v v v v a host-variable is specified. USER authorization-name or host-variable Identifies the authorization-name by the specified authorization-name or a host-variable. it must be padded on the right with blanks. v If the length of the authorization name is less than the length of the host variable. In addition. The password must be left-justified within the host variable. The authorization name must be left-justified within the host variable and must conform to the rules of forming an authorization name. USING password or host-variable Identifies the password by the specified password or a host-variable. S must not identify an existing connection of the application process. v It must be a character string variable.commitable updates can be performed on the connection for this unit of work. When the CONNECT statement is executed. or locks. If password is specified as a literal. v It must not be followed by an indicator variable. v Chapter 5. which contains the authorization name that will be used to start the remote job. it must be padded on the right with blanks. If a host-variable is specified. The information is returned in the fields of the SQLCA as described above. It must not be followed by an indicator variable. It must be a character-string variable. It must be left justified.

the remote authorization-name and password to be used in connecting to a given RDB. Conversation is unprotected. The connection is either a local connection or a connection to an application requester driver program.CONNECT (Type 2) Notes Successful connect: If the CONNECT statement is successful: v A connection to server S is created and placed in the current and held states. When TCP/IP is used for connecting to an RDB. the information in the SQLERRP field has the form pppvvrrm. an implicit connect is not bound by the above restrictions. – 4 . 48 – 2 .It is unknown if commitable updates can be performed. The SQLERRD(4) field of the SQLCA contains values indicating whether server S allows commitable updates to be performed. the QRETSVRSEC system value must be set to ’1’ rather than the default of ’0’. Conversation is unprotected.No commitable updates can be performed. if any.It is unknown if commitable updates can be performed.commitable updates can be performed. Implicit connect: Implicit connect will always send the authorization-name of the application requester job and will not send passwords. When using these commands for DRDA connection. v Additional information about the connection is placed in the SQLERRMC field of the SQLCA. Unsuccessful connect: If the CONNECT statement is unsuccessful. Use of the ADDSVRAUTE and other -SVRAUTE commands allows one to specify.It is unknown if commitable updates can be performed. In order for the password to be stored with the ADDSVRAUTE or CHGSVRAUTE command. Following is a list of values and their meanings for the SQLERRD(4) field of the SQLCA on the CONNECT: – 1 . – 3 . is placed in the dormant state. for a given user under which the implicit (or explicit) CONNECT is done. v Information about server S is placed in the SQLERRP and SQLERRD(4) fields of the SQLCA. Conversation is protected. if the server is Version 7 of DB2 UDB for OS/390 and z/OS. – 5 . an explicit connect statement must be used. where: – ppp identifies the product as follows: ARI for DB2 for VM and VSE DSN for DB2 UDB for OS/390 and z/OS QSQ for DB2 UDB for iSeries SQL for all other DB2 UDB products – vv is a two-digit version identifier such as '07' – rr is a two-digit release identifier such as '01' – m is a one-digit modification level such as '0' For example. If the authorization-name of the server job is different or if a password must be sent. “SQL Communication Area. it is very 424 DB2 UDB for iSeries SQL Reference V5R2 . the value of SQLERRP is 'DSN07010'. Refer to Appendix B. the connection state of the activation group and the states of its connections are unchanged. If the server is an IBM relational database product. Conversation is unprotected. The previous connection. v S is placed in the CURRENT SERVER special register.” on page 825.

See the Distributed Database Programming book for more details. (execute statements referencing objects at SVLLAB) Example 2: Connect to a remote server specifying a userid and password. may not be validated again on subsequent connections to the same relational database with the same user profile. (set AUTHID and PASSWORD to new values) EXEC SQL CONNECT TO SVLLAB USER :AUTHID USING :PASSWORD. The first CONNECT statement creates the TOROLAB connection and the second CONNECT statement places it in the dormant state. (execute statements referencing objects at TOROLAB) EXEC SQL CONNECT TO SVLLAB. (execute SQL statements accessing data on the server) EXEC SQL COMMIT. if it has not been previously run: CHGSYSVAL SYSVAL(QRETSVRSEC) VALUE(’1’) This command adds the required server authorization entry: ADDSVRAUTE USRPRF(JOE) SERVER(TOROLAB3) USRID(ANONYMOUS) + PASSWORD(SHIBBOLETH) This statement. perform work for the user and then connect as another user to perform further work. see Example 2 under Type 2 CONNECT. EXEC SQL CONNECT TO SVLLAB USER :AUTHID USING :PASSWORD. For more information. (execute statements referencing objects at TOROLAB3) Chapter 5. EXEC SQL CONNECT TO TOROLAB. run under JOE’s user profile. Statements 425 . The RDB directory entry for TOROLAB3 specifies *IP for the connection type. Before running the application. the password. some setup must be done. Revalidation of the password depends on if the conversation is still active. refer to the SQL Programming Concepts book. This command will be required to allow server security information to be retained in OS/400. if specified. Once a connection to a relational database for a user profile is established. (execute SQL statements accessing data on the server) Example 3: User JOE wants to connect to TOROLAB3 and execute SQL statements under the user ID ANONYMOUS which has a password of SHIBBOLETH. Examples Example 1: Execute SQL statements at TOROLAB and SVLLAB.CONNECT (Type 2) important to realize that the value of the RDB name entered into the SERVER parameter must be in UPPER CASE. will now make the desired connection: EXEC SQL CONNECT TO TOROLAB3. For more information about implicit connect.

and that name is different from the authorization ID of the statement. then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority Syntax CREATE ALIAS alias-name FOR table-name view-name ( member-name ) Description alias-name Names the alias. FOR table-name or view-name Identifies the table or view at the current server for which the alias is to be defined. the alias will be created in the current library (*CURLIB). If the alias name is not a valid system name. If the table is not qualified and does not exist at the time the alias is created. *READ and *ADD to the library into which the alias is created v Administrative authority If SQL names are specified and a user profile exists that has the same name as the library into which the alias is created. The name.CREATE ALIAS CREATE ALIAS The CREATE ALIAS statement defines an alias on a table. view. the alias will be created in the schema specified by the implicit or explicit qualifier. DB2 UDB for iSeries will generate a system name. view. If not qualified. 426 DB2 UDB for iSeries SQL Reference V5R2 . the alias will be created in the same schema as the table or view for which the alias was created. the alias will be created in the schema that is specified by the qualifier. An alias name cannot be specified (an alias cannot refer to another alias). see “Rules for Table Name Generation” on page 554. table. must not be the same as an index. Invocation This statement can be embedded in an application program or issued interactively. For information on the rules for generating a name. If SQL names were specified. It is an executable statement that can be dynamically prepared. including the implicit or explicit qualifier. or member of a database file at the current server. Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v The following system authorities: – *USE to the Create DDM File (CRTDDMF) command – *EXECUTE. alias or file that already exists at the current server. If system names were specified.

If the owner of the alias is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). aliases are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema. then the qualifier is the implicit qualifier. aliases are created with the system authority of *EXCLUDE on *PUBLIC. If a member is specified. Alias attributes: An alias is created as a special form of a DDM file. the table-name or view-name is qualified by the library in which the alias is created. the owner of the alias is the user profile or group user profile of the job executing the statement. If system names were specified and the table-name or view-name is not qualified and does not exist when the alias is created. an error is returned. the owner of the alias is the user profile or group user profile of the job executing the statement. An alias created over a distributed table is only created on the current server. | | | An alias can be defined to reference either the system name or SQL name.CREATE ALIAS The table-name or view-name need not identify a table or view that exists at the time the alias is created. If system names are used. *FIRST is used. Chapter 5. Notes The Override Database File (OVRDBF) CL command allows the database manager to process individual members of a database file. member-name Identifies a member of a database file. If the table or view does not exist when the alias is created. However. since system names are generated during create processing. Otherwise. it is recommended that the SQL name be specified. see the DB2 Multisystem book. Creating an alias over a member of a database file. If system names were specified. For more information about distributed tables. Statements 427 . you can only use the alias in data manipulation (DML) SQL statements. If the table or view does not exist when the alias is used. These keywords are non-standard and should not be used: v The keyword SYNONYM can be used as a synonym for ALIAS. If SQL names were specified and the table-name or view-name was not qualified. is easier and performs better by eliminating the need to perform the override. For more information. | | | | Alias authority: If SQL names are used. a warning is returned. that group profile will also have authority to the alias. however. | | | | Alias ownership: If SQL names were specified. If a member name is not specified. | | | | Keyword Synonym: The following keywords are synonyms supported for compatibility to prior releases. see “Naming Conventions” on page 45. the owner of the alias is the user profile with the same name as the schema into which the alias is created.

CREATE ALIAS SALES_JANUARY FOR SALES(JANUARY) 428 DB2 UDB for iSeries SQL Reference V5R2 .CREATE ALIAS Examples Example 1: Create an alias named CURRENT_PROJECTS for the PROJECT table. The sales table has 12 members (one for each month of the year). CREATE ALIAS CURRENT_PROJECTS FOR PROJECT Example 2: Create an alias named SALES_JANUARY on the JANUARY member of the SALES table.

v It has been granted the INSERT privilege on the table. Statements 429 . Successful execution of the statement also generates: v A function to cast from the distinct type to its source type v A function to cast from the source type to its distinct type v As appropriate. Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v The system authorities *EXECUTE.CREATE DISTINCT TYPE CREATE DISTINCT TYPE The CREATE DISTINCT TYPE statement defines a distinct type at the current server. and that name is different from the authorization ID of the statement. or v It has been granted the system authorities of *OBJOPR and *ADD on the table. and – The system authority *EXECUTE on library QSYS2 v Administrative authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. A distinct type is always sourced on one of the built-in data types. Invocation This statement can be embedded in an application program or issued interactively. and v Administrative authority The privileges held by the authorization ID of the statement must include at least one of the following: v For the SYSTYPES catalog table: – The INSERT privilege on the table. If SQL names are specified and a user profile exists that has the same name as the library into which the distinct type is created. then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority Syntax DISTINCT CREATE AS built-in-type WITH COMPARISONS TYPE distinct-type-name Chapter 5. *READ and *ADD to the library into which the distinct type is created. It is an executable statement that can be dynamically prepared. support for the use of comparison operators with the distinct type.

The name.CREATE DISTINCT TYPE built-in-type: | SMALLINT INTEGER INT BIGINT (5. the distinct type will be created in the schema specified by the implicit or explicit qualifier. the distinct type will be created in the current library (*CURLIB). the distinct type will be created in the schema that is specified by the qualifier. If not qualified. must not be the same as a distinct type that already exists at the current server. If SQL names were specified. 430 DB2 UDB for iSeries SQL Reference V5R2 . If system names were specified.0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( 1 ) CHARACTER CHAR CHARACTER CHAR VARCHAR ( integer ) VARYING ( integer ) allocate-clause ( 1M CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ) ) K M G allocate-clause FOR SBCS DATA FOR MIXED DATA CCSID integer FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer . including the implicit or explicit qualifier.0 ( integer . integer ) ( integer ( 1 ) GRAPHIC ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( CCSID integer ) allocate-clause ) allocate-clause 1M ) ) K M G allocate-clause integer DATE ( 0 ) TIME ( 6 TIMESTAMP ( DATALINK ( ROWID integer ) allocate-clause CCSID integer 200 ) ) Description distinct-type-name Names the distinct type.

it must be cast to a built-in type. If the distinct type is sourced on a string data type. WITH COMPARISONS is the default. or any of the following system-reserved keywords even if you specify them as delimited identifiers. = <= ¬< ALL AND ANY BETWEEN BOOLEAN CASE CAST CHECK DISTINCT EXCEPT EXISTS < <> != FALSE FOR FROM IN IS LIKE MATCH NODENAME NODENUMBER NOT NULL > ¬= !< ONLY OR OVERLAPS PARTITION POSITION RRN SELECT SIMILAR SOME STRIP SUBSTRING >= ¬< !> TABLE THEN TRIM TRUE TYPE UNIQUE UNKNOWN WHEN | | If a qualified distinct-type-name is specified. For more information about data types. the default attributes of the data type as shown in the syntax diagram are implied. For portability of applications across platforms. Service programs are not created for these comparison functions. built-in-data-type Specifies the built-in data type used as the basis for the internal representation of the distinct type. or SYSIBM. Chapter 5. or scale attributes. In order to use the LIKE predicate on a distinct type. use the following recommended data type names: v DOUBLE or REAL instead of FLOAT. distinct-type-name must not be the name of a built-in data type. see “Rules for Table Name Generation” on page 554. Comparison functions will be generated for all source types with the exception of a DATALINK whether or not WITH COMPARISONS is specified.CREATE DISTINCT TYPE If the distinct type name is not a valid system name. v DECIMAL instead of NUMERIC. QSYS2. a CCSID is associated with the distinct data type at the time the distinct type is created. See “CREATE TABLE” on page 526 for a more complete description of each built-in data type. 49. If you do not specify a specific value for the data types that have length.49 For compatibility with other DB2 products. For information on the rules for generating a name. precision. WITH COMPARISONS Specifies that system-generated comparison functions are to be created for comparing two instances of the distinct type. The comparison functions do not support the LIKE predicate. QTEMP. Statements 431 . These comparison functions are not registered in the SYSROUTINES catalog table. WITH COMPARISONS should be specified. the schema name cannot be QSYS. DB2 UDB for iSeries will generate a system name. see “CREATE TABLE” on page 526.

T_SHOESIZE 432 DB2 UDB for iSeries SQL Reference V5R2 . In cases in which a length. The cast functions are created as if the following statements were executed (except that the service programs are not created.T_SHOESIZE) RETURNS VARCHAR(2) FUNCTION CLAIRE.CREATE DISTINCT TYPE Notes Additional Generated Functions: The successful execution of the CREATE DISTINCT TYPE statement causes the database manager to generate the following cast functions: v One function to convert from the distinct type to the source type v One function to convert from the source type to the distinct type v One function to convert from INTEGER to the distinct type if the source type is SMALLINT v One function to convert from DOUBLE to the distinct type if the source type is REAL v One function to convert from VARCHAR to the distinct type if the source type is CHAR v One function to convert from VARGRAPHIC to the distinct type if the source type is GRAPHIC. precision. precision.T_SHOESIZE AS VARCHAR(2) WITH COMPARISONS When the statement is executed.T_SHOESIZE (VARCHAR(2) RETURNS CLAIRE. The name of the cast function that converts from the source type to the distinct type is the name of the distinct type. and scale. For example.VARCHAR (CLAIRE. VARCHAR converts from the distinct type to the source type. assume that a distinct type named T_SHOESIZE is created with the following statement: CREATE DISTINCT TYPE CLAIRE. the unqualified name of the cast function that converts from the distinct type to the source type is simply the name of the source data type. The data type of the value that the cast function returns includes any length. The cast functions that are generated are created in the same schema as that of the distinct type. so you cannot grant or revoke privileges to these functions): CREATE FUNCTION source-type-name (distinct-type-name) RETURNS source-type-name CREATE FUNCTION distinct-type-name (source-type-name) RETURNS distinct-type-name | | | | Names of the Generated Cast Functions: Table 44 on page 433 contains details about the generated cast functions. precision. or scale is specified for the source data type in the CREATE DISTINCT TYPE statement. or scale values that were specified for the source data type on the CREATE DISTINCT TYPE statement. FUNCTION CLAIRE. the database manager also generates the following cast functions. The input parameter of the cast function has the same data type as the source data type. including the length. A function with the same name and same function signature must not already exist in the current server. The unqualfied name of the cast function that converts from the distinct type to the source type is the name of the source data type. and T_SHOESIZE converts from the source type to the distinct type.

CAST Functions on Distinct Types Source Type Name SMALLINT Function Name distinct-type-name distinct-type-name SMALLINT INTEGER distinct-type-name INTEGER BIGINT distinct-type-name BIGINT DECIMAL distinct-type-name DECIMAL NUMERIC distinct-type-name NUMERIC REAL or FLOAT(n) where n <= 24 distinct-type-name distinct-type-name REAL DOUBLE or DOUBLE PRECISION or FLOAT(n) where n > 24 distinct-type-name Parameter Type SMALLINT INTEGER distinct-type-name INTEGER distinct-type-name BIGINT distinct-type-name DECIMAL(p.s) distinct-type-name NUMERIC(p. For each built-in data type that can be the source data type for a distinct type.CREATE DISTINCT TYPE Notice that function VARCHAR returns a value with a data type of VARCHAR(2) and that function T_SHOESIZE has an input parameter with a data type of VARCHAR(2). The cast functions that are generated for a distinct type are implicitly dropped when the distinct type is dropped with the DROP statement. Statements 433 . the data types of the input parameters.s) distinct-type-name distinct-type-name REAL distinct-type-name DOUBLE CHAR distinct-type-name CHAR distinct-type-name VARCHAR distinct-type-name VARCHAR CLOB distinct-type-name CLOB GRAPHIC distinct-type-name GRAPHIC distinct-type-name VARGRAPHIC distinct-type-name VARGRAPHIC distinct-type-name CHAR(n) distinct-type-name VARCHAR(n) VARCHAR(n) distinct-type-name CLOB(n) distinct-type-name GRAPHIC(n) distinct-type-name VARGRAPHIC(n) VARGRAPHIC(n) distinct-type-name DOUBLE distinct-type-name CHAR(n) distinct-type-name distinct-type-name VARCHAR(n) distinct-type-name CLOB(n) distinct-type-name GRAPHIC(n) distinct-type-name distinct-type-name VARGRAPHIC(n) Chapter 5.s) distinct-type-name REAL DOUBLE distinct-type-name DOUBLE Return Type distinct-type-name distinct-type-name SMALLINT distinct-type-name INTEGER distinct-type-name BIGINT distinct-type-name DECIMAL(p. Table 44.s) distinct-type-name NUMERIC(p. and the data types of the values that the functions returns. A generated cast function cannot be explicitly dropped. the following table gives the names of the generated cast functions.

CAST Functions on Distinct Types (continued) Source Type Name DBCLOB Function Name distinct-type-name DBCLOB BLOB distinct-type-name BLOB DATE distinct-type-name DATE TIME distinct-type-name TIME TIMESTAMP distinct-type-name TIMESTAMP DATALINK distinct-type-name DATALINK Parameter Type DBCLOB(n) distinct-type-name BLOB(n) distinct-type-name DATE distinct-type-name TIME distinct-type-name TIMESTAMP distinct-type-name DATALINK distinct-type-name ROWID distinct-type-name Return Type distinct-type-name DBCLOB(n) distinct-type-name BLOB(n) distinct-type-name DATE distinct-type-name TIME distinct-type-name TIMESTAMP distinct-type-name DATALINK distinct-type-name ROWID | | ROWID distinct-type-name ROWID Notes: * Conversion is only supported for UCS-2 graphic. the owner of the distinct type is the user profile or group user profile of the job executing the statement. which is based on the 434 DB2 UDB for iSeries SQL Reference V5R2 . If the owner of the distinct type is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). distinct types are created with the system authority of *EXCLUDE on *PUBLIC. If system names are used. A built-in function can be used on a distinct type only after a sourced user-defined function. Built-in Functions: The functions described in the above table are the only functions that are generated automatically when distinct types are defined. NUMERIC and FLOAT are not recommended when creating a distinct type for a portable application. and so on) are automatically supported for the distinct type. Otherwise.CREATE DISTINCT TYPE Table 44. LENGTH. If system names were specified. | | | | Distinct type authority: If SQL names are used. none of the built-in functions (AVG. Consequently. the owner of the distinct type is the user profile or group user profile of the job executing the statement. that group profile will also have authority to the distinct type. the owner of the distinct type is the user profile with the same name as the schema into which the distinct type is created. MAX. DECIMAL and DOUBLE should be used instead. Distinct type attributes: A distinct type is created as a *SQLUDT object. Only a DATALINK can be cast to a DATALINK type. | | | | Distinct type ownership: If SQL names were specified. distinct types are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema.

The schema name of the distinct type must be included in the distinct type for successful use of these operators and cast functions in SQL statements. v Function CLAIRE. CREATE DISTINCT TYPE CLAIRE.T_DEPARTMENT takes a CHAR(3) as input and returns a value with distinct type T_DEPARTMENT. CREATE DISTINCT TYPE MILES AS DOUBLE WITH COMPARISONS The successful execution of this statement also generates two cast functions. Statements 435 . Example 2: Create a distinct type named MILES that is sourced on the built-in DOUBLE data type.CREATE DISTINCT TYPE built-in function. v Function CLAIRE.T_DEPARTMENT AS CHAR(3) WITH COMPARISONS The successful execution of this statement also generates three cast functions: v Function CLAIRE. CREATE DISTINCT TYPE SHOESIZE AS INTEGER WITH COMPARISONS The successful execution of this statement also generates two cast functions. See “Extending or Overriding a Built-in Function” under “CREATE FUNCTION” on page 436. Example 3: Create a distinct type T_DEPARTMENT that is sourced on the built-in CHAR data type. and function MILES(DOUBLE) returns a value with distinct type MILES. Function DOUBLE(MILES) returns a value with data type DOUBLE. has been created for the distinct type. Examples Example 1: Create a distinct type named SHOESIZE that is sourced on the built-in INTEGER data type. Function INTEGER(SHOESIZE) returns a value with data type INTEGER. and function SHOESIZE(INTEGER) returns a value with distinct type SHOESIZE.T_DEPARTMENT takes a VARCHAR(3) as input and returns a value with distinct type T_DEPARTMENT. Chapter 5.CHAR takes a T_DEPARTMENT as input and returns a value with data type CHAR(3).

QSYS. or the result of a column function. v External Table The function is written in a programming language such as C or Java and returns a set of rows. or SYSIBM. or SQL) that already exists at the current server. The unqualified function name must not be one of the following names reserved for system use even they are specified as delimited identifiers: = <= ¬< ALL AND ANY BETWEEN BOOLEAN CASE CAST CHECK DISTINCT EXCEPT EXISTS < <> != FALSE FOR FROM IN IS LIKE MATCH NODENAME NODENUMBER NOT NULL > ¬= !> ONLY OR OVERLAPS PARTITION POSITION RRN SELECT SIMILAR SOME STRIP SUBSTRING >= ¬< !< TABLE THEN TRIM TRUE TYPE UNIQUE UNKNOWN WHEN 436 DB2 UDB for iSeries SQL Reference V5R2 . QTEMP. The external program is referenced by a function defined at the current server along with various attributes of the function. The external program is referenced by a function defined at the current server along with various attributes of the function. See “CREATE FUNCTION (SQL Table)” on page 488. See “CREATE FUNCTION (External Table)” on page 456. The following types of functions can be defined: v External Scalar The function is written in a programming language such as C or Java and returns a scalar value. the schema-name cannot be QSYS2. v Sourced The function is implemented by invoking another function (built-in. The function body is defined at the current server along with various attributes of the function. The function body is defined at the current server along with various attributes of the function. If function-name is not qualified. A sourced function can return a scalar result. See “CREATE FUNCTION (External Scalar)” on page 440. See “CREATE FUNCTION (SQL Scalar)” on page 479. it is implicitly qualified with the default schema name.CREATE FUNCTION CREATE FUNCTION The CREATE FUNCTION statement defines a user-defined function at the current server. external. The function inherits attributes of the underlying source function. v SQL Scalar The function is written exclusively in SQL and returns a scalar value. See “CREATE FUNCTION (Sourced)” on page 470. Notes Choosing the Schema and Function Name: If a qualified function name is specified. sourced. v SQL TABLE The function is written exclusively in SQL and returns a set of rows.

the number of parameters. However. and more significantly. Based on the rules of promotion. a constant that is one of the input arguments to the function might have a built-in data type that is different from the data type that the function expects. scale. precision. schema name. A function can have no input parameters. which might have different representations on different platforms: – FLOAT. Statements 437 . The AS LOCATOR clause has no effect on determining whether data types can be promoted. This can be useful when the value of the parameter is very large. In this case. For example. a schema must not contain two functions with the same name that have the same data types for all of their corresponding data types. which is used in function resolution. or CCSID) must not identify a user-defined function that exists at the current server. Chapter 5. and the data type each parameter (without regard for other attributes such as length. the rules of promotion that can affect the values of the parameters need to be considered. might not be promotable to that expected data type. The combination of name.CREATE FUNCTION Defining the Parameters: The input parameters for the function are specified as a list within parenthesis. The return type has no impact on the determining uniqueness of a function. v Choosing Data Types for Parameters: When choosing the data types of the input and result parameters for a function. do not use the following data types. nor does it affect the function signature. The AS LOCATOR clause specifies that a locator to the value of the parameter is passed instead of the actual value. – NUMERIC. for example: CREATE FUNCTION WOOFER() The data type of the result of the function is specified in the RETURNS clause for the function. an empty set of parenthesis must be specified. v Specifying AS LOCATOR for a Parameter: Passing a locator instead of a value can result in fewer bytes being passed in or out of the function. Use DOUBLE or REAL instead. Use DECIMAL instead. Determining the Uniqueness of Functions in a Schema: The same name can be used for more than one function in a schema if the function signature of each function is unique. Two different schemas can each contain a function with the same name that have the same data types for all of their corresponding data types. See “Promotion of Data Types” on page 76. The maximum number of parameters allowed in CREATE FUNCTION is 90. we recommend using the following data types for parameters: – INTEGER instead of SMALLINT – DOUBLE instead of REAL – VARCHAR instead of CHAR – VARGRAPHIC instead of GRAPHIC For portability of functions across platforms that are not DB2 UDB for iSeries. Specify AS LOCATOR only for parameters with a LOB data type or a distinct type based on a LOB data type. The function signature is the qualified function name combined with the number and data types of the input parameters. AS LOCATOR can not be specified for SQL functions.

If the SPECIFIC clause is not specified. it is recommended that a specific name also be specified. as are DECIMAL(11.2). The database manager considers the synonyms of data types a match. If a schema name is not specified on CREATE FUNCTION. Assume that the following statements are executed to create four functions in the same schema. REAL and FLOAT.. including the schema name must not identify the specific name of another function or procedure that exists at the current server. the following are considered to be the same type: CHAR and GRAPHIC. the database manager does not consider any length. CHAR(40) . and a unique function signature. a specific name is generated. For example.3).2)) . and DECIMAL(4. If a schema name is specified. An error is returned if the signature of the function being created is a duplicate of a signature for an existing user-defined function with the same name and schema. CREATE FUNCTION ANGLE (DEC(10. or commenting on the function. CREATE FUNCTION ANGLE (DECIMAL(12.CREATE FUNCTION When determining whether corresponding data types match. VARCHAR and VARGRAPHIC. Furthermore. For example. For example. and DOUBLE and FLOAT) are considered a match.. the signature for the new user-defined function named ROUND is different from all the function signatures supported by the built-in ROUND function. For example. v Overriding a Built-in Function: Create the new user-defined function with the same name and signature as an existing built-in function. The new function has the same name and data type as the corresponding parameters of the built-in function but implements different logic.. The second and fourth statements fail because they create functions that are duplicates of the functions that the first and third statements created. the character and graphic types are considered to be the same. In this case. CHAR(13) and GRAPHIC(8) are considered to be the same type. However. CREATE FUNCTION PART (INT. CREATE FUNCTION PART (INTEGER.. CHAR(15) . The specific name is implicitly or explicitly qualified with a schema name.7)) . Specifying a Specific Name for a Function: When defining multiple functions with the same name and schema (with different parameter lists). the function cannot be invoked by its specific name. the signature for the new user-defined function named ROUND will be the same as a signature that is supported by the built-in ROUND function. The specific name can be used to uniquely identify the function such as when sourcing on this function. a user-defined function similar to the built-in function ROUND that accepts the distinct type MONEY as input rather than the built-in numeric types might be necessary.. Extending or Overriding a Built-in Function: Giving a user-defined function the same name as a built-in function is not a recommended practice unless the functionality of the built-in function needs to be extended or overridden. In this case. precision. v Extending the Functionality of Existing Built-in Functions: Create the new user-defined function with the same name as the built-in function. or scale attributes in the comparison. The name. 438 DB2 UDB for iSeries SQL Reference V5R2 . it must be the same as the explicit or implicit schema name of the function name.. Therefore... it is the same as the explicit or implicit schema name of the function name (function-name). and CLOB and DBCLOB. dropping the function. a user-defined function similar to the built-in function ROUND that uses different rules for rounding than the built-in ROUND function might be necessary. CHAR(8) and CHAR(35) are considered to be the same.

or perhaps even worse. appear to run successfully but provide a different result if the user-defined function is chosen by the data base manager rather than the built-in function. Chapter 5. an application that uses the unqualified function name and was previously successful using the built-in function of that name might fail. Special Registers in Functions: The settings of the special registers of the invoker are inherited by the function on invocation and restored upon return to the invoker. Statements 439 .CREATE FUNCTION Once a built-in function has been overridden.

the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: 50. the privileges held by the authorization ID of the statement must include at least one of the following: v For the external program or service program that is referenced in the SQL statement: – The system authority *EXECUTE on the library that contains the external program or service program. A user-defined external scalar function returns a single value each time it is invoked. then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority | | | If a distinct type is referenced. Authorization The privileges held by the authorization id of the statement must include at least one of the following: v For the SYSFUNCS catalog view and SYSPARMS catalog table50: – The INSERT privilege on the table. v Administrative Authority If SQL names are specified and a user profile exists that has the same name as the library into which the function is created. If user does not have this authority. The system needs this authority to update the program object to contain the information necessary to save/restore the function to another system. v It has been granted the INSERT privilege on the table. but the program object is not updated. and – The system authority *EXECUTE on library QSYS2 v Administrative Authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. The GRTOBJAUT CL command must be used to grant these privileges. or issued interactively. – The system authority *EXECUTE on the external program or service program.CREATE FUNCTION (External Scalar) CREATE FUNCTION (External Scalar) This CREATE FUNCTION (External Scalar) statement creates an external scalar function at the current server. or v It has been granted the system authorities of *OBJOPR and *ADD on the table. It is an executable statement that can be dynamically prepared. Invocation This statement can be embedded in an application program. and – The system authority *CHANGE on the program or service program. If the external program or service program exists. 440 DB2 UDB for iSeries SQL Reference V5R2 . the function is still created. and that name is different from the authorization ID of the statement.

CREATE FUNCTION (External Scalar) | | | | | | | | | – The USAGE privilege on the distinct type. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type. and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. v It was granted the USAGE privilege to the distinct type. Syntax CREATE FUNCTION function-name ( . Statements 441 . parameter-declaration RETURNS data-type2 AS LOCATOR data-type3 CAST FROM data-type4 AS LOCATOR option-list ) parameter-declaration: data-type1 parameter-name AS LOCATOR Chapter 5.

CREATE FUNCTION (External Scalar) data-type1. data-type4: built-in-type distinct-type-name built-in-type: | SMALLINT INTEGER INT BIGINT (5. data-type2.0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( CHARACTER CHAR CHARACTER CHAR VARCHAR 1 ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer . integer ) ( integer ) VARYING ( integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 GRAPHIC ) CCSID integer ) ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 ) TIMESTAMP ROWID 442 DB2 UDB for iSeries SQL Reference V5R2 .0 ( integer . data-type3.

Chapter 5. scale. Description function-name Names the user-defined function. If there is no current library. or CCSID attributes of the data type) must not identify a user-defined function that exists at the current server. precision. the number of parameters.CREATE FUNCTION (External Scalar) option-list: PARAMETER STYLE (1) LANGUAGE C C++ CL COBOL COBOLLE FORTRAN JAVA PLI RPG RPGLE PARAMETER STYLE DB2GENERAL DB2SQL GENERAL GENERAL WITH NULLS JAVA SQL NOT DETERMINISTIC SPECIFIC specific-name IS DETERMINISTIC READS SQL DATA NO SQL CONTAINS SQL MODIFIES SQL DATA CALLED ON NULL INPUT RETURNS NULL ON NULL INPUT STATIC DISPATCH NO DBINFO DBINFO EXTERNAL ACTION NO EXTERNAL ACTION FENCED NOT FENCED NO FINAL CALL FINAL CALL ALLOW PARALLEL DISALLOW PARALLEL NO SCRATCHPAD 100 SCRATCHPAD integer EXTERNAL EXTERNAL NAME external-program-name Notes: 1 The optional clauses can be specified in a different order. and the data type of each parameter (without regard for any length. the function will be created in the schema that is specified by the qualifier. the function will be created in the schema specified by the implicit or explicit qualifier. schema name. For system naming. the function will be created in QGPL. For SQL naming. If no qualifier is specified. Statements 443 . The combination of name. the function will be created in the current library (*CURLIB).

If a CCSID is specified. If a CCSID is not specified. AS LOCATOR Specifies that a locator to the value of the parameter is passed to the function instead of the actual value. RETURNS Specifies the output of the function. and message text. If a CCSID is not specified. as well as any optional parameters are included. the CCSID is determined by the default CCSID at the current server at the time the function is invoked. data-type2 Specifies the data type and attributes of the output. the result returned is assumed to be encoded in that CCSID. (parameter-declaration. Although not required. the parameter will be converted to that CCSID prior to passing it to the function. or DataLink) or a distinct type (that is not based on a DataLink). | | Certain function names are reserved for system use. If a CCSID is specified. the input and result parameters specified and the implicit parameters for indicators. Do not specify the same name more than once. For external functions created with PARAMETER STYLE SQL. See “Specifying AS LOCATOR for a parameter” in “CREATE FUNCTION” on page 436 for more information. You can specify any built-in data type (except LONG VARCHAR. There must be one entry in the list for each parameter that the function expects to receive.. The maximum number of parameters is also limited by the maximum number of parameters allowed by the licensed program that is used to compile the external program. function name.. For more information see “Choosing the Schema and Function Name” on page 436. LONG VARGRAPHIC. v If AS LOCATOR is not specified. specific name. Specify AS LOCATOR only for parameters with a LOB data type or a distinct type based on a LOB data type. you can give each parameter a name. parameter-name Specifies the name of the input parameter. SQLSTATE. the data is converted to the specified CCSID.. data-type1 Specifies the number of input parameters of the function and the data type of each input parameter. v If AS LOCATOR is specified and the CCSID of the data the locator points to is encoded in a different CCSID. 444 DB2 UDB for iSeries SQL Reference V5R2 .CREATE FUNCTION (External Scalar) In general. you can give each parameter a name. more than one function can have the same name if the function signature of each function is unique. All the parameters for a function are input parameters.) Specifies the number of input parameters of the function and the data type of each parameter. Although not required. The maximum number of parameters allowed in CREATE FUNCTION is 90.

(For information on casting data types. All programs must be designed to run in the server’s environment. the data the locator points to is converted to the CCSID of the job. In this case. See “Specifying AS LOCATOR for a parameter” in “CREATE FUNCTION” on page 436 for more information. the result returned is assumed to be encoded in the CCSID of the job (or associated graphic CCSID of the job for graphic string return values). consider using CCSID 13488 (UCS-2 graphic string data). see the description of data-type2 above. data-type3 CAST FROM data-type4 Specifies the data type and attributes of the output (data-type4) and the data type in which that output is returned to the invoking statement (data-type3). To avoid any potential loss of characters during the conversion. The value for data-type3 can be any built-in data type or distinct type. v If AS LOCATOR is specified. This is especially important if the data type is graphic string data. For CCSID information. SPECIFIC specific-name Specifies a unique name for the function. See “Specifying AS LOCATOR for a parameter” in “CREATE FUNCTION” on page 436 for more information. see “Casting Between Data Types” on page 78). Specify AS LOCATOR only if the result of the function has a LOB data type or a distinct type based on a LOB data type. The two data types can be different. the function returns a CHAR(10) value. Statements 445 . See “Specifying a Specific Name for a Function” in “CREATE FUNCTION” on page 436. Specify AS LOCATOR only if the result of the function has a LOB data type or a distinct type based on a LOB data type. AS LOCATOR Specifies that the function returns a locator to the value rather than the actual value. which the database manager converts to a DATE value and then passes to the statement that invoked the function: CREATE FUNCTION GET_HIRE_DATE (CHAR6) RETURNS DATE CAST FROM CHAR(10) The value of data-type4 must not be a distinct type and must be castable to data-type3. for the following definition. if the CCSID of the data the locator points to is encoded in a different CCSID. the LANGUAGE is determined from the program attribute information associated with the external program at the time the function is created. AS LOCATOR Specifies that the function returns a locator to the value rather than the actual value.CREATE FUNCTION (External Scalar) v If AS LOCATOR is not specified. If LANGUAGE is not specified. LANGUAGE Specifies the language interface convention to which the function body is written. For example. consider explicitly specifying a CCSID that can represent any characters that will be returned from the function. Chapter 5. The language of the program is assumed to be C if: v The program attribute information associated with the program does not identify a recognizable language v The program cannot be found C The external program is written in C.

which must be a public static method of the specified Java class PLI The external program is written in PL/I. FORTRAN The external program is written in FORTRAN. or NO SQL Specifies whether the function can execute any SQL statements and. if so. READS SQL DATA The function does not execute SQL statements that modify data. The database manager will call the user-defined function. READS SQL DATA. MODIFIES SQL DATA The function can execute any SQL statement except those statements that are not supported in any function. “Characteristics of SQL Statements. DETERMINISTIC or NOT DETERMINISTIC Specifies whether the function is deterministic. | | | | | NOT DETERMINISTIC Specifies that the function will not always return the same result from successive function invocations with identical input arguments. RPGLE The external program is written in ILE RPG. NOT DETERMINISTIC should be specified if the function contains a reference to a special register or a non-deterministic function.” on page 835 for a detailed list of the SQL statements that can be executed under each data access indication. what type. NO SQL The function does not execute SQL statements. CL The external program is written in CL or ILE CL. DETERMINISTIC Specifies that the function will always return the same result from successive invocations with identical input arguments. The database manager verifies that the SQL issued by the function is consistent with this specification. COBOLLE The external program is written in ILE COBOL. JAVA The external program is written in JAVA.CREATE FUNCTION (External Scalar) C++ The external program is written in C++. RPG The external program is written in RPG. 446 DB2 UDB for iSeries SQL Reference V5R2 . See Appendix C. | | | | | | | | | | | | | | | CONTAINS SQL. CONTAINS SQL The function does not execute SQL statements that read or modify data. COBOL The external program is written in COBOL. MODIFIES SQL DATA.

or all. CALLED ON NULL INPUT Specifies that the function is to be invoked. there is one scratchpad. The result is the null value. FENCED The function will run in a separate thread.000. NO EXTERNAL ACTION The function does not perform an external action. EXTERNAL ACTION should be specified if the function contains a reference to another function that has an external action. For each reference to the function in an SQL statement. Thus. three scratchpads are allocated for the three references to UDFX in the following SQL statement: Chapter 5. NOT FENCED functions can keep SQL cursors open across individual calls to the function. the cursor position will also be preserved between calls to the function. SCRATCHPAD integer Specifies that the function requires a persistent memory area of length integer. EXTERNAL ACTION The function performs some external action (outside the scope of the function program). RETURNS NULL ON INPUT Specifies that the function is not invoked if any of the input arguments is null. It need not be called with each successive function invocation. argument values are null. If the memory area is not specified. If DISALLOW PARALLEL is specified. assuming that function UDFX was defined with the SCRATCHPAD keyword. the function must be invoked with each successive function invocation. The function can return a null or nonnull value. NOT FENCED The function may run in the same thread as the invoking SQL statement. RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT Specifies whether the function is called if any of the input arguments is null at execution time. For example. if any. a pointer is passed following the required parameters that points to a static storage area. The scope of a scratchpad is the SQL statement. The integer can range from 1 to 16. If parameter style DB2SQL is specified. If PARALLEL is specified. making the function responsible for testing for null argument values.CREATE FUNCTION (External Scalar) | | | | | | | | | | FENCED or NOT FENCED Specifies whether the function will run in the same thread as the invoking SQL statement or in a separate thread. only 1 memory area will be allocated for the function.000. Since cursors can be kept open. This parameter implies that the function SCRATCHPAD Specifies whether the function requires a static memory area. a memory area is allocated for each user-defined function reference in the statement. | | | | | | | | | | | | EXTERNAL ACTION or NO EXTERNAL ACTION Specifies whether the function contains an external action. the size of the area is 100 bytes. Statements 447 .

SQL arguments are passed and the function is expected to return a result. A final call occurs at these times: v End of statement: When the cursor is closed for cursor-oriented statements. v End of transaction: When normal end of statement processing does not occur. for some reason. FINAL CALL is only allowed with PARAMETER STYLE DB2SQL or PARAMETER STYLE DB2GENERAL. the function receives an additional argument that specifies the type of call. To differentiate between final calls and other calls. SCRATCHPAD is only allowed with PARAMETER STYLE DB2SQL or PARAMETER STYLE DB2GENERAL. the logic of an application. or the execution of the statement has completed. For example. bypasses closing the cursor. one scratchpad is allocated for each parallel task of each reference to the function in the SQL statement. v End of a parallel task: When the function is executed by parallel tasks. FINAL CALL Specifies that a final call is made to the function. This can lead to unpredictable results. normal call. Final Call Specifies the last call to the function to enable the function to free resources. A final call is not a normal call. Normal Call Specifies that SQL arguments are passed and the function is expected to return a result. NO SCRATCHPAD Specifies that the function does not require a persistent memory area. Specify the DISALLOW PARALLEL clause for functions that will not work correctly with parallelism. the count reflects the number of invocations done by the parallel task and not the SQL statement. | | | | | | | | | | | | | | | | | | | | | The types of calls are: First Call Specifies the first call to the function for this reference to the function in this SQL statement. if a function uses the scratchpad to count the number of times that it is invoked.CREATE FUNCTION (External Scalar) SELECT A. NO FINAL CALL Specifies that a final call is not made to the function. If PARAMETER STYLE DB2SQL is specified and FINAL CALL is specified. UDFX(A) FROM TABLEB WHERE UDFX(A) > 103 OR UDFX(A) < 19 If the function is run under parallel tasks. 448 DB2 UDB for iSeries SQL Reference V5R2 . or final call. the database manager attempts to make the final call. A first call is a normal call. For example. If an error occurs. FINAL CALL Specifies whether the function requires special call indication. an additional parameter is passed to the function indicating first call.

if you specify one or more of the following clauses: v NOT DETERMINISTIC v EXTERNAL ACTION v FINAL CALL v MODIFIES SQL DATA v SCRATCHPAD Otherwise. Table 45 contains a description of the DBINFO structure. if a function sends a note for each final call to it. ALLOW PARALLEL Specifies that the function can be run in parallel. ALLOW PARALLEL is the default. The default is DISALLOW PARALLEL. Commitable operations should not be performed during a FINAL CALL. The run-time authorization ID. because the FINAL CALL may occur during a close invoked as part of a COMMIT operation. DBINFO fields Field Relational database Authorization ID Data Type VARCHAR(128) VARCHAR(128) Description The name of the current server. DBINFO Specifies whether or not the function requires the database information be passed. If a commit operation occurs while a cursor defined as WITH HOLD is open. Chapter 5. a final call is made regardless of whether a cursor defined as WITH HOLD is open. Table 45.H. Statements 449 . If a commit occurs at the end of a parallel task. DBINFO Specifies that the database manager should pass a structure containing status information to the function. a final call is made when the cursor is closed or the application ends. Specify the DISALLOW PARALLEL clause for functions that have inappropriate actions when executed in parallel. For example. DISALLOW PARALLEL Specifies that the function cannot be run in parallel.CREATE FUNCTION (External Scalar) | | | | | | | | | | | Some functions that use a final call can receive incorrect results if parallel tasks execute the function. one note is sent for each parallel task instead of once for the function. Detailed information about the DBINFO structure can be found in include file SQLUDF in QSYSINC. PARALLEL Specifies whether the function can be run in parallel. DBINFO is only allowed with PARAMETER STYLE DB2SQL or PARAMETER STYLE DB2GENERAL.

RELEASE. Target column VARCHAR(128) VARCHAR(128) VARCHAR(128) If a user-defined function is specified on the right-hand side of a SET clause in an UPDATE statement. If the CCSID of the input string is not the same as the CCSID of the parameter. these fields are blank. ROLLBACK and SET TRANSACTION statement is not allowed in the external program of the function. If external-program-name is not specified. The name must identify a program. | | | | | NO DBINFO Specifies that the function does not require the database information to be passed. the input string passed to the external function will be converted before calling the external program. 450 DB2 UDB for iSeries SQL Reference V5R2 . DISCONNECT. All functions are statically dispatched. v Reserved If a CCSID is not explicitly specified for a parameter on the CREATE FUNCTION statement. the input string is assumed to be encoded in the CCSID of the job at the time the function is executed. but it must exist at the time the function is invoked. The validity of the name is checked at the server. and modification level of the database manager. | | | | | | | | | | | | | | | | | | | STATIC DISPATCH Specifies that the function is dispatched statically. the current path will be used to search for the program or service program at the time the function is invoked. DBINFO fields (continued) Field CCSID Information Data Type INTEGER INTEGER INTEGER INTEGER CHAR(8) Description The CCSID information of the job. The program. Version and release Platform CHAR(8) INTEGER The version. A CONNECT.CREATE FUNCTION (External Scalar) Table 45. SET CONNECTION. The following information identifies the CCSID: v SBCS CCSID v DBCS CCSID v Mixed CCSID v Indication of which of the first three CCSIDs is appropriate. or java class that will be executed when the function is invoked in an SQL statement. an error is returned. The server’s platform type. the following information identifies the target column: v Schema name v Base table name v Column name If the user-defined function is not on the right-hand side of a SET clause in an UPDATE statement. service program. release. COMMIT. or java class need not exist at the time the function is created. If the format of the name is not correct. If the naming option is *SYS and the name is not qualified. the external program name is assumed to be the same as the function name. or java class that exists at the server at the time the function is invoked. service program. EXTERNAL NAME external-program-name Specifies the program. service program.

DB2GENERAL This parameter style is used to specify the conventions for passing parameters to and returning the value from external functions that are defined as a method in a Java class. The information on the layout of the message data in the SQLERRMC. parameter-2. For example: return_val func(parameter-1. v A parameter for the result of the function. v A parameter for the result of the function. v A parameter for the indicator variable for the result. GENERAL All applicable parameters are passed.. see the include sqludf in the appropriate source file. sqludf can be found in QSYSINC/H. All applicable parameters are passed. Note that the result is returned through as a value of a value returning function. for C..CREATE FUNCTION (External Scalar) PARAMETER STYLE Specifies the conventions used for passing parameters to and returning the values from functions: SQL All applicable parameters are passed. Statements 451 . The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. see the replacement data descriptions for message SQL0443 in message file QSQLMSG. v N parameters for indicator variables for the input parameters. v A VARCHAR(517) input parameter for the fully qualified function name. Chapter 5. For example. v A CHAR(5) output parameter for SQLSTATE. v A VARCHAR(70) output parameter for the message text. The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. v A VARCHAR(128) input parameter for the specific name. When control is returned to the invoking program. The SQLSTATE returned indicates the success or failure of the function. Only a portion of the message text is available. the message text can be found in the 6th token of the SQLERRMC field of the SQLCA. The user may set the SQLSTATE to any valid value in the external program to return an error or warning from the function. . DB2GENERAL is only allowed when the LANGUAGE is JAVA.) GENERAL is only allowed when EXTERNAL NAME identifies a service program. For more information about the parameters passed. The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. The SQLSTATE returned is an SQLSTATE that is assigned by the external program.

452 DB2 UDB for iSeries SQL Reference V5R2 . The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. v A VARCHAR(517) input parameter for the fully qualified function name. v A CHAR(5) output parameter for SQLSTATE.. Note that the result is returned through as a value of a value returning function.. The SQLSTATE returned either be: – the SQLSTATE from the last SQL statement executed in the external program. v A VARCHAR(128) input parameter for the specific name. JAVA This parameter style is specifies a parameter passing convention that conforms to the Java language and SQLJ routines specification. DB2SQL All applicable parameters are passed. . v A parameter for the indicator variable for the result. v A parameter for the result of the function. v An additional argument is passed for an indicator variable array. v A VARCHAR(70) output parameter for the message text.) JAVA is only allowed when the LANGUAGE is JAVA. All applicable parameters are passed. Note that the result is returned through as a value of a value returning function. For example: return_val func(parameter-1. v Zero to three optional parameters: – A structure (consisting of an INTEGER followed by a CHAR(n)) input and output parameter for the scratchpad. parameter-2. v N parameters for indicator variables for the input parameters.. For example: return_val func(parameter-1.CREATE FUNCTION (External Scalar) GENERAL WITH NULLS All applicable parameters are passed. The SQLSTATE returned indicates the success or failure of the function. – an SQLSTATE that is assigned by the external program. if SCRATCH PAD was specified on the CREATE FUNCTION statement. . parameter-2. The user may set the SQLSTATE to any valid value in the external program to return an error or warning from the function.) GENERAL WITH NULLS is only allowed when EXTERNAL NAME identifies a service program. The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. v A parameter for the indicator variable for the result.. The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement.

an attempt is made to save the function’s attributes in the associated program or service program object.CREATE FUNCTION (External Scalar) – An INTEGER input parameter for the call type. or QSYS2. Otherwise. ACTGRP(*CALLER) should normally be used so that the function runs in the same activation group as the calling program. an SQLCODE of -443 will be returned and a CPDB521 message will be placed in the job log. If the object cannot be updated. the function will still be created. – A structure for the dbinfo structure. If the *PGM or *SRVPGM object is saved and then restored to this or another system. For more information. the catalogs are automatically updated with those attributes. Note that language of the external function determines how the parameters are passed. if DBINFO was specified on the CREATE FUNCTION statement. in C. v The external program must exist when the CREATE FUNCTION statement is issued. any VARCHAR or CHAR parameters are passed as NUL-terminated strings. it runs in whatever activation group was specified when the external program or service program was created. For example. Creating the Function: When an external function associated with an ILE external program or service program is created. an error is issued. QSYS. v If the specific name was not specified. During restore of the function: v If the specific name was specified when the function was originally created and it is not unique. and an error is issued. For example. However. Statements 453 . Notes General Considerations for Defining User-defined Functions: See “CREATE FUNCTION” on page 436 for general information on defining user-defined functions. the function cannot be registered. v The external program or service program must contain at least one SQL statement. see the SQL Programming Concepts book. v If the signature is not unique. if FINAL CALL was specified on the CREATE FUNCTION statement. | Chapter 5. v The external program must be an ILE *PGM or *SRVPGM object. The attributes can be saved for external functions subject to the following restrictions: v The external program library must not be SYSIBM. you must have the Developer Kit for Java (5722-JV1) installed on your system. a unique name is generated if necessary. For more information about the parameters passed. for C. Invoking the Function: When an external function is invoked. ACTGRP(*NEW) is not allowed. sqludf can be found in QSYSINC/H. see the include sqludf in the appropriate source file. Notes for Java Functions: To be able to run Java functions.

else { *output = 2*(*input)-4. /* sqlstate */ char fname[140]. CREATE FUNCTION NTEST1 (SMALLINT) RETURNS SMALLINT EXTERNAL NAME NTESTMOD SPECIFIC MINENULL1 LANGUAGE C DETERMINISTIC NO SQL FENCED PARAMETER STYLE DB2SQL RETURNS NULL ON NULL INPUT NO EXTERNAL ACTION The program code: void nudft1 (int *input. v The value DB2GENRL may be used as a synonym for DB2GENERAL. *output_ind = 0. Syntax alternatives: The following keywords are synonyms supported for compatibility to prior releases. /* ptr to output arg short *input_ind. /* fully qualified function name */ char finst[129]. using the specific name MINENULL1. } return. /* ptr to input indicator short *output_ind. These keywords are non-standard and should not be used: v The keywords VARIANT and NOT VARIANT can be used as synonyms for NOT DETERMINISTIC and DETERMINISTIC. /* ptr to output indicator char sqlstate[6]. The simplest way to avoid a function call and get a null result when an input value is null is to specify RETURNS NULL ON NULL INPUT on the CREATE FUNCTION statement. /* ptr to input arg int *output. } */ */ */ */ Example 2: Assume that a user wants to define an external function named CENTER.CREATE FUNCTION (External Scalar) If an error occurs while running a Java procedure. The function program will be written in C. Depending on the error. The following statement defines the function. v The keywords SIMPLE CALL can be used as a synonym for GENERAL.4 The function should return a null value if and only if one of the input arguments is null. /* function specific name */ char msgtext[71]) /* msg text buffer */ { if (*input_ind == -1) *output_ind = -1. an SQLCODE of -443 will be returned. The following statement 454 DB2 UDB for iSeries SQL Reference V5R2 . v The keywords NULL CALL and NOT NULL CALL can be used as synonyms for CALLED ON NULL INPUT and RETURNS NULL ON NULL INPUT. Examples Example 1: Assume an external function program in C is needed that implements the following logic: rslt = 2 * input . other messages may exist in the job log of the job where the procedure was run.

CREATE FUNCTION (External Scalar) defines the function. The name of the program containing the function body is the same as the name of the function.FINDVWL’ NO EXTERNAL ACTION CALLED ON NULL INPUT DETERMINISTIC NO SQL Chapter 5. and lets the database manager generate a specific name for the function. DOUBLE) RETURNS DECIMAL(8. is to be run fenced. McBride plans to give the function specific name FOCUS98. CREATE FUNCTION SMITH. The user-defined function is written in Java. it returns a value with a data type of DECIMAL(8. CREATE FUNCTION CENTER (INTEGER. and is the FINDVWL method of class JAVAUDFS. The function program returns a value with a DOUBLE data type. The following statement written by user McBride defines the function and ensures that when the function is invoked.4) CAST FROM DOUBLE EXTERNAL NAME CMOD SPECIFIC FOCUS98 LANGUAGE C DETERMINISTIC NO SQL FENCED PARAMETER STYLE DB2SQL NO EXTERNAL ACTION SCRATCHPAD NO FINAL CALL Example 4: The following example defines a Java user-defined function that returns the position of the first vowel in a string. DOUBLE. The function program uses a scratchpad to perform some one-time only initialization and save the results. CREATE FUNCTION FINDV (VARCHAR(32000)) RETURNS INTEGER FENCED LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME ’JAVAUDFS.CENTER (DOUBLE. FLOAT) RETURNS FLOAT LANGUAGE C DETERMINISTIC NO SQL PARAMETER STYLE DB2SQL NO EXTERNAL ACTION Example 3: Assume that user McBride (who has administrative authority) wants to define an external function named CENTER in the SMITH schema. so the EXTERNAL clause does not include ’NAME external-program-name’. Statements 455 .4).

the function is still created. and returns a table to the SELECT by returning one row at a time. If user does not have this authority. The function returns a result table.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE FUNCTION (External Table) This CREATE FUNCTION (External Table) statement creates an external table function at the current server. then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority If a distinct type is referenced. It is an executable statement that can be dynamically prepared. or v It has been granted the system authorities of *OBJOPR and *ADD on the table. v Administrative Authority If SQL names are specified and a user profile exists that has the same name as the library into which the function is created. the privileges held by the authorization ID of the statement must include at least one of the following: v For the external program or service program that is referenced in the SQL statement: – The system authority *EXECUTE on the library that contains the external program or service program. If the external program or service program exists. A table function may be used in the FROM clause of a SELECT. – The system authority *EXECUTE on the external program or service program. The system needs this authority to update the program object to contain the information necessary to save/restore the function to another system. and – The system authority *CHANGE on the program or service program. the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: 456 DB2 UDB for iSeries SQL Reference V5R2 . and – The system authority *EXECUTE on library QSYS2 v Administrative Authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. or you can issue this statement interactively. Invocation You can embed this statement in an application program. v It has been granted the INSERT privilege on the table. but the program object is not updated. and that name is different from the authorization ID of the statement. Authorization The privileges held by the authorization id of the statement must include at least one of the following: v For the SYSFUNCS catalog view and SYSPARMS catalog table: – The INSERT privilege on the table.

v It was granted the USAGE privilege to the distinct type. Statements 457 . RETURNS TABLE ( column-name data-type2 AS LOCATOR ) option-list parameter-declaration: data-type1 parameter-name AS LOCATOR Chapter 5. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type.CREATE FUNCTION (External Table) | | | | | | | | | | | | CREATE FUNCTION function-name ( . parameter-declaration ) – The USAGE privilege on the distinct type. and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. Syntax .

0 ( integer . data-type2: built-in-type distinct-type-name built-in-type: SMALLINT INTEGER INT BIGINT (5.CREATE FUNCTION (External Table) data-type1. integer ) ( integer ) VARYING ( integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 GRAPHIC ) CCSID integer ) ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 ) TIMESTAMP ROWID 458 DB2 UDB for iSeries SQL Reference V5R2 .0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( CHARACTER CHAR CHARACTER CHAR VARCHAR 1 ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer .

Statements 459 . Chapter 5. the function will be created in the schema that is specified by the qualifier. the function will be created in the current library (*CURLIB). the function will be created in QGPL.CREATE FUNCTION (External Table) | option-list: (1) LANGUAGE C C++ CL COBOL COBOLLE FORTRAN JAVA PLI RPG RPGLE READS SQL DATA NO SQL CONTAINS SQL MODIFIES SQL DATA PARAMETER STYLE DB2GENERAL DB2SQL SPECIFIC specific-name NOT DETERMINISTIC IS DETERMINISTIC CALLED ON NULL INPUT RETURNS NULL ON NULL INPUT STATIC DISPATCH NO DBINFO DBINFO NO SCRATCHPAD EXTERNAL ACTION NO EXTERNAL ACTION EXTERNAL 100 FENCED NOT FENCED NO FINAL CALL FINAL CALL DISALLOW PARALLEL EXTERNAL NAME external-program-name SCRATCHPAD integer CARDINALITY integer Notes: 1 The optional clauses can be specified in a different order. and the data type of each parameter (without regard for any length. scale. more than one function can have the same name if the function signature of each function is unique. The combination of name. If no qualifier is specified. the function will be created in the schema specified by the implicit or explicit qualifier. or CCSID attributes of the data type) must not identify a user-defined function that exists at the current server. For SQL naming. Certain function names are reserved for system use. For more information see “Choosing the Schema and Function Name” on page 436. In general. precision. | | | | | | | | | | | | | | | | Description function-name Names the user-defined function. For system naming. schema name. the number of parameters. If there is no current library.

column-name Specifies the name of a column of the output table. for example: CREATE FUNCTION WOOFER() If a CCSID is specified. AS LOCATOR Specifies that the input parameter is a locator to the value rather than the actual value. For PARAMETER STYLE DB2SQL. there must be no more than (255-(N*2))/2 columns. LONG VARGRAPHIC. Although not required. For PARAMETER STYLE DB2GENERAL. you can give each parameter a name. Although not required. A function can have no parameters.. If a DATE or TIME is specified. If a CCSID is not specified. the table function must return the date or time in ISO format. the CCSID is determined by the default CCSID at the current server at the time the function is invoked. Assume the number of parameters is N. you must code an empty set of parentheses. All the parameters for a function are input parameters. If a CCSID is specified.. data-type1 Specifies the number of input parameters of the function and the data type of each input parameter. the parameter will be converted to that CCSID prior to passing it to the function. the result returned is assumed to be encoded in that CCSID. In this case. You can specify AS LOCATOR only if the input parameter has a LOB data type or a distinct type based on a LOB data type. Parameters with a large object (LOB) data type are not supported when PARAMETER STYLE JAVA is specified. Do not specify the same name more than once. there must be no more than (247-(N*2))/2 columns. You can specify any built-in data type (except LONG VARCHAR. v If AS LOCATOR is not specified. Do not specify the same name more than once. you can give each parameter a name. or DataLink) or a distinct type (that is not based on a DataLink).CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | (parameter-declaration. There must be one entry in the list for each parameter that the function expects to receive.) Specifies the number of parameters of the function and the data type of each parameter.. 460 DB2 UDB for iSeries SQL Reference V5R2 . data-type2 Specifies the data type and attributes of the output. The maximum number of parameters allowed in CREATE FUNCTION (External Table) is 90. RETURNS TABLE Specifies the output table of the function. The maximum number of parameters may be additionally limited by the maximum number of parameters allowed by the licensed program that is used to compile the external program. parameter-name Specifies the name of the input parameter.

Chapter 5. FORTRAN The external program is written in FORTRAN. including the schema name. If LANGUAGE is not specified. the data is converted to the specified CCSID. the qualifier must be the same as the qualifier of the function name. SPECIFIC specific-name Provides a unique name for the function. the data the locator points to is converted to the CCSID of the job. If qualified. If unqualified. You can specify AS LOCATOR only for a LOB data type or a distinct type based on a LOB data type. consider explicitly specifying a CCSID that can represent any characters that will be returned from the function.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v If AS LOCATOR is specified and the CCSID of the data the locator points to is encoded in a different CCSID. COBOL The external program is written in COBOL. must not identify the specific name of another function or procedure that exists at the current server. the result returned is assumed to be encoded in the CCSID of the job (or associated graphic CCSID of the job for graphic string return values). To avoid any potential loss of characters during the conversion. AS LOCATOR Specifies that the function returns a locator to the value for the column rather than the actual value. C++ The external program is written in C++. This is especially important if the data type is graphic string data. If specific name is not specified. COBOLLE The external program is written in ILE COBOL. If a CCSID is not specified. The name is implicitly or explicitly qualified with a schema name. CL The external program is written in CL or ILE CL. if the CCSID of the data the locator points to is encoded in a different CCSID. consider using CCSID 13488 (UCS-2 graphic string data). If a function or procedure with that specific name already exists. In this case. it is set to the function name. the LANGUAGE is determined from the program attribute information associated with the external program at the time the function is created. the implicit qualifier is the same as the qualifier of the function name. v If AS LOCATOR is specified. The name. Statements 461 . v If AS LOCATOR is not specified. a unique name is generated similar to the rules used to generate unique table names. The language of the program is assumed to be C if: v The program attribute information associated with the program does not identify a recognizable language v The program cannot be found C The external program is written in C. LANGUAGE (language clause) The language clause specifies the language of the external program.

NOT FENCED functions can keep SQL cursors open across individual calls to the function. READS SQL DATA. DETERMINISTIC or NOT DETERMINISTIC Specifies whether the function is deterministic. FENCED The function will run in a separate thread. READS SQL DATA The function does not execute SQL statements that modify data. the cursor position will also be preserved between calls to the function. The database manager verifies that the SQL issued by the function is consistent with this specification. RPG The external program is written in RPG. what type. FENCED is the safest option if the function contains SQL cursors. CONTAINS SQL. 462 DB2 UDB for iSeries SQL Reference V5R2 .CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | JAVA The external program is written in JAVA. RPGLE The external program is written in ILE RPG. The database manager will call the user-defined function as a method in a Java class. DETERMINISTIC Specifies that the function will always return the same result from successive invocations with identical input arguments. NOT FENCED The function may run in the same thread as the invoking SQL statement.” on page 835 for a detailed list of the SQL statements that can be executed under each data access indication. or NO SQL Specifies whether the function can execute any SQL statements and. NOT DETERMINISTIC should be specified if the function contains a reference to a special register or a non-deterministic function. NO SQL The function does not execute SQL statements. because multiple invocations of the same function in the same SQL statement may conflict with each other. MODIFIES SQL DATA The function can execute any SQL statement except those statements that are not supported in any function. if so. NOT DETERMINISTIC Specifies that the function will not always return the same result from successive function invocations with identical input arguments. CONTAINS SQL The function does not execute SQL statements that read or modify data. See Appendix C. MODIFIES SQL DATA. “Characteristics of SQL Statements. FENCED or NOT FENCED Specifies whether the function will run in the same thread as the invoking SQL statement or in a separate thread. PLI The external program is written in PL/I. Since cursors can be kept open.

if any. close call. If NO FINAL CALL is specified. For example. The scope of a scratchpad is the SQL statement. fetch call. then the database manager can only make three types of calls to the table function: open. SCRATCHPAD Specifies whether the function requires a static memory area. making the function responsible for testing for null argument values. there is one scratchpad. the function must be invoked with each successive function invocation. The result is the null value. or all. RETURNS NULL ON INPUT Specifies that the function is not invoked if any of the input arguments is null. or final call. It also controls when the scratchpad is re-initialized.C1 FROM TABLE(UDFX(:hv1)) AS A. FINAL CALL Specifies whether the function requires a final call (and a separate first call). fetch and close. EXTERNAL ACTION or NO EXTERNAL ACTION Specifies whether the function contains an external action. B. then in addition to open. two scratchpads are allocated for the two references to UDFX in the following SQL statement: SELECT A. fetch and close. SCRATCHPAD integer Specifies that the function requires a persistent memory area of length integer. CALLED ON NULL INPUT Specifies that the function is to be invoked. NO EXTERNAL ACTION The function does not perform an external action. Statements 463 . if FINAL CALL is specified. the call-type argument is ALWAYS present. If the memory area is not specified. a pointer is passed following the required parameters that points to a static storage area. The call-type argument indicates first call. Only 1 memory area will be allocated for the function. EXTERNAL ACTION should be specified if the function contains a reference to another function that has an external action. However. Thus.000. a first call and a final Chapter 5. The function can return a null or nonnull value. regardless of which FINAL CALL option is chosen. It need not be called with each successive function invocation. FINAL CALL Specifies that the function requires a final call (and a separate first call). If parameter style DB2SQL is specified. TABLE(UDFX(:hv1)) AS B NO SCRATCHPAD Specifies that the function does not require a persistent memory area. For table functions.C1. argument values are null.000. The integer can range from 1 to 16. the size of the area is 100 bytes. open call.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT Specifies whether the function is called if any of the input arguments is null at execution time. assuming that function UDFX was defined with the SCRATCHPAD keyword. EXTERNAL ACTION The function performs some external action (outside the scope of the function program). For each reference to the function in an SQL statement.

the logic of an application. Final Call Specifies the last call to the function to enable the function to free resources. DBINFO Specifies that the database manager should pass a structure containing status information to the function. The types of calls are: First Call Specifies the first call to the function for this reference to the function in this SQL statement.H. Table functions cannot run in parallel. DBINFO Specifies whether or not the function requires the database information be passed. Fetch Call Specifies a call to fetch a row from the table function in this SQL statement. or the execution of the statement has completed. bypasses closing the cursor. For example. Open Call Specifies a call to open the table function result in this SQL statement. because the FINAL CALL may occur during a close invoked as part of a COMMIT operation. the function receives an additional argument that specifies the type of call.Specifies that a final call is made to the function. To differentiate between final calls and other calls. the database manager attempts to make the final call. for some reason.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | call can be made to the table function. Table 46 on page 465 contains a description of the DBINFO structure. A final call occurs at these times: v End of statement: When the cursor is closed for cursor-oriented statements. However the open. Detailed information about the DBINFO structure can be found in include file SQLUDF in QSYSINC. DISALLOW PARALLEL Specifies that the function cannot be run in parallel. Commitable operations should not be performed during a FINAL CALL. NO FINAL CALL Specifies that the function does not require a final call (and a separate first call). If an error occurs. If a commit operation occurs while a cursor defined as WITH HOLD is open. Close Call Specifies a call to close the table function result in this SQL statement. 464 DB2 UDB for iSeries SQL Reference V5R2 . fetch. v End of transaction: When normal end of statement processing does not occur. and close calls are still made. a final call is made when the cursor is closed or the application ends.

Chapter 5. If a user-defined function is specified on the right-hand side of a SET clause in an UPDATE statement. Note that n could be equal to zero for a statement that is similar to SELECT COUNT(*) FROM TABLE(TF(. are of interest. The run-time authorization ID. The server’s platform type.. The following information identifies the CCSID: v SBCS CCSID v DBCS CCSID v Mixed CCSID v Indication of which of the first three CCSIDs is appropriate. the input string passed to the external function will be converted before calling the external program. the input string is assumed to be encoded in the CCSID of the job at the time the function is executed. The values may be in any order. Statements 465 . The number of non-zero entries in the table function column list specified in the ″Table function column list″ field below. these fields are blank. Since this optimization may complicate the function logic. DBINFO fields Field Relational database Authorization ID CCSID Information Data Type VARCHAR(128) VARCHAR(128) INTEGER INTEGER INTEGER INTEGER CHAR(8) Description The name of the current server. v Reserved If a CCSID is not explicitly specified for a parameter on the CREATE FUNCTION statement. The version. Reserved for future use. CHAR(24) Pointer (16 Bytes) This field is a pointer to an array of short integers which is dynamically allocated by the database manager.)) AS QQ. and is less than or equal to the number of result columns defined for the function in the RETURNS TABLE clause. 2 means the second defined result column. The values correspond to the ordinal numbers of the columns which this statement needs from the table function. and modification level of the database manager. n may be equal to 0.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Version and release Platform Number of table function column list entries Reserved Table function column list CHAR(8) INTEGER SMALLINT Target column VARCHAR(128) VARCHAR(128) VARCHAR(128) Table 46. where n is specified in the ″Number of table function column list entries″ field. and these are the columns identified (by number) in the array. The function need not return all values for all the result columns of the table function. release. The CCSID information of the job. Only the first n entries. the function can choose to return every defined column. the following information identifies the target column: v Schema name v Base table name v Column name If the user-defined function is not on the right-hand side of a SET clause in an UPDATE statement. where no actual column values are needed by the query. and so on. This array represents an opportunity for optimization. A value of 1 means the first defined result column. If the CCSID of the input string is not the same as the CCSID of the parameter.. Only a subset of the values may be needed in a particular context.

All applicable parameters are passed. COMMIT. CARDINALITY integer This optional clause provides an estimate of the expected number of rows to be returned by the function for optimization purposes. If the CARDINALITY clause is not specified for a table function. v The next M parameters are the result columns of the function that are specified on the RETURNS TABLE clause. DB2GENERAL is only allowed when the LANGUAGE is JAVA. RELEASE. STATIC DISPATCH Specifies that the function is dispatched statically. an error is returned. The validity of the name is checked at the server. but it must exist at the time the function is invoked. If the format of the name is not correct. PARAMETER STYLE Specifies the conventions used for passing parameters to and returning the values from functions: DB2GENERAL This parameter style is used to specify the conventions for passing parameters to and returning the value from external functions that are defined as a method in a Java class. then queries which require the end-of-table condition will also be infinite and will have to be interrupted. Examples of such queries are those involving GROUP BY and ORDER BY. i. The parameters are defined to be in the following order: v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. SET CONNECTION. the database manager will assume a finite value as a default. or java class that exists at the server at the time the function is invoked. If external-program-name is not specified. The name must identify a program. ROLLBACK and SET TRANSACTION statement is not allowed in the external program of the function. the external program name is assumed to be the same as the function name. service program. or java class need not exist at the time the function is created. The parameters are defined to be in the following order: 466 DB2 UDB for iSeries SQL Reference V5R2 . service program. Valid values for integer range from 0 to 2 147 483 647 inclusive. Warning: If a function does in fact have infinite cardinality. The user is advised to not write such UDFs. service program.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | NO DBINFO Specifies that the function does not require the database information to be passed. it returns a row every time it is called and never returns the end-of-table condition. A CONNECT.e. DB2SQL All applicable parameters are passed. DISCONNECT. If the naming option is *SYS and the name is not qualified. EXTERNAL NAME external-program-name Specifies the program. the current path will be used to search for the program or service program at the time the function is invoked. The program. All functions are statically dispatched. or java class that will be executed when the function is invoked in an SQL statement.

v The external program must be an ILE *PGM or *SRVPGM object. or QSYS2. The user may set the SQLSTATE to any valid value in the external program to return an error or warning from the function. Notes General Considerations for Defining User-defined Functions: See “CREATE FUNCTION” on page 436 for general information on defining user-defined functions. in C. For example. if DBINFO was specified on the CREATE FUNCTION statement. Creating the Function: When an external function associated with an ILE external program or service program is created. v M parameters for the indicator variables of the result columns of the function that are specified on the RETURNS TABLE clause v A CHAR(5) output parameter for SQLSTATE. The SQLSTATE returned either be: – the SQLSTATE from the last SQL statement executed in the external program. see the include sqludf in the appropriate source file. If the *PGM or *SRVPGM object is saved and then restored to this or another system. v The next M parameters are the result columns of the function that are specified on the RETURNS TABLE clause. v An INTEGER input parameter for the call type. any VARCHAR or CHAR parameters are passed as NUL-terminated strings. see the SQL Programming Concepts book. – an SQLSTATE that is assigned by the external program. QSYS. For more information about the parameters passed. Note that language of the external function determines how the parameters are passed. For more information. Chapter 5. v A VARCHAR(517) input parameter for the fully qualified function name. the catalogs are automatically updated with those attributes. an attempt is made to save the function’s attributes in the associated program or service program object.CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v The first N parameters are the input parameters that are specified on the CREATE FUNCTION statement. v A VARCHAR(128) input parameter for the specific name. Statements 467 . The attributes can be saved for external functions subject to the following restrictions: v The external program library must not be SYSIBM. The SQLSTATE returned indicates the success or failure of the function. v N parameters for indicator variables for the input parameters. v A VARCHAR(70) output parameter for the message text. v The external program must exist when the CREATE FUNCTION statement is issued. v A structure for the dbinfo structure. For example. if SCRATCH PAD was specified on the CREATE FUNCTION statement. sqludf can be found in QSYSINC/H. v A structure (consisting of an INTEGER followed by a CHAR(n)) input and output parameter for the scratchpad. for C.

These keywords are non-standard and should not be used: v The keywords VARIANT and NOT VARIANT can be used as synonyms for NOT DETERMINISTIC and DETERMINISTIC. If the object cannot be updated. it runs in whatever activation group was specified when the external program or service program was created. Syntax alternatives: The following keywords are synonyms supported for compatibility to prior releases. the function will still be created. and an error is issued. v The value DB2GENRL may be used as a synonym for DB2GENERAL. a unique name is generated if necessary. ACTGRP(*CALLER) should normally be used so that the function runs in the same activation group as the calling program. FINAL CALL must be specified for each table function. CREATE FUNCTION DOCMATCH (VARCHAR(30). Otherwise. the UDF will always return the same table. Example The following creates a table function written to return a row consisting of a single document identifier column for each known document in a text management system. ACTGRP(*NEW) is not allowed. In addition. other messages may exist in the job log of the job where the procedure was run. Although the size of the output for DOCMATCH is highly variable. an SQLCODE of -443 will be returned. an error is issued. an SQLCODE of -443 will be returned and a CPDB521 message will be placed in the job log. The first parameter matches a given subject area and the second parameter contains a given string. and therefore it is defined as DETERMINISTIC. If an error occurs while running a Java procedure. v The keywords NULL CALL and NOT NULL CALL can be used as synonyms for CALLED ON NULL INPUT and RETURNS NULL ON NULL INPUT. Note the RETURNS clause which defines the output from DOCMATCH. v If the specific name was not specified. During restore of the function: v If the specific name was specified when the function was originally created and it is not unique. and is specified to help the optimizer. Within the context of a single session. Depending on the error. Invoking the Function: When an external function is invoked. v If the signature is not unique. VARCHAR(255)) RETURNS TABLE (DOCID CHAR(16)) EXTERNAL NAME ’MYLIB/RAJIV(UDFMATCH)’ LANGUAGE C PARAMETER STYLE DB2SQL NO SQL 468 DB2 UDB for iSeries SQL Reference V5R2 .CREATE FUNCTION (External Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v The external program or service program must contain at least one SQL statement. the DISALLOW PARALLEL keyword is added as table functions cannot operate in parallel. However. CARDINALITY 20 is a representative value. you must have the Developer Kit for Java (5722-JV1) installed on your system. Notes for Java Functions: To be able to run Java functions. the function cannot be registered.

Statements 469 .CREATE FUNCTION (External Table) | | | | | | | | DETERMINISTIC NO EXTERNAL ACTION NOT FENCED SCRATCHPAD FINAL CALL DISALLOW PARALLEL CARDINALITY 20 Chapter 5.

the authorization ID of the statement must include at least one of the following for the source function: v The EXECUTE privilege on the function v Administrative authority The authorization ID of the statement has the EXECUTE privilege on a function when: v It is the owner of the function. and that name is different from the authorization ID of the statement. To create a sourced function. at the current server. the privileges held by the authorization ID of the statement must also include at least one of the following: v The following system authorities: – *USE to the Create Service Program (CRTSRVPGM) command or – *USE to the Create Program (CRTPGM) command – *EXECUTE and *ADD to the library into which the function is created. or v It has been granted the system authorities of *OBJOPR and *EXECUTE on the function. v Administrative authority If SQL names are specified and a user profile exists that has the same name as the library into which the function is created. v It has been granted the EXECUTE privilege on the function. based on another existing scalar or column function. v It has been granted the INSERT privilege on the table. If the source function is a user-defined function. then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority | | | | 470 DB2 UDB for iSeries SQL Reference V5R2 . or v It has been granted the system authorities of *OBJOPR and *ADD on the table. Invocation This statement can be embedded in an application program or issued interactively. and – The system authority *EXECUTE on library QSYS2 v Administrative authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table.CREATE FUNCTION (Sourced) CREATE FUNCTION (Sourced) This CREATE FUNCTION (Sourced) statement is used to create a user-defined function. It is an executable statement that can be dynamically prepared. Authorization The privileges held by the authorization id of the statement must include at least one of the following: v For the SYSFUNCS catalog view and SYSPARMS catalog table: – The INSERT privilege on the table.

CREATE FUNCTION (Sourced) | | | | | | | | | | | | If a distinct type is referenced. Syntax CREATE FUNCTION function-name ( . the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: – The USAGE privilege on the distinct type. v It was granted the USAGE privilege to the distinct type. parameter-type2 SPECIFIC specific-name ) parameter-declaration: data-type1 parameter-name AS LOCATOR data-type1. parameter-declaration ) (1) RETURNS data-type2 AS LOCATOR SOURCE function-name SPECIFIC specific-name function-name ( . data-type2. Statements 471 . and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type. Chapter 5. data-type3: built-in-type distinct-type-name Notes: 1 The RETURNS. SPECIFIC. and SOURCE clauses can be specified in any order.

0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( CHARACTER CHAR CHARACTER CHAR VARCHAR 1 ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer .CREATE FUNCTION (Sourced) built-in-type: | SMALLINT INTEGER INT BIGINT (5.0 ( integer . integer ) ( integer ) VARYING ( integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 GRAPHIC ) CCSID integer ) ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 ) TIMESTAMP ( 200 ) DATALINK ( integer ) ROWID CCSID integer 472 DB2 UDB for iSeries SQL Reference V5R2 .

the name can be the same name as the existing function. this checking does not guarantee that an error will not occur when the function is invoked. more than one function can have the same name if the function signature of each function is unique. Statements 473 . For more information see “Choosing the Schema and Function Name” on page 436.. parameter-name Specifies the name of the parameter. Each parameter-declaration is an input parameter for the function. precision. If there is no current library. and the data type of each parameter (without regard for any length. The combination of name. A maximum of 90 parameters can be specified. the function will be created in the schema specified by the implicit or explicit qualifier.. Although not required. distinct-type-name The data type of the input parameter is a distinct type. However. or CCSID attributes of the data type) must not identify a user-defined function that exists at the current server.. For system naming. Each name in the parameter list must not be the same as any other name. built-in-type The data type of the input parameter is a built-in data type. For SQL naming. If no qualifier is specified. scale. schema name. The length. In general. Any valid SQL data type may be used provided it is castable to the type of the corresponding parameter of the function identifed in the SOURCE clause (for information see “Casting Between Data Types” on page 78). the function will be created in QGPL. | | Certain function names are reserved for system use. The data type can be a built-in data type or a distinct data type. the function will be created in schema that is specified by the qualifier. If the function is sourced on an existing function to enable the use of the existing function with a distinct type. the function will be created in the current library (*CURLIB). precision. See “CREATE TABLE” on page 526 for a more complete description of each built-in data type. or scale attributes for the parameter are those of the source Chapter 5. data-type1 Specifies the number of input parameters of the function and the data type of each input parameter. the number of parameters. (parameter-declaration.CREATE FUNCTION (Sourced) parameter-type: data-type3 AS LOCATOR Description function-name Names the user-defined function. See “Considerations for invoking a sourced user-defined function” under “Notes” for this statement. a parameter name can be specified for each parameter.) Specifies the number of input parameters of the function and the data type of each parameter.

You can specify AS LOCATOR only if the input parameter has a LOB data type or a distinct type based on a LOB data type. NODENAME. or a DataLink) or distinct type (that is not based on a DataLink). You can specify any built-in data type (except LONG VARCHAR.CREATE FUNCTION (Sourced) type of the distinct type (those specified on CREATE DISTINCT TYPE). RETURNS Specifies the output of the function. function signature. AS LOCATOR Specifies that the input parameter is a locator to the value rather than the actual value. | | | | | | | | | | SOURCE Specifies that the new function is being defined is a sourced function. RRN. You can specify AS LOCATOR only if the output from the function has a LOB data type or a distinct type based on a LOB data type. If specific name is not specified. The name. DataLinks are not allowed for funcitons sourced on external functions. See “CREATE DISTINCT TYPE” on page 429 for more information. (For information on casting data types. it is set to the function name. The particular function can be identified by its name. The function must exist at the current server and it must be a function that was defined with the CREATE FUNCTION statement or a cast function that was generated by a CREATE DISTINCT TYPE statement. If qualified. the parameter will be converted to that CCSID prior to passing it to the function. A sourced function is implemented by another function (the source function). STRIP. PARTITION. SPECIFIC specific-name Provides a unique name for the function. If a CCSID is not specified. IFNULL. The name is implicitly or explicitly qualified with a schema name. the CCSID is determined by the default CCSID at the current server at the time the function is invoked. see “Casting Between Data Types” on page 78) AS LOCATOR Specifies that the function returns a locator to the value rather than the actual value. NULLIF. If unqualified. a unique name is generated similar to the rules used to generate unique table names. If the name of the distinct type is specified without a schema name. 474 DB2 UDB for iSeries SQL Reference V5R2 . SUBSTRING. provided it is castable from the result type of the source function. MAX. LONG VARGRAPHIC. The AS LOCATOR clause is not allowed for functions sourced on SQL functions. POSITION. LAND. must not identify the specific name of another function or procedure that exists at the current server. NODENUMBER. the database manager resolves the schema name by searching the schemas in the SQL path. MIN. the implicit qualifier is the same as the qualifier of the function name. HASH. LOR. The source function can be any built-in scalar or column function except COALESCE. the qualifier must be the same as the qualifier of the function name. including the schema name. If a function or procedure with that specific name already exists. or specific name. If a CCSID is specified. data-type Specifies the data type and attributes of the output.

2). Functions A and B inherit all of the attributes that are specified on CREATE FUNCTION statement for function C. GRAPHIC. The function may have any number of parameters defined for it. this syntax variation must be used... function-name Identifies the function to be used as the source function by its function name. assume that function A is sourced on function B.) Identifies the function to be used as the source function by its function signature. VARCHAR. v If a specific value for a length. To use a built-in function as the source function.. the database manager searches the SQL path to resolve the schema name for the distinct type. v Empty parenthesis indicates that the data base manager ignores the attribute when determining whether the data types match.. the function identified must have zero parameters. Otherwise. parameter-type. . DBCLOB. you can specify a value or use a set of empty parentheses. If the data type is FLOAT. an error is returned function-name (parameter-type2. For example. precision or scale attribute. CHAR. or any previously created user-defined function. If there is more than one function of the specified name in the specified or implicit schema. and XOR. Synonyms for data types are considered a match. TRANSLATE.) must identify a function with the specified signature at the current server. the value must exactly match the value that was specified (implicitly or explicitly) in the CREATE FUNCTION statement. Statements 475 . Chapter 5. CLOB. The number of data types. the specified schema is searched for the function.. Function C is a scalar function. The source function can be one of the following built-in functions only if one argument is specified: BLOB. VALUE. the sourced function inherits the attributes of the scalar function. If an unqualified name is specified. The function-name (parameter-type. and the logical concatenation of the data types is used to identify the specific function instance. The specified parameters must match the data types in the corresponding position that were specified when the function was created. precision. DEC() will be considered a match for a parameter of a function defined with a data type of DEC(7. the precision does not have to exactly match the value that was specified because matching is based on the data type (REAL or DOUBLE). and ZONED. It can be a system-generated user-defined function (generated when a distinct type was created). If an unqualified distinct type name is specified. which in turn is sourced on function C. the schemas of the SQL path are searched... For data types that have a length. or scale attribute is specified. If function-name() is specified. For example. function-name Identifies the name of the source function.. Identifies the parameters of the function. DECIMAL. This can involve several layers of sourced functions. If you base the sourced function directly or indirectly on a scalar function. VARGRAPHIC. which uniquely identifies the function.CREATE FUNCTION (Sourced) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | TRIM.

specifying the FOR DATA clause or CCSID clause is optional. The data type of the final result of the source function must match or be castable to the result of the sourced function. the owner of the function is the user profile or group user profile of the job executing the statement. the data is converted to the specified CCSID. the data type length is ignored. If a CCSID is not specified the return data is converted to the CCSID of the job (or associated graphic CCSID of the job for graphic string return values). If system names were specified. it must match the value that was implicitly or explicitly specified in the CREATE FUNCTION statement. The implicit length must exactly match the value that was specified (implicitly or explicitly) in the CREATE FUNCTION statement. If a CCSID is specified and the CCSID of the return data is encoded in a different CCSID. If AS LOCATOR is specified and a length is explicitly specified. Omission of either clause indicates that the database manager ignores the attribute when determining whether the data types match. Notes General Considerations for Defining User-defined Functions: See “CREATE FUNCTION” on page 436 for general information on defining user-defined functions. or scale is not explicitly specified. If AS LOCATOR is specified the data type must be a LOB or a distinct type based on a LOB. Otherwise. and empty parentheses are not specified. SPECIFIC specific-name Identifies the function to be used as the source function by its specific name. The number of input parameters in the function that is being created must be the same as the number of parameters in the source function. This is especially important if the data type is graphic string data. the default schema is used as the qualifier. To avoid any potential loss of characters during the conversion. If an unqualified specific-name is specified. Function ownership: If SQL names were specified. In this case. the owner of the function is the user profile with the same name as the schema into which the function is created. if the CCSID of the return data is encoded in a different CCSID. The specific-name must identify a specific function that exists in the specified or implicit schema. If you specify either clause. consider explicitly specifying a CCSID that can represent any characters that will be returned from the function. AS LOCATOR Specifies that the function is defined to receive a locator for this parameter. the owner of the function is the user profile or group user profile of the job executing the statement.CREATE FUNCTION (Sourced) | | | | | | | | | | | | | | | | | | | | | v If length. For data types with a subtype or CCSID attribute. an error occurs. 476 DB2 UDB for iSeries SQL Reference V5R2 . If the data type of each input parameter is not the same as or castable to the corresponding parameter of the source function. precision. consider using CCSID 13488 (UCS-2 graphic string data). the default attributes of the data type are implied.

functions are created with the system authority of *EXCLUDE on *PUBLIC. each argument to the function is assigned to the associated parameter defined for the function. assume that function A is sourced on function B. that group profile will also have authority to the function. functions are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema. Examples Example 1: Assume that distinct type HATSIZE is defined and is based on the built-in data type INTEGER. a small service program object is created that represents the function. The RETURNS data type of the underlying function might not be castable to the RETURNS data type of the source function. This can involve several layers of sourced functions. Considerations for invoking a sourced user-defined function: When a sourced function is invoked. The result of the underlying function is assigned to the RETURNS data type of the sourced function. It is recommended that the RETURNS data type of a sourced function be defined with attributes that are the same or greater than the attributes defined for the RETURNS data type of the underlying function. Creating the Function: When a sourced function is created. The values are then cast (if necessary) to the data type of the corresponding parameters of the underlying function. and the definition references function A in the SOURCE clause. It is recommended that the data types of the parameters of a sourced function be defined with attributes that are less than or equal to the attributes of the corresponding parameters of the underlying function. An AVG function could be defined to compute the average hat size of different departments. Considerations when the function is based on a user-defined function: If the sourced function is based directly or indirectly on an external scalar function. CREATE FUNCTION AVG (HATSIZE) RETURNS HATSIZE SOURCE AVG (INTEGER) Chapter 5. is defined to return a SMALLINT. Function B is a sourced function. an error would occur when function A is invoked assuming the following functions exist. For example. the sourced function inherits the attributes of the EXTERNAL clause of the external scalar function. Function A returns an INTEGER. If the owner of the function is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). the attributes from the CREATE FUNCTION statement are automatically added to the catalog on that system.CREATE FUNCTION (Sourced) Function authority: If SQL names are used. Statements 477 . which in turn is sourced on function C. Functions A and B inherit all of the attributes that are specified on the EXTERNAL clause of the CREATE FUNCTION statement for function C. Function C is an external scalar function. This can occur when the RETURNS data type of this new source function has a shorter length or less precision than the RETURNS data type of the underlying function. For example. If system names are used. For example: an argument passed on input to a function that matches the data type and length or precision attributes of the parameter for the function might not be castable if the corresponding parameter of the underlying source function has a shorter length or less precision. When this service program is saved and restored to another system. An error can occur either in the assignment or in the cast. Create a sourced function that is based on built-in function AVG.

two cast functions were generated. which allow HATSIZE to be cast to INTEGER for the argument and INTEGER to be cast to HATSIZE for the result of the function. Example 2: After Smith created the external scalar function CENTER in his schema. DOUBLE). there is a need to use this function. function. CREATE FUNCTION MYCENTER (INTEGER.CREATE FUNCTION (Sourced) The syntax of the SOURCE clause includes an explicit parameter list because the source function is a built-in function. Create a sourced function that is based on CENTER. INTEGER) RETURNS DOUBLE SOURCE SMITH. 478 DB2 UDB for iSeries SQL Reference V5R2 . When distinct type HATSIZE was created.CENTER (INTEGER. but the invocation of the function needs to accept two INTEGER arguments instead of one INTEGER argument and one DOUBLE argument.

and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type.CREATE FUNCTION (SQL Scalar) CREATE FUNCTION (SQL Scalar) This CREATE FUNCTION (SQL Scalar) statement creates an SQL function at the current server. the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: – The USAGE privilege on the distinct type. or v It has been granted the system authorities of *OBJOPR and *ADD on the table. or you can issue this statement interactively. The privileges held by the authorization ID of the statement must also include at least one of the following: v The following system authorities: – *USE to the Create Service Program (CRTSRVPGM) command or – *EXECUTE and *ADD to the library into which the function is created. v It was granted the USAGE privilege to the distinct type. v Administrative authority If a distinct type is referenced. and – The system authority *EXECUTE on library QSYS2 v Administrative Authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. Statements ) 479 . parameter-declaration Chapter 5. It is an executable statement that can be dynamically prepared. Invocation You can embed this statement in an application program. Authorization The privileges held by the authorization id of the statement must include at least one of the following: v For the SYSFUNCS catalog view and SYSPARMS catalog table: – The INSERT privilege on the table. The function returns a single result. | | | | | | | | | | | | | | | Syntax CREATE FUNCTION function-name ( . v It has been granted the INSERT privilege on the table. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type.

CREATE FUNCTION (SQL Scalar) RETURNS data-type2 LANGUAGE SQL option-list SET OPTION-statement SQL-routine-body parameter-declaration: parameter-name data-type1 480 DB2 UDB for iSeries SQL Reference V5R2 .

CREATE FUNCTION (SQL Scalar) data-type: built-in-type distinct-type-name built-in-type: | SMALLINT INTEGER INT BIGINT (5. integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 ) GRAPHIC ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( CCSID integer ) ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 TIMESTAMP ( 200 ) DATALINK ( integer ) ROWID Chapter 5.0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( 1 ) CHARACTER CHAR CHARACTER CHAR VARCHAR ( integer ) VARYING ( integer ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer .0 ( integer . Statements ) CCSID integer 481 .

For system naming. Do not specify the same name more than once.. If no qualifier is specified.CREATE FUNCTION (SQL Scalar) option-list: (1) SPECIFIC specific-name NOT DETERMINISTIC IS DETERMINISTIC READS SQL DATA CONTAINS SQL MODIFIES SQL DATA EXTERNAL ACTION NO EXTERNAL ACTION CALLED ON NULL INPUT RETURNS NULL ON NULL INPUT STATIC DISPATCH FENCED NOT FENCED ALLOW PARALLEL DISALLOW PARALLEL Notes: 1 The optional clauses can be specified in a different order. The combination of name. For more information see “Choosing the Schema and Function Name” on page 436. the function will be created in the schema that is specified by the qualifier.. data-type1 Specifies the number of input parameters of the function and the data type 482 DB2 UDB for iSeries SQL Reference V5R2 .) Specifies the number of parameters of the function and the data type of each parameter. scale. and the data type of each parameter (without regard for any length. In general. For SQL naming. If there is no current library. | | Certain function names are reserved for system use. | The maximum number of parameters allowed is 90. A parameter name must be specified for parameters in SQL functions. the function will be created in the current library (*CURLIB). precision. the function will be created in the schema specified by the implicit or explicit qualifier. (parameter-declaration. the number of parameters. or CCSID attributes of the data type) must not identify a user-defined function that exists at the current server. schema name. the function will be created in QGPL. you can give each parameter a name. more than one function can have the same name if the function signature of each function is unique. Although not required. parameter-name Specifies the name of the input parameter. SQL-routine-body: SQL-control-statement Description function-name Names the user-defined function..

the data is converted to the specified CCSID. If a function or procedure with that specific name already exists. If unqualified. a unique name is generated similar to the rules used to generate unique table names. DETERMINISTIC or NOT DETERMINISTIC Specifies whether the function is deterministic. the parameter will be converted to that CCSID prior to passing it to the function. The name is implicitly or explicitly qualified with a schema name. you must code an empty set of parentheses. If specific name is not specified. the qualifier must be the same as the qualifier of the function name. If a CCSID is specified and the CCSID of the return data is encoded in a different CCSID. must not identify the specific name of another function or procedure that exists at the current server. To avoid any potential loss of characters during the conversion.CREATE FUNCTION (SQL Scalar) of each input parameter. DETERMINISTIC Specifies that the function will always return the same result from successive invocations with identical input arguments. Chapter 5. LANGUAGE SQL Specifies that this is an SQL function. if the CCSID of the return data is encoded in a different CCSID. for example: CREATE FUNCTION WOOFER() If a CCSID is specified. There must be one entry in the list for each parameter that the function expects to receive. RETURNS Specifies the output of the function. NOT DETERMINISTIC should be specified if the function contains a reference to a special register or a non-deterministic function. or LONG VARGRAPHIC) or a distinct type. All the parameters for a function are input parameters. If a CCSID is not specified the return data is converted to the CCSID of the job (or associated graphic CCSID of the job for graphic string return values). SPECIFIC specific-name Provides a unique name for the function. Statements 483 . it is set to the function name. | | | | | NOT DETERMINISTIC Specifies that the function will not always return the same result from successive function invocations with identical input arguments. the CCSID is determined by the default CCSID at the current server at the time the function is invoked. The name. You can specify any built-in data type (except LONG VARCHAR. A function can have no parameters. data-type2 Specifies the data type and attributes of the output. consider explicitly specifying a CCSID that can represent any characters that will be returned from the function. including the schema name. consider using CCSID 13488 (UCS-2 graphic string data). In this case. If a CCSID is not specified. the implicit qualifier is the same as the qualifier of the function name. If qualified. This is especially important if the data type is graphic string data. In this case.

NOT FENCED functions can keep SQL cursors open across individual calls to the function. if any. making the function responsible for testing for null argument values. EXTERNAL ACTION The function performs some external action (outside the scope of the function program). or MODIFIES SQL DATA Specifies whether the function can execute any SQL statements and. FENCED or NOT FENCED Specifies whether the function will run in the same thread as the invoking SQL statement or in a separate thread. FENCED The function will run in a separate thread. The function can return a null or nonnull value. READS SQL DATA. NO EXTERNAL ACTION The function does not perform an external action. PARALLEL Specifies whether the function can be run in parallel. NOT FENCED The function may run in the same thread as the invoking SQL statement. the cursor position will also be preserved between calls to the function. Thus. or all. RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT Specifies whether the function is called if any of the input arguments is null at execution time. READS SQL DATA The function does not execute SQL statements that modify data. MODIFIES SQL DATA The function can execute any SQL statement except those statements that are not supported in any function. “Characteristics of SQL Statements. The result is the null value. CONTAINS SQL The function does not execute SQL statements that read or modify data. if so.CREATE FUNCTION (SQL Scalar) | | | | | | | | | | | | | | | | | | | | | | | | | CONTAINS SQL. It need not be called with each successive function invocation. | | | | | | | | | | | EXTERNAL ACTION or NO EXTERNAL ACTION Specifies whether the function contains an external action. The database manager verifies that the SQL issued by the function is consistent with this specification. RETURNS NULL ON INPUT Specifies that the function is not invoked if any of the input arguments is null. 484 DB2 UDB for iSeries SQL Reference V5R2 . EXTERNAL ACTION should be specified if the function contains a reference to another function that has an external action. what type. argument values are null. FENCED is the safest option if the function contains SQL cursors. CALLED ON NULL INPUT Specifies that the function is to be invoked. because multiple invocations of the same function in the same SQL statement may conflict with each other. Since cursors can be kept open.” on page 835 for a detailed list of the SQL statements that can be executed under each data access indication. the function must be invoked with each successive function invocation. See Appendix C.

Chapter 5. including a compound statement. | | | | Function ownership: If SQL names were specified. A call to a procedure that issues a CONNECT. and NAMING are not allowed in the CREATE FUNCTION statement. SET OPTION-statement Specifies the options that will be used to create the function. the owner of the function is the user profile or group user profile of the job executing the statement. to create a debuggable function. it must contain at least one RETURN statement and a RETURN statement must be executed when the function is called.CREATE FUNCTION (SQL Scalar) ALLOW PARALLEL Specifies that the function can be run in parallel. Statements 485 . SQL-routine-body Specifies a single SQL statement.” on page 779 for more information about defining SQL functions. DYNDFTCOL. SET CONNECTION. if you specify one or more of the following clauses: v NOT DETERMINISTIC v EXTERNAL ACTION v MODIFIES SQL DATA Otherwise. See Chapter 6. The options CLOSQLCSR. functions are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema. | | | | Function authority: If SQL names are used. COMMIT. | | | | | | | | | | STATIC DISPATCH Specifies that the function is dispatched statically. If system names were specified. CNULRQD. see “SET OPTION” on page 734. ROLLBACK and SET TRANSACTION statement is not allowed in a function. If system names are used. | | | If the SQL-routine-body is a compound statement. functions are created with the system authority of *EXCLUDE on *PUBLIC. Notes General Considerations for Defining User-defined Functions: See “CREATE FUNCTION” on page 436 for general information on defining user-defined functions. All functions are statically dispatched. DFTRDBCOL. The default is DISALLOW PARALLEL. “SQL Control Statements. DISALLOW PARALLEL Specifies that the function cannot be run in parallel. RELEASE. ALLOW PARALLEL is the default. the owner of the function is the user profile with the same name as the schema into which the function is created. Otherwise. DISCONNECT. For example. the owner of the function is the user profile or group user profile of the job executing the statement. the following statement could be included: SET OPTION DBGVIEW = *STMT For more information.

If a function is specified in the select-list of a select-statement and if the function specifies EXTERNAL ACTION or MODIFIES SQL DATA. | | | | | | | Identifier Resolution: If the tables specified in a routine body exist. SQL parameter. and the label name for SQL variables. If the specific name is not a valid system name. Otherwise. If the *SRVPGM object is saved and then restored to this or another system. 486 DB2 UDB for iSeries SQL Reference V5R2 . it will be overlaid. The function’s attributes are saved in the associated service program object. | | | | | | Creating the Function: When an SQL function is created. and an error is issued. a unique name is generated using the rules for generating system table names. v If the signature is not unique. all references in the routine body of an SQL routine are resolved to identify a particular column. the catalogs are automatically updated with those attributes. qualify the duplicate names by using the table designator for columns. v If the specific name was not specified.CREATE FUNCTION (SQL Scalar) If the owner of the function is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). If a program already exists in the specified library. the function name for parameters. If the tables do not exist. all names that exist as SQL variables or parameters are resolved to identify the variable or parameter when the function is created. that group profile will also have authority to the function. it runs in the activation group of the calling program. it will used as the name of member and program. During restore of the function: v If the specific name was specified when the function was originally created and it is not unique. The SQL options used to create the service program are the options that are in effect at the time the CREATE FUNCTION statement is executed. A *SRVPGM object is then created using the CRTSRVPGM command. the function cannot be registered. The remaining names are assumed to be columns bound to the tables when the function is invoked. the function will only be invoked for each row returned. the database manager creates a temporary source file that will contain C source code with embedded SQL statements. a unique name is generated using the rules for generating system table names. | | Invoking the Function: When an SQL function is invoked. or SQL variable at the time the SQL routine is created. an error is issued. | | | | | Syntax alternatives: The following keywords are synonyms supported for compatibility to prior releases. If duplicate names are used for columns and SQL variables and parameters. If the specific name is a valid system name. The specific name is used to determine the name of the source file member and *SRVPGM object. The service program is created with ACTGRP(*CALLER). If the member already exists. a unique name is generated if necessary. These keywords are non-standard and should not be used: v The keywords VARIANT and NOT VARIANT can be used as synonyms for NOT DETERMINISTIC and DETERMINISTIC. the UDF may be invoked for rows that are not selected.

CREATE FUNCTION TAN (X DOUBLE) RETURNS DOUBLE LANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC RETURN SIN(X)/COS(X) Notice that a parameter name (X) is specified for the input parameter to function TAN. The invocations of the SIN and COS functions. Example Define a scalar function that returns the tangent of a value using the existing SIN and COS built-in functions. pass the parameter X as input. The parameter name is used within the body of the function to refer to the input parameter. Statements 487 . Chapter 5. within the body of the TAN user-defined function.CREATE FUNCTION (SQL Scalar) | | v The keywords NULL CALL and NOT NULL CALL can be used as synonyms for CALLED ON NULL INPUT and RETURNS NULL ON NULL INPUT.

CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE FUNCTION (SQL Table) This CREATE FUNCTION (SQL table) statement creates an SQL table function at the current server. or v It has been granted the system authorities of *OBJOPR and *ADD on the table. v It has been granted the INSERT privilege on the table. v Administrative authority If a distinct type is referenced. Authorization The privileges held by the authorization id of the statement must include at least one of the following: v For the SYSFUNCS catalog view and SYSPARMS catalog table: – The INSERT privilege on the table. or you can issue this statement interactively. and – The system authority *EXECUTE on library QSYS2 v Administrative Authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. Invocation You can embed this statement in an application program. v It was granted the USAGE privilege to the distinct type. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type. It is an executable statement that can be dynamically prepared. Syntax 488 DB2 UDB for iSeries SQL Reference V5R2 . the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: – The USAGE privilege on the distinct type. and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. The function returns a single result table. The privileges held by the authorization ID of the statement must also include at least one of the following: v The following system authorities: – *USE to the Create Service Program (CRTSRVPGM) command or – *EXECUTE and *ADD to the library into which the function is created.

RETURNS TABLE ( column-name data-type2 ) SQL-routine-body SET OPTION-statement LANGUAGE SQL option-list | parameter-declaration: parameter-name data-type1 Chapter 5. Statements 489 .CREATE FUNCTION (SQL Table) CREATE FUNCTION function-name ( . parameter-declaration ) .

data-type2: built-in-type distinct-type-name built-in-type: SMALLINT INTEGER INT BIGINT (5.0 ( integer .0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( CHARACTER CHAR CHARACTER CHAR VARCHAR 1 ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer . integer ) ( integer ) VARYING ( integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 GRAPHIC ) CCSID integer ) ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 ) TIMESTAMP ( 200 ) DATALINK ( integer ) ROWID CCSID integer 490 DB2 UDB for iSeries SQL Reference V5R2 .CREATE FUNCTION (SQL Table) data-type1.

the function will be created in the schema that is specified by the qualifier.. If no qualifier is specified. the function will be created in the schema specified by the implicit or explicit qualifier. In general. you can give each parameter a name. scale. Statements 491 . Do not specify the same name more than once. For SQL naming. and the data type of each parameter (without regard for any length. The combination of name. parameter-name Specifies the name of the input parameter.CREATE FUNCTION (SQL Table) | option-list: (1) SPECIFIC specific-name NOT DETERMINISTIC IS DETERMINISTIC CALLED ON NULL INPUT RETURNS NULL ON NULL INPUT DISALLOW PARALLEL CARDINALITY integer STATIC DISPATCH READS SQL DATA CONTAINS SQL MODIFIES SQL DATA FENCED NOT FENCED EXTERNAL ACTION NO EXTERNAL ACTION Notes: 1 The optional clauses can be specified in a different order.. more than one function can have the same name if the function signature of each function is unique. For more information see “Choosing the Schema and Function Name” on page 436. Although not required. precision. The maximum number of parameters allowed is 90. If there is no current library. the function will be created in QGPL. Certain function names are reserved for system use. data-type1 Specifies the number of input parameters of the function and the data type Chapter 5. or CCSID attributes of the data type) must not identify a user-defined function that exists at the current server. For system naming.) Specifies the number of parameters of the function and the data type of each parameter. the function will be created in the current library (*CURLIB). schema name. SQL-routine-body: SQL-control-statement | | | | | | | | | | | | | | | | | | | | | | | | | | Description function-name Names the user-defined function. A parameter name must be specified for parameters in SQL functions. (parameter-declaration. the number of parameters..

If a CCSID is not specified. it is set to the function name. must not identify the specific name of another function or procedure that exists at the current server. This is especially important if the data type is graphic string data. or LONG VARGRAPHIC) or a distinct type. If a CCSID is specified and the CCSID of the return data is encoded in a different CCSID. RETURNS TABLE Specifies the output table of the function.CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | of each input parameter. if the CCSID of the return data is encoded in a different CCSID. In this case. SPECIFIC specific-name Provides a unique name for the function. column-name Specifies the name of a column of the output table. Do not specify the same name more than once. NOT 492 DB2 UDB for iSeries SQL Reference V5R2 . the CCSID is determined by the default CCSID at the current server at the time the function is invoked. Assume the number of parameters is N. for example: CREATE FUNCTION WOOFER() If a CCSID is specified. data-type2 Specifies the data type and attributes of the output. LANGUAGE SQL Specifies that this is an SQL function. There must be one entry in the list for each parameter that the function expects to receive. a unique name is generated similar to the rules used to generate unique table names. NOT DETERMINISTIC Specifies that the function will not always return the same result from successive function invocations with identical input arguments. To avoid any potential loss of characters during the conversion. In this case. The name is implicitly or explicitly qualified with a schema name. If unqualified. There must be no more than (247-(N*2))/2 columns. you must code an empty set of parentheses. the data is converted to the specified CCSID. DETERMINISTIC or NOT DETERMINISTIC Specifies whether the function is deterministic. the qualifier must be the same as the qualifier of the function name. the parameter will be converted to that CCSID prior to passing it to the function. The name. consider using CCSID 13488 (UCS-2 graphic string data). If qualified. including the schema name. If a CCSID is not specified the return data is converted to the CCSID of the job (or associated graphic CCSID of the job for graphic string return values). the implicit qualifier is the same as the qualifier of the function name. All the parameters for a function are input parameters. You can specify any built-in data type (except LONG VARCHAR. If specific name is not specified. A function can have no parameters. consider explicitly specifying a CCSID that can represent any characters that will be returned from the function. If a function or procedure with that specific name already exists.

Thus. FENCED The function will run in a separate thread.” on page 835 for a detailed list of the SQL statements that can be executed under each data access indication. making the function responsible for testing for null argument values. Statements 493 . what type. EXTERNAL ACTION should be specified if the function contains a reference to another function that has an external action. because multiple invocations of the same function in the same SQL statement may conflict with each other. The database manager verifies that the SQL issued by the function is consistent with this specification. MODIFIES SQL DATA The function can execute any SQL statement except those statements that are not supported in any function. if any. or all. CONTAINS SQL The function does not execute SQL statements that read or modify data. Since cursors can be kept open.CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | DETERMINISTIC should be specified if the function contains a reference to a special register or a non-deterministic function. CALLED ON NULL INPUT Specifies that the function is to be invoked. the function must be invoked with each successive function invocation. The result is the null value. the cursor position will also be preserved between calls to the function. DETERMINISTIC Specifies that the function will always return the same result from successive invocations with identical input arguments. See Appendix C. READS SQL DATA. argument values are null. NOT FENCED The function may run in the same thread as the invoking SQL statement. RETURNS NULL ON INPUT Specifies that the function is not invoked if any of the input arguments is null. EXTERNAL ACTION The function performs some external action (outside the scope of the function program). EXTERNAL ACTION or NO EXTERNAL ACTION Specifies whether the function contains an external action. or MODIFIES SQL DATA Specifies whether the function can execute any SQL statements and. CONTAINS SQL. Chapter 5. NOT FENCED functions can keep SQL cursors open across individual calls to the function. FENCED or NOT FENCED Specifies whether the function will run in the same thread as the invoking SQL statement or in a separate thread. if so. The function can return a null or nonnull value. RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT Specifies whether the function is called if any of the input arguments is null at execution time. READS SQL DATA The function does not execute SQL statements that modify data. “Characteristics of SQL Statements. FENCED is the safest option if the function contains SQL cursors.

“SQL Control Statements. SET CONNECTION. Table functions cannot run in parallel. CNULRQD. DYNDFTCOL. the owner of the function is the user profile or group user profile of the job executing the statement. See Chapter 6. COMMIT. functions are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema. SQL-routine-body Specifies a single SQL statement. DISALLOW PARALLEL Specifies that the function cannot be run in parallel. CARDINALITY integer This optional clause provides an estimate of the expected number of rows to be returned by the function for optimization purposes. Notes General Considerations for Defining User-defined Functions: See “CREATE FUNCTION” on page 436 for general information on defining user-defined functions. A call to a procedure that issues a CONNECT. It need not be called with each successive function invocation. the following statement could be included: SET OPTION DBGVIEW = *STMT For more information. including a compound statement. to create a debuggable function. the owner of the function is the user profile with the same name as the schema into which the function is created. SET OPTION-statement Specifies the options that will be used to create the function. ROLLBACK and SET TRANSACTION statement is not allowed in a function. STATIC DISPATCH Specifies that the function is dispatched statically. it must contain exactly one RETURN statement and it must be executed when the function is called. If system names are used. Function authority: If SQL names are used. DISCONNECT. the database manager will assume a finite value as a default. functions are created with the system authority of *EXCLUDE on *PUBLIC. the owner of the function is the user profile or group user profile of the job executing the statement.CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | NO EXTERNAL ACTION The function does not perform an external action. If the SQL-routine-body is a compound statement. 494 DB2 UDB for iSeries SQL Reference V5R2 .” on page 779 for more information about defining SQL functions. Otherwise. and NAMING are not allowed in the CREATE FUNCTION statement. If the CARDINALITY clause is not specified for a table function. DFTRDBCOL. Valid values for integer range from 0 to 2 147 483 647 inclusive. For example. If system names were specified. see “SET OPTION” on page 734. Function ownership: If SQL names were specified. All functions are statically dispatched. The options CLOSQLCSR. RELEASE.

Identifier Resolution: If the tables specified in a routine body exist. or SQL variable at the time the SQL routine is created. If the specific name is not a valid system name. Statements 495 . If duplicate names are used for columns and SQL variables and parameters. all references in the routine body of an SQL routine are resolved to identify a particular column. The SQL options used to create the service program are the options that are in effect at the time the CREATE FUNCTION statement is executed. it runs in the activation group of the calling program. an error is issued. v If the specific name was not specified. If the *SRVPGM object is saved and then restored to this or another system. Chapter 5. a unique name is generated if necessary. If the member already exists. the function name for parameters. qualify the duplicate names by using the table designator for columns. a unique name is generated using the rules for generating system table names. The service program is created with ACTGRP(*CALLER). and an error is issued. During restore of the function: v If the specific name was specified when the function was originally created and it is not unique.CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | If the owner of the function is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). it will used as the name of member and program. a unique name is generated using the rules for generating system table names. the function cannot be registered. The specific name is used to determine the name of the source file member and *SRVPGM object. the catalogs are automatically updated with those attributes. Syntax alternatives: The following keywords are synonyms supported for compatibility to prior releases. If the specific name is a valid system name. all names that exist as SQL variables or parameters are resolved to identify the variable or parameter when the function is created. it will be overlaid. A *SRVPGM object is then created using the CRTSRVPGM command. that group profile will also have authority to the function. Creating the Function: When an SQL function is created. Invoking the Function: When an SQL function is invoked. The function’s attributes are saved in the associated service program object. SQL parameter. v The keywords NULL CALL and NOT NULL CALL can be used as synonyms for CALLED ON NULL INPUT and RETURNS NULL ON NULL INPUT. and the label name for SQL variables. The remaining names are assumed to be columns bound to the tables when the function is invoked. the database manager creates a temporary source file that will contain C source code with embedded SQL statements. These keywords are non-standard and should not be used: v The keywords VARIANT and NOT VARIANT can be used as synonyms for NOT DETERMINISTIC and DETERMINISTIC. v If the signature is not unique. If the tables do not exist. If a program already exists in the specified library.

FIRSTNME FROM EMPLOYEE WHERE EMPLOYEE.LASTNAME. LASTNAME VARCHAR(15).DEPTNO 496 DB2 UDB for iSeries SQL Reference V5R2 .WORKDEPT =DEPTEMPLOYEES. CREATE FUNCTION DEPTEMPLOYEES (DEPTNO CHAR(3)) RETURNS TABLE (EMPNO CHAR(6). FIRSTNAME VARCHAR(12)) LANGUAGE SQL READS SQL DATA NO EXTERNAL ACTION DETERMINISTIC DISALLOW PARALLEL RETURN SELECT EMPNO.CREATE FUNCTION (SQL Table) | | | | | | | | | | | | | | | | | Example Define a table function that returns the employees in a specified department number.

then the privileges held by the authorization ID of the statement must include at least one of the following: v The system authority *ADD to the user profile with that name v Administrative authority Syntax CREATE UNIQUE WHERE NOT NULL ENCODED VECTOR INDEX index-name . Invocation This statement can be embedded in an application program or issued interactively. Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v The following system authorities: – *USE to the Create Logical File (CRTLF) command – *EXECUTE and *ADD to the library into which the index is created – *CHANGE to the data dictionary if the library into which the index is created is an SQL schema with a data dictionary v Administrative authority The privileges held by the authorization ID of the statement must also include at least one of the following: v The INDEX privilege on the table v Administrative authority The authorization ID of the statement has the INDEX privilege on the table when: v It is the owner of the table. and that name is different from the authorization ID of the statement. v It has been granted the INDEX or ALTER privilege to the table. It is an executable statement that can be dynamically prepared.CREATE INDEX CREATE INDEX The CREATE INDEX statement creates an index on a table at the current server. Statements 497 . ASC ON table-name ( column-name DESC ) Chapter 5. or v It has been granted the system authorities of either *OBJALTER or *OBJMGT to the table If SQL names are specified and a user profile exists that has the same name as the library into which the table is created.

view. The name. this is identical to UNIQUE.. For information on the rules for generating a name. otherwise. ENCODED VECTOR Specifies that the resulting index will be an encoded vector index (EVI).CREATE INDEX DISTINCT WITH integer VALUES Description UNIQUE Prevents the table from containing two or more rows with the same value of the index key. If system names were specified. An encoded vector index cannot be used to ensure an ordering of rows.. If SQL names were specified. table. When UNIQUE is used. The constraint is also checked during the execution of the CREATE INDEX statement. must not be the same as an index. The same column may be specified more than once. The table-name must identify a base table (not a view) that exists at the current server. see the Database Performance and Query Optimization book. if the key is a single column that can contain null values. see “Rules for Table Name Generation” on page 554. the index will be created in the schema specified by the implicit or explicit qualifier. or a distinct type based on a LOB 498 DB2 UDB for iSeries SQL Reference V5R2 . A column-name must not identify a LOB or DATALINK column. If the table already contains rows with duplicate key values. ) Identifies the list of columns that will be part of the index key. or file that already exists at the current server. If not qualified. DB2 UDB for iSeries will generate a system name. UNIQUE WHERE NOT NULL Prevents the table from containing two or more rows with the same nonnull value of the index key. . Multiple null values are allowed. For example. alias. ON table-name Identifies the table on which the index is to be created. the index is not created. The constraint is enforced when rows of the table are updated or new rows are inserted. that column can contain no more than one null value. (column-name. For more information. null values are treated as any other values. index-name Names the index. the index name will be created in the schema that is specified by the qualifier. including the implicit or explicit qualifier. Each column-name must be an unqualified name that identifies a column of the table. the index name will be created in the same schema as the table over which the index is created. It is used by the database manager to improve the performance of queries. If the index name is not a valid system name.

An index created over a distributed table is created on all of the servers across which the table is distributed. where n is the number of columns specified that allows nulls. This clause may be specified for any type of index. this is used as a hint to the optimizer. see the DB2 Multisystem book. That is the default. the key for SBCS data or mixed data is the weighted value of the key based on the sort sequence. If system names are used. the index entries are created when data is inserted into the table. If the owner of the index is a member of a group profile (GRPPRF keyword) and group authority is specified (GRPAUT keyword). and the sum of their byte lengths must not exceed 2000−n. the owner of the index is the user profile or group user profile of the job executing the statement. Index attributes: An index is created as a keyed logical file. Sort sequence: Any index created over columns containing SBCS or mixed data is created with the sort sequence in effect at the time the statement is executed. Index ownership: If SQL names were specified. ASC Puts the index entries in ascending order by the column. CREATE INDEX creates the index entries for it. Chapter 5. For more information about distributed tables. that group profile will also have authority to the index.CREATE INDEX or datalink column. The number of columns must not exceed 120. the owner of the index is the user profile with the same name as the schema into which the index is created. For non-encoded vector indexes. Otherwise. indexes are created with the authority to *PUBLIC as determined by the create authority (CRTAUT) parameter of the schema. Statements 499 . For encoded vector indexes this is used to determine the initial size of the codes assigned to each distinct key value. For sort sequences other than *HEX. the file wait time and record wait time attributes are set to the default that is specified on the WAITFILE and WAITRCD keywords of the Create Logical File (CRTLF) command. DESC Puts the index entries in descending order by the column. Notes Effects of the statement: CREATE INDEX creates a description of the index. indexes are created with the system authority of *EXCLUDE on *PUBLIC. WITH integer DISTINCT VALUES Specifies the estimated number of distinct key values. Index authority: If SQL names are used. The default value is 256. If system names were specified. If the named table already contains data. the owner of the index is the user profile or group user profile of the job executing the statement. If the table does not yet contain data. When an index is created.

The index entries are to be in ascending order. JOB) 500 DB2 UDB for iSeries SQL Reference V5R2 . Arrange the index entries in ascending order by job title (JOB) within each department (WORKDEPT). CREATE INDEX JOB_BY_DPT ON EMPLOYEE (WORKDEPT.CREATE INDEX Examples Example 1: Create an index named UNIQUE_NAM on the PROJECT table. The purpose of the index is to ensure that there are not two entries in the table with the same value for project name (PROJNAME). CREATE UNIQUE INDEX UNIQUE_NAM ON PROJECT(PROJNAME) Example 2: Create an index named JOB_BY_DPT on the EMPLOYEE table.

COBOL or Java. This can be useful when the value of the parameter is very large. The specific name can be used to uniquely identify the procedure when dropping. This means that two different schemas can each contain a procedure with the same name that have the same number of parameters. which might have different representations on different platforms: v FLOAT. Statements 501 . it is recommended that a specific name also be specified. The external executable is referenced by a procedure defined at the current server along with various attributes of the procedure. Chapter 5. v SQL The procedure is written exclusively in SQL. However. AS LOCATOR can not be specified for SQL procedures. Specifying AS LOCATOR for a Parameter: Passing a locator instead of a value can result in fewer bytes being passed in or out of the procedure. a schema must not contain two procedures with the same name that have the same number of parameters. or commenting on the procedure. If the SPECIFIC clause is not specified. granting to. Use DOUBLE or REAL instead. The signature of a procedure is the qualified procedure name combined with the number of the input parameters (the data types of the parameters are not part of a procedure’s signature). Specify AS LOCATOR only for parameters with a LOB data type or a distinct type based on a LOB data type. v NUMERIC. revoking from. do not use the following data types. See “CREATE PROCEDURE (External)” on page 502.CREATE PROCEDURE | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE PROCEDURE The CREATE PROCEDURE statement defines a procedure at the current server. See “CREATE PROCEDURE (SQL)” on page 513. The procedure body is defined at the current server along with various attributes of the procedure. The following types of procedures can be defined: v External The procedure program is written in a programming language such as C. Determining the Uniqueness of Procedures in a Schema: At the current server. a specific name is generated. Notes Choosing Data Types for Parameters: For portability of procedures across platforms that are not DB2 UDB for iSeries. each procedure signature must be unique. The AS LOCATOR clause specifies that a locator to the value of the parameter is passed instead of the actual value. Use DECIMAL instead. The Specific Name for a Procedure: When defining multiple procedures with the same name and schema (with different number of parameters).

Authorization The privileges held by the authorization ID of the statement must include at least one of the following: v For the SYSPROCS catalog view and SYSPARMS catalog table: – The INSERT privilege on the table. and – The system authority *EXECUTE on library QSYS2 v Administrative authority The authorization ID of the statement has the INSERT privilege on a table when: v It is the owner of the table. v It was granted the system authorities of *OBJOPR and *EXECUTE to the distinct type. Invocation This statement can be embedded in an application program or issued interactively. and – The system authority *EXECUTE on the library containing the distinct type v Administrative authority The authorization ID of the statement has the USAGE privilege on a distinct type when one of the following is true: v It is the owner of the distinct type. the privileges held by the authorization ID of the statement must include at least one of the following: v For the external program referenced in the SQL statement: – The system authority *EXECUTE on the external program. It is an executable statement that can be dynamically prepared. and – The system authority *EXECUTE on the library containing the external program v Administrative authority | | | | | | | | | | | | If a distinct type is referenced. the privileges held by the authorization ID of the statement must include at least one of the following: v For each distinct type identified in the statement: – The USAGE privilege on the distinct type. Syntax 502 DB2 UDB for iSeries SQL Reference V5R2 . v It was granted the USAGE privilege to the distinct type. or v It has been granted the system authorities of *OBJOPR and *ADD on the table.CREATE PROCEDURE (External) CREATE PROCEDURE (External) The CREATE PROCEDURE (External) statement defines an external procedure at the current server. v It has been granted the INSERT privilege on the table. If the external program exists.

CREATE PROCEDURE (External) CREATE PROCEDURE procedure-name ( . Chapter 5. parameter-declaration ) option-list parameter-declaration: IN data-type OUT INOUT parameter-name AS LOCATOR option-list: PARAMETER STYLE (1) LANGUAGE C C++ CL COBOL COBOLLE FORTRAN JAVA PLI REXX RPG RPGLE PARAMETER STYLE DB2GENERAL DB2SQL GENERAL GENERAL WITH NULLS JAVA SQL NOT DETERMINISTIC DETERMINISTIC MODIFIES SQL DATA NO SQL CONTAINS SQL READS SQL DATA CALLED ON NULL INPUT DYNAMIC RESULT SETS 0 DYNAMIC RESULT SETS integer NO DBINFO DBINFO FENCED NOT FENCED PROGRAM TYPE MAIN EXTERNAL EXTERNAL NAME external-program-name SPECIFIC specific-name OLD SAVEPOINT LEVEL NEW SAVEPOINT LEVEL COMMIT ON RETURN NO COMMIT ON RETURN YES Notes: 1 The optional clauses can be specified in a different order. Statements 503 .

CREATE PROCEDURE (External) data-type: built-in-type distinct-type-name built-in-type: | SMALLINT INTEGER INT BIGINT (5.0 ( integer . integer ) ( integer ) VARYING ( integer ) ( 1M ) CLOB CHAR LARGE OBJECT CHARACTER LARGE OBJECT ( integer K M G ) FOR SBCS DATA FOR MIXED DATA CCSID integer ( 1 GRAPHIC ) CCSID integer ) ( integer ) GRAPHIC VARYING ( integer VARGRAPHIC ( 1M ) DBCLOB ( integer K M G ( BLOB BINARY LARGE OBJECT ( ) 1M ) integer K M G ) DATE ( 0 ) TIME ( 6 ) TIMESTAMP ROWID 504 DB2 UDB for iSeries SQL Reference V5R2 .0) DECIMAL DEC NUMERIC ( 53 ) FLOAT ( integer ) REAL PRECISION DOUBLE ( CHARACTER CHAR CHARACTER CHAR VARCHAR 1 ) FOR BIT DATA FOR SBCS DATA FOR MIXED DATA CCSID integer .

. (parameter-declaration. Although not required. A DataLink or a distinct type based on a DataLink may not be specified as an output parameter. When the language type is REXX. only 90 parameters are allowed. The name cannot be the same as any other parameter-name for the procedure. For system naming. For SQL naming. The maximum number of parameters allowed in CREATE PROCEDURE is 255. the number of parameters must not identify a procedure that exists at the current server. INOUT Identifies the parameter as both an input and output parameter for the procedure. you can give each parameter a name. 51. For more information about data types.) Specifies the number of parameters of the procedure and the data type of each parameter. DataLinks are not valid for external procedures. Chapter 5. only for output.. If GENERAL WITH NULLS is specified. the maximum is 254. the procedure will be created in the schema specified by the implicit or explicit qualifier. parameter-name Names the parameter. the procedure will be created in the current library (*CURLIB). A DataLink or a distinct type based on a DataLink may not be specified as an input and output parameter. The maximum number of parameters is also limited by the maximum number of parameters allowed by the licensed program used to compile the external program. see “CREATE TABLE” on page 526. IN Identifies the parameter as an input parameter to the procedure. If no qualifier is specified. The data type must be valid for the language specified in the language clause. schema name. The combination of name. If a CCSID is not specified. A parameter for a procedure can be used only for input.51 OUT Identifies the parameter as an output parameter that is returned by the procedure. If parameter style SQL is specified. Any changes made to the parameter within the procedure are not available to the calling SQL application when control is returned. and the SQL Programming Concepts book. the parameter will be converted to that CCSID prior to passing it to the procedure. If a CCSID is specified. data-type Specifies the data type of the parameter.. the CCSID is determined by the default CCSID at the current server at the time the procedure is called. all parameters must be input parameters. the procedure will be created in the schema specified by the qualifier. Statements 505 .CREATE PROCEDURE (External) Description procedure-name Names the procedure. or for both input and output.

REXX The external program is a REXX procedure. COBOL The external program is written in COBOL. LANGUAGE Specifies the language that the external program is written in. You can specify AS LOCATOR only if the input parameter has a LOB data type or a distinct type based on a LOB data type. PARAMETER STYLE Specifies the conventions used for passing parameters to and returning the values from procedures: SQL Specifies that in addition to the parameters on the CALL statement.CREATE PROCEDURE (External) AS LOCATOR Specifies that the input parameter is a locator to the value rather than the actual value. v N parameters for indicator variables for the parameters. If LANGUAGE is not specified. The SQLSTATE returned indicates the success or failure of the procedure. The parameters are defined to be in the following order: v The first N parameters are the parameters that are specified on the CREATE PROCEDURE statement. 506 DB2 UDB for iSeries SQL Reference V5R2 . then the language is assumed to be C. the LANGUAGE is determined from the program attribute information associated with the external program at the time the procedure is created. C The external program is written in C. If the program attribute information associated with the program does not identify a recognizable language or the program cannot be found. CL The external program is written in CL. The SQLSTATE returned is assigned by the external program. COBOLLE The external program is written in ILE COBOL. v A CHAR(5) output parameter for SQLSTATE. FORTRAN The external program is written in FORTRAN. PLI The external program is written in PL/I. RPG The external program is written in RPG. C++ The external program is written in C++. several additional parameters are passed to the procedure. JAVA The external program is written in JAVA. The language clause is required if the external program is a REXX procedure. RPGLE The external program is written in ILE RPG.

if DBINFO was specified on the CREATE PROCEDURE statement. Additional arguments are not passed for indicator variables. for C. INOUT and OUT parameters will be passed as single entry arrays to facilitate returning values. For more information about the parameters passed. several additional parameters are passed to the procedure. For details on passing parameters in JAVA. For more information about how the indicators are handled. see the SQL Programming Concepts book. GENERAL Specifies that the procedure will use a parameter passing mechanism where the procedure receives the parameters specified on the CALL. v A VARCHAR(128) input parameter for the specific name. see the include sqludf in the appropriate source file. except that the following additional parameter may be passed as the last parameter: v A parameter for the dbinfo structure. another argument is passed to the procedure. Statements 507 . This additional argument contains an indicator array with an element for each of the parameters of the CALL statement. sqludf can be found in QSYSINC/H. sqludf can be found in QSYSINC/H. DB2SQL is identical to the SQL parameter style. | | | | | DB2GENERAL Specifies that the procedure will use a parameter passing convention that is defined for use with Java methods. PARAMETER STYLE DB2GENERAL can only be specified with LANGUAGE JAVA. PARAMETER STYLE GENERAL WITH NULLS cannot be used with LANGUAGE JAVA. v A VARCHAR(70) output parameter for the message text. | | | | | JAVA Specifies that the procedure will use a parameter passing convention that conforms to the Java language and SQLJ Routines specification. DB2SQL Specifies that in addition to the parameters on the CALL statement. PARAMETER STYLE SQL cannot be used with LANGUAGE JAVA. for C. v A VARCHAR(517) input parameter for the fully qualified procedure name. Chapter 5. see the Developer Kit for Java book. For example. this would be an array of short ints. For example. PARAMETER STYLE DB2SQL cannot be used with LANGUAGE JAVA. GENERAL WITH NULLS Specifies that in addition to the parameters on the CALL statement as specified in GENERAL. In C. you should write Java procedures that use the PARAMETER STYLE JAVA conventions. see the include sqludf in the appropriate source file. For more information about the parameters passed.CREATE PROCEDURE (External) The user may set the SQLSTATE to any valid value in the external program to return an error or warning from the function. PARAMETER STYLE GENERAL cannot be used with LANGUAGE JAVA. For increased portability.

If zero is specified. If the format of the name is not correct. JDBC on the iSeries server. DISCONNECT. For example. an error is returned. CONNECT. Thus. the result set starts with the current position. For more information about result sets see “SET RESULT SETS” on page 751. see the Developer Kit for Java book. the result set will start with the 6th row of the result set. The validity of the name is checked at the server. see the SQL Programming Concepts book. For more information. SET CONNECTION. COMMIT and ROLLBACK statements are not allowed in an ATOMIC SQL procedure. but it must exist at the time the procedure is called. The program cannot be an ILE service program. DYNAMIC RESULT SETS integer Specifies the maximum number of result sets that can be returned from the procedure. The name is implicitly or explicitly qualified with a schema name. only 100 procedures can have result sets that are waiting to be fetched. the implicit qualifier is the same as the qualifier of the procedure name.CREATE PROCEDURE (External) | | | PARAMETER STYLE JAVA can only be specified with LANGUAGE JAVA. ROLLBACK and SET TRANSACTION statements are not allowed in a procedure that is running on a remote server. The name. If unqualified. COMMIT. For details on passing parameters in JAVA. If the naming option is *SYS and the program name is not qualified. integer must be greater than or equal to zero. or the SQL Call Level Interface. no result sets are returned. SPECIFIC specific-name Provides a unique name for the procedure. the number of results returned is the minimum of the number of result sets specified on this keyword and the SET RESULTS SET statement. but at any time. The external program need not exist at the time the procedure is created. 508 DB2 UDB for iSeries SQL Reference V5R2 . If the SET RESULT SETS statement is issued. and v the external program does not have an attribute of ACTGRP(*NEW). the external program name is assumed to be the same as the procedure name. the library list will be used to search for the program at the time the procedure is called. Result sets are only returned if both the following ar true: v the procedure is called from a iSeries Access client ODBC or JDBC driver. in C. any VARCHAR or CHAR parameters are passed as NUL-terminated strings. A procedure can have any number of result sets. If qualified. If external-program-name is not specified. Note that language of the external procedure determines how the parameters are passed. The program name must identify a program that exists at the server at the time the procedure is called. RELEASE. the qualifier must be the same as the qualifier of the procedure name. The result sets are scrollable. including the schema name. If a cursor is used to return a result set. if 5 FETCH NEXT operations have been performed prior to returning from the procedure. EXTERNAL NAME external-program-name Specifies the program that will be executed when the procedure is called by the CALL statement. must not identify the specific name of another procedure or function that exists at the current server.

FENCED or NOT FENCED This parameter is allowed for compatibility with other products and is not used by DB2 UDB for iSeries. DBINFO fields Field Relational database Data Type VARCHAR(128) Description The name of the current server. READS SQL DATA. Chapter 5. may be executed in the procedure or any routine called from this procedure. even when the referenced data in the database has not changed. or all. if any. DETERMINISTIC or NOT DETERMINISTIC Specifies whether the procedure returns the same results each time the procedure is called with the same IN and INOUT arguments. NOT DETERMINISTIC The procedure always returns the same results each time the procedure is called with the same IN and INOUT arguments. | | PROGRAM TYPE MAIN Specifies that the procedure executes as a main routine. CONTAINS SQL Specifies that SQL statements that neither read nor modify SQL data can be executed by the procedure. if any.H. Table 47 contains a description of the DBINFO structure. it is the same as the procedure name.” on page 835 for a detailed list of the SQL statements that can be executed under each data access indication. See Appendix C. argument values are null. Detailed information about the DBINFO structure can be found in include file SQLUDF in QSYSINC. NO SQL Specifies that the procedure cannot execute any SQL statements. DBINFO Specifies that the database manager should pass a structure containing status information to the procedure. or NO SQL Specifies which SQL statements. “Characteristics of SQL Statements. The function can return a null or nonnull value. READS SQL DATA Specifies that SQL statements that do not modify SQL data can be included in the procedure. provided the referenced data in the database has not changed. Table 47. CALLED ON NULL INPUT Specifies that the function is to be invoked. If a function or procedure with that specific name already exists. MODIFIES SQL DATA. MODIFIES SQL DATA Specifies that the procedure can execute any SQL statement except statements that are not supported in procedures. making the function responsible for testing for null argument values. Statements 509 . DBINFO is only allowed with PARAMETER STYLE DB2SQL. a unique name is generated similar to the rules used to generate unique table names.CREATE PROCEDURE (External) If specific-name is not specified. DETERMINISTIC The procedure may not return the same result each time the procedure is called with the same IN and INOUT arguments. | | | | | | | | | | | | | | | | | | | | CONTAINS SQL.

v Reserved If a CCSID is not explicitly specified for a parameter on the CREATE PROCEDURE statement. Any SAVEPOINT statements issued within the procedure with OLD SAVEPOINT LEVEL implicitly or explicitly specified on the SAVEPOINT statement are created at the same savepoint level as the caller of the procedure. NO is the default. OLD SAVEPOINT LEVEL A new savepoint level is not created. If the procedure returns with an error. Therefore. a commit is not issued.CREATE PROCEDURE (External) Table 47. | | | | | | | | | | | | | | | | | | | | | | | | OLD SAVEPOINT LEVEL or NEW SAVEPOINT LEVEL Specifies whether a new savepoint level is to be created on entry to the procedure. YES The database manager issues a commit if the procedure returns successfully. release. COMMIT ON RETURN Specifies whether the database manager commits the transaction immediately on return from the procedure. Target Column VARCHAR(128) VARCHAR(128) VARCHAR(128) Version and release Platform CHAR(8) INTEGER The version. 510 DB2 UDB for iSeries SQL Reference V5R2 . If the CCSID of the input string is not the same as the CCSID of the parameter. The CCSID information of the job. the name of any new savepoint set within the procedure will not conflict with any existing savepoints set in higher savepoint levels (such as the savepoint level of the calling program) with the same name. NEW SAVEPOINT LEVEL A new savepoint level is created on entry to the procedure. and modification level of the database manager. Not applicable for a call to a procedure. The following information identifies the CCSID: v SBCS CCSID v DBCS CCSID v Mixed CCSID v Indication of which of the first three CCSIDs is appropriate. This is the default. the input string is assumed to be encoded in the CCSID of the job at the time the function is executed. the input string passed to the external function will be converted before calling the external program. The server’s platform type. NO The database manager does not issue a commit when the procedure returns. Any savepoints set within the procedure are created at a savepoint level that is nested deeper than the level at which this procedure was invoked. DBINFO fields (continued) Field Authorization ID CCSID Information Data Type VARCHAR(128) INTEGER INTEGER INTEGER INTEGER CHAR(8) Description The run-time authorization ID.

the procedure cannot be registered. an error is issued. During restore of the procedure: v If the specific name was specified when the procedure was originally created and it is not unique. the attributes from the DECLARE PROCEDURE statement will be used rather than the attributes from the CREATE PROCEDURE statement. Invoking the Procedure: If a DECLARE PROCEDURE statement defines a procedure with the same name as a created procedure. ACTGRP(*CALLER) should normally be used so that the procedure runs in the same activation group as the calling program. v The external program must be an ILE *PGM object. However. v If the procedure name and number of parameters is not unique. and an error is issued. the procedure will still be created. the catalogs are automatically updated with those attributes. Chapter 5.52 If the procedure returns result sets. Statements 511 . The attributes can saved for external procedures subject to the following restrictions: v The external program library must not be SYSIBM. or QSYS2. If the *PGM object is saved and then restored to this or another system. | 52. If the external program was created with ACTGRP(*NEW) and the job commitment definition is not used. and a static CALL statement where the procedure name is not identified by a host variable is executed from the same source program. an attempt is made to save the procedure’s attributes in the associated program object. the cursors that are associated with the result sets must have been defined as WITH HOLD to be usable after the commit. If the object cannot be updated. v The external program must contain at least one SQL statement.CREATE PROCEDURE (External) | | | | | The commit operation includes the work that is performed by the calling application process and the procedure. The CREATE PROCEDURE statement applies to static and dynamic CALL statements as well as to a CALL statement where the procedure name is identified by a host variable. Creating the Procedure: When an external procedure associated with an ILE external program is created. When an external procedure is invoked. the work that is performed in the procedure will be committed or rolled back as a result of the activation group ending. v The external program must exist when the CREATE PROCEDURE statement is issued. QSYS. it runs in whatever activation group was specified when the external program was created. v If the specific name was not specified. a unique name is generated if necessary. Notes General Considerations for Defining Procedures: See “CREATE PROCEDURE” on page 501 for general information on defining procedures.

If an error occurs while running a Java procedure. OUT NUM_PARTS INTEGER. Example Example 1: Create the procedure definition for a procedure. v DYNAMIC RESULT SET. total part cost and a result set that lists the part numbers. OUT QUANTITY INTEGER) LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME ’parts.CREATE PROCEDURE (External) Notes for Java Procedures: To be able to run Java procedures. CREATE PROCEDURE PARTS_ON_HAND (IN PARTNUM INTEGER. that is passed a part number and returns the cost of the part and the quantity that are currently available.2). v The keywords SIMPLE CALL can be used as a synonym for GENERAL. written in C. These keywords are non-standard and should not be used: v The keywords VARIANT and NOT VARIANT can be used as synonyms for NOT DETERMINISTIC and DETERMINISTIC. OUT COST DECIMAL(7. quantity and unit cost of each part. an SQLCODE of -443 will be returned. v The keywords NULL