embedded sq l

Upload: german-eduardo-lopez-velez

Post on 02-Jun-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Embedded Sq l

    1/55

    Firebird

    Embedded SQLGuide for RM/Cobol

  • 8/11/2019 Embedded Sq l

    2/55

  • 8/11/2019 Embedded Sq l

    3/55

    Embedded SQL Guide for RM/Cobol 3

    Table of Contents

    1. Program Structure...............................................................................................................................6

    1.1. General...........................................................................................................................................61.2. Reading this Guide.........................................................................................................................61.3. efinition of !erms........................................................................................................................61.". e#laring $ost %ariables...............................................................................................................&1.'. e#laring and (##essing atabases...............................................................................................&1.6. !ransa#tions....................................................................................................................................&1.&. SQL Statements..............................................................................................................................)1.). Statement $andles..........................................................................................................................)1.*. +nami# SQL ,SQL-...................................................................................................................)1.1. Error $andling..............................................................................................................................)

    2. Using Databases..................................................................................................................................10

    2.1. e#laring a atabase....................................................................................................................12.1.1. Conne#tion Strings................................................................................................................12.1.2. SE! (!((SE.................................................................................................................12.1.3. SE! 0(MES........................................................................................................................11

    2.2. ening a atabase......................................................................................................................112.2.1. C00EC!...........................................................................................................................11

    2.3. Closing a atabase.......................................................................................................................132.3.1. SC00EC!.....................................................................................................................13

    3. Using Transactions.............................................................................................................................143.1. !ransa#tion eha4iour..................................................................................................................1"

    3.1.1. (##ess Mode.........................................................................................................................1"3.1.2. Lo#5 Resolution....................................................................................................................1"3.1.3. solation Le4el......................................................................................................................1"

    3.2. Starting a !ransa#tion...................................................................................................................1'3.2.1. SE! !R(0S(C!0..........................................................................................................1'

    3.3. Sa4ing our Changes...................................................................................................................163.3.1. CMM!..............................................................................................................................16

    3.". is#arding our Changes.............................................................................................................163.".1. RLL(C7.........................................................................................................................16

    4. Accessing the Data..............................................................................................................................1".1. Suorted ata !+es..................................................................................................................1)".2. SQL E8ressions..........................................................................................................................2

    ".2.1. 9re#eden#e of erators.......................................................................................................21

    ".2.2. String Con#atenation............................................................................................................21".2.3. (rithmeti# erators............................................................................................................21".2.". Comarison erators..........................................................................................................22

    ".2.".1. E!:EE0...................................................................................................................22".2.".2. C0!(00G..............................................................................................................22".2.".3. 0..................................................................................................................................23".2.".". L7E..............................................................................................................................23".2.".'. S 0;LL........................................................................................................................23".2.".6. S!(R!0G :!$........................................................................................................2"".2.".&. (LL...............................................................................................................................2"

  • 8/11/2019 Embedded Sq l

    4/55

    " Embedded SQL Guide for RM/Cobol

    ".2.".). (0 or SME.............................................................................................................2"".2.".*. E

    ".". nserting ata...............................................................................................................................3&".".1. !he 0SER! Statement........................................................................................................3&

    ".'. ;dating ata...............................................................................................................................3)".'.1. !he ;9(!E statement.......................................................................................................3)

    ".6. eleting ata................................................................................................................................3*".6.1. !he ELE!E Statement.......................................................................................................3*

    !. Accessing "lob Data...........................................................................................................................40'.1. Retrie4ing lob ata...................................................................................................................."

    '.1.1. Retrie4ing the lob .........................................................................................................."'.1.2. Retrie4ing the lob ata......................................................................................................"1

  • 8/11/2019 Embedded Sq l

    5/55

    Embedded SQL Guide for RM/Cobol '

    '.1.2.1. e#laring RE( L Cursors.................................................................................."1'.1.2.2. ening RE( L Cursors...................................................................................."1'.1.2.3. =et#hing lob ata......................................................................................................."1'.1.2.". Closing RE( L Cursors....................................................................................."2

    '.2. ;dating lob ata......................................................................................................................"2

    '.2.1. nserting lob ata..............................................................................................................."2'.2.1.1. e#laring L 0SER! Cursors..............................................................................."2'.2.1.2. ening L 0SER! Cursors................................................................................."2'.2.1.3. nserting lob ata......................................................................................................."3'.2.1.". Closing L :R!E Cursors...................................................................................."3

    '.2.2. ;dating the lob ............................................................................................................"3'.3. eleting lob ata.......................................................................................................................""

    6. Using Store# Proce#ures...................................................................................................................4!6.1. ;sing Sele#t 9ro#edures..............................................................................................................."'6.2. ;sing E8e#utable 9ro#edures......................................................................................................."'

    $. Using %&ents.......................................................................................................................................4$

    &.1. Signaling E4ent ##urren#e........................................................................................................."&&.2. Registering nterest in E4ents......................................................................................................."&&.3. :aiting for an E4ent...................................................................................................................."&

    . 'iscellaneous Statements..................................................................................................................4().1. RELE(SE>REQ;ES!S.............................................................................................................."*

    (. )an#ling %rrors.................................................................................................................................!0*.1. :$E0E%ER................................................................................................................................'*.2. Che#5ing SQLCE ire#tl+.....................................................................................................'1*.3. isla+ing Error Messages...........................................................................................................'1

    *.3.1. rm#>status>address...............................................................................................................'1*.3.2. is#>interrete.........................................................................................................................'1

    10. Com*iling an# +unning ,our Program........................................................................................!31.1. Comiling our 9rogram...........................................................................................................'31.2. Running our 9rogram..............................................................................................................''

  • 8/11/2019 Embedded Sq l

    6/55

    6 Embedded SQL Guide for RM/Cobol

    1. Program Structure

    1.1. General

    (n embedded SQL ali#ation is an ali#ation in ?hi#h the SQL statements needed to a##ess data from the databasemanager are #oded dire#tl+ into the sour#e #ode of the ali#ation. !hese SQL statements are #omiled into #ode@

    e8e#utable b+ the database manager@ at #omile time rather than at run time as is the #ase for d+nami# SQL ,SQL-ali#ations. !his results in a modest imro4ement in the ali#ationAs erforman#e. t also ma5es the ali#ationAs sour#e#ode easier to understand sin#e the SQL statements are lo#ated in the #ode at the la#e ?here the+ ?ill be e8e#uted ratherthan being buried in :R70GBS!R(GE.

    Embedded SQL ali#ations in#lude de#larations and statements ?hi#h tell the rero#essor@ g*re@ ho? the ali#ation is tointera#t ?ith the =irebird database manager. !he ali#ation must

    e#lare host 4ariables to use for data transfer bet?een the ali#ation and the database manager.

    e#lare all databases to be a##essed b+ the ali#ation.

    en@ all databases before the+ are a##essed b+ the ali#ation.

    Set the otions for and start all non default transa#tions used b+ the ali#ation.

    n#lude the SQL statements used to a##ess the ali#ationAs data.Close all transa#tions and databases before the ali#ation terminates.

    9ro4ide error handling.

    !his #hater tou#hes@ 4er+ briefl+@ on ea#h of these oints. More detail is gi4en in the follo?ing #haters.

    1.2. Reading this Guide

    !here are #ertain #on4entions used throughout this guide ?hen des#ribing the s+nta8 of SQL statements.

    :ords gi4en in uer #ase are reser4ed ?ords and must be t+ed as sho?n.

    :ords gi4en in lo?er #ase are user sulied.

    tems en#losed in bra#es@ D@ reresent a list of #hoi#es@ one of ?hi#h must be #hosen.

    tems en#losed in sFuare bra#5ets@ H@ reresent otional items.

    9un#tuation@ li5e semiB#olons and Fuotes@ must be t+ed as sho?n.

    1.. !efinition of "erms

    !here are #ertain terms used throughout this guide that ma+ be ne? to some users. elo? is a shorte8lanation of some of these terms.

    Tablesare similar to CL files.

    +o-sare similar to CL re#ords.

    Columnsare similar to CL fields.

    Cursorsare ointers into the ro?s of the result set of a SQL sear#h.

    +esult sets#ontain ro?s returned b+ a Fuer+.

    ( &ie-is a subset of one or more tables #ontaining some or all of the #olumns and some or all of the ro?s from the table,s-.

    !he 5e+?ord U//is used to refer to #olumns that do not ha4e a 4alue. !his is sometimes a diffi#ult #on#et for Cobolrogrammers to gras sin#e Ino 4alueJ is not eFui4alent to sa#es or Keros. ( #olumn 4alue has a 4alue of sa#es or Keros isT U//. ( #olumn the is U//?ill ne4er be #onsidered as eFual to a #olumn ?ith a 4alue@ ?hate4er that 4alue mighthaen to be. n fa#t@ a U//#olumn is not e4en #onsidered to be eFual to another U//#olumn. (n+ e8ression ?hi#hin#ludes U//e4aluates to un5no?n rather than a se#ifi# 4alue.

  • 8/11/2019 Embedded Sq l

    7/55

    Embedded SQL Guide for RM/Cobol &

    1.#. !eclaring $ost %ariables

    $ost 4ariables are standard Cobol data items that are used to transfer data bet?een the ali#ation and the databasemanager. $ost 4ariables are used in the follo?ing situations

    uring data retrie4al the 4alues of database fields are mo4ed into host 4ariables.

    uring insert or udate oerations the 4alues of host 4ariables are mo4ed into database fields.$ost 4ariables #an be used to hold the 4alues used in sear#h #onditions.

    Some embedded SQL rero#essors reFuire that all host 4ariables be de#lared bet?een EG0 ECL(RE SEC!0 andE0 ECL(RE SEC!0 de#larations. =or ortabilit+ reasons =irebird suorts these de#larations but it is not areFuirement of the =irebird rero#essor that host 4ariables be de#lared bet?een them. $ost 4ariables ma+ be de#laredan+?here a standard Cobol data item ma+ be de#lared@ either in the :R70GBS!R(GE or L07(GE se#tions.

    n addition to being able to de#lare host 4ariables in the usual@ Cobol ?a+ it is also ossible to de#lare a host 4ariable(SE 0 the definition of a database #olumn. ;sing (SE 0 ensures that the host 4ariable is of the roer siKe andt+e to hold the data from the database #olumn. =or e8amle@ the follo?ing statements both de#lare a shier address field

    01 WS-SHIP-ADDR PIC X(35).

    01 WS-SHIP-ADDR BASED ON LOADS.LD_SHIP_ADDR1.

    (ssuming that the #olumn L>S$9>(R1 from the table L(S is defined as a 3' #hara#ter te8t field these t?o linesof #ode are eFui4alent.

    1.&. !eclaring and 'ccessing !atabases

    Embedded SQL ali#ations #an a##ess multile =irebird databases simultaneousl+. Ea#h database must be de#lared andoened before it #an be a##essed b+ the ali#ation. 9rograms that a##ess onl+ a single database need not de#lare thedatabase or assign a database handle. nstead the database #an be se#ified on the g*re#ommand line.

    !he embedded SQL ali#ation must de#lare and oen the database before attemting to start a transa#tion or a##ess an+ ofthe database tables. ening a database erforms the follo?ing a#tions

    Conne#ts to the database manager

    en the database files

    (llo#ates the s+stem resour#es reFuired to manage the database #onne#tion

    !o de#lare a database the ali#ation uses the SE! (!((SE statement. !o oen the database it uses the C00EC!statement. =or e8amle@ the follo?ing #ode sniet de#lares a database and oens it

    EXEC SQL DECLARE DATABASE DB1 = 'sa!"#.$%&' .

    ...

    EXEC SQL CONNECT DB1 .

    efore terminating@ an embedded SQL ali#ation must #lose the database. !o #lose a database use the SC00EC!statement or the RELE(SE #lause of the CMM! and RLL(C7 statements.

    1.(. "ransactions

    (n understanding of transa#tion management is #entral to an+ SQL ali#ation. (ll data a##ess must be #arried out ?ithinthe #onte8t of a transa#tion. !he transa#tion is resonsible for ma5ing #ertain that all data #hanges ?ithin its s#oe eithersu##eed or fail as a unit. Effi#ient use of transa#tions ?ill result in a fast@ resonsi4e s+stem. neffi#ient use of transa#tions#an lead to a slo?@ sluggish s+stem or@ e4en ?orse@ a s+stem lagued b+ hangs and deadlo#5s.

    E4en though g*rero4ides automati# transa#tion management ?ouldnAt re#ommend using it. E8li#it transa#tionmanagement al?a+s gi4es better #ontrol and effi#ien#+.

    !o start a transa#tion the ali#ation uses the SE! !R(0S(C!0 statement. !his statement se#ifies the t+e oftransa#tion to be started@ RE( 0L or RE( :R!E@ the isolation le4el@ RE( CMM!!E or S0(9S$!@ thelo#5 resolution mode@ :(! or 0 :(!@ and other otions. t also@ otionall+@ names the transa#tion. !he transa#tionname be#omes imortant if +ou ?ant to use multile transa#tions ?ithin a single ali#ation.

  • 8/11/2019 Embedded Sq l

    8/55

    ) Embedded SQL Guide for RM/Cobol

    !o sa4e the #hanges made during a transa#tion@ the ali#ation uses the CMM! statement. !o dis#ard #hanges it uses theRLL(C7 statement.

    1.). SQL Statements

    SQL statements are al?a+s re#eded b+ EREQ;ES!S statement before terminating an+ subrograms using the E

  • 8/11/2019 Embedded Sq l

    9/55

    Embedded SQL Guide for RM/Cobol *

    RO* LOADS WHERE LD_LOAD_N+*BER = 1,35 . *O2E NEW ADDRESS4 TO WS-SHIP-ADDR.EXEC SQL +PDATE LOADS SET LD_SHIP_ADDR1 = WS-SHIP-ADDR WHERE LD_LOAD_N+*BER = 1,35 .

  • 8/11/2019 Embedded Sq l

    10/55

    1 Embedded SQL Guide for RM/Cobol

    2. 0sing !atabases

    !his #hater des#ribes ho? embedded SQL ali#ations use SQL statements to de#lare and a##ess databases. !here arethree SQL statements ?hi#h set u a database for a##ess

    SE! (!((SE de#lares a database handle and otionall+ #onfigures #ertain oerational arameters for thedatabase.

    SE! 0(MES otionall+ se#ifies the #hara#ter set in use b+ the ali#ation for C$(R@ %(RC$(R and !E

    C00EC! oens a database and otionall+ assigns 4alues to #ertain oerational arameters for the database.

    (ll databases must be #losed before the ali#ation terminates.

    2.1. !eclaring a !atabase

    efore a database #an be used in an ali#ation it must be de#lared using the SE! (!((SE statement to establish adatabase handle. ( database handle is a 32 bit integer 4alue that ro4ides a uniFue identifier for the database #onne#tion.atabase handles are used in subseFuent SQL statements to identif+ the database that the+ should a#t uon. atabasehandles #an also be used in ali#ations that a##ess multile databases simultaneousl+ to differentiate tables ?hen t?o or

    more databases ha4e identi#all+ named tables.

    Ea#h database handle must ha4e a name that is uniFue among all other 4ariables in the ali#ation and #annot be a Cobolreser4ed ?ord.

    t is ossible for an embedded SQL ali#ation to a##ess data from more than one database #on#urrentl+. !o do this +oumust de#lare ea#h database searatel+ using the SE! (!((SE statement. Ea#h de#laration must use a uniFue name forthe database handle.

    2.1.1. Connection Strings

    E4er+ database is referen#ed b+ using a #onne#tion string ,ath-. ( #onne#tion string #onsists of t?o arts an otionalser4er name and a latform se#ifi# ath to the database file itself. !here are se4eral different formats for #onne#tion stringsdeending on the roto#ol to be used to #ommuni#ate ?ith the database manager but sin#e ?e ?ill be using onl+ the !C9/9roto#ol ?ill onl+ des#ribe that format in this guide.

    !he #onne#tion string has the follo?ing format

    s#6#!a78

    Connection String for a in#o-s Ser&er

    9,:;%"# = LOBAL STATIC EXTERNF CO*PILETI*EF ILENA*EF '%&>a#' +SER '>a#' PASSWORD '!9%'F R+NTI*E ILENA*EF '%&>a#' 6a +SER '>a#' 6a PASSWORD '!9%' 6aFF

    SE! (!((SE de#lares a host 4ariable named #bhan#leto hold the database handle asso#iated ?ith #bname.(li#ations ?hi#h a##ess multile databases simultaneousl+ must use SE! (!((SE to #reate searate databasehandles for ea#h database.

  • 8/11/2019 Embedded Sq l

    11/55

    Embedded SQL Guide for RM/Cobol 11

    #bnameis the latform se#ifi# ath to the database. t must follo? the file naming #on4entions for the ser4er ?here thedatabase resides.

    !he /"A/arameter de#lares the handle to be global to the run unit. (ll subroutines e8e#uted as art of the #urrent rununit #an a##ess this handle. !he STATCarameter restri#ts a##essibilit+ of the handle to the #urrent sour#e module. !he%5T%+arameter #auses the handle to referen#e a global handle from another sour#e module. Global is the default.

    !he otional C'P/%T'%and +UT'%arameters allo? a single database handle to refer to one database at#omile time and a different database at run time. f these arameters are omitted or if onl+ C'P/%T'%is gi4en thehandle ?ill referen#e the same database at #omile time and run time. !he run time database #an be o4erridden b+ theC00EC! statement.

    !he US%+and PASS+Darameters sul+ the user id and ass?ord used to #onne#t to the database. !he #omiletime user id and ass?ord #an be o4erridden on the g*re#ommand line. !he run time user id and ass?ord #an beo4erridden b+ the C00EC! statement or b+ sul+ing their 4alues in the host 4ariables denoted b+ &ar.

    !his statement #auses a number of host 4ariables to be de#lared at the oint in the rogram ?here it is en#ountered. $en#e@this statement must be la#ed in :R70GBS!R(GE.

    E8amleWORGIN-STORAE SECTION.EXEC SQL

    SET DATABASE TL = CO*PILETI*E '9,:;>#;7?>_s7?>J' 6a AS %&8a>%"# %&8a>%"# /;>$?J_!7sKF /%!_s!#;sKF

  • 8/11/2019 Embedded Sq l

    12/55

    12 Embedded SQL Guide for RM/Cobol

    /;>$?J_!7sK = +SER 's#' 6a PASSWORD '!ass9%' 6a CACHE ?>7#J# B+ERSF /;>$?J_!7sKF

    f the all seems a little daunting@ ?ell it is. !his #an be restated in a form more familiar to Cobol rogrammers as

    ormat 1

    CONNECT TOF ALL DEA+LT +SER 's#' 6aF PASSWORD '!ass9%' 6aF CACHE ?>7#J# B+ERSFF

    ormat 2

    CONNECT TOF ';>>#;7?>_s7?>J' 6a AS %&8a>%"# %&8a>%"# ... +SER 's#' 6aF PASSWORD '!ass9%' 6aF CACHE ?>7#J# B+ERSFF

    ;se of A//or D%AU/T@ as in =ormat 1@ oens all databases se#ified b+ a SE! (!((SE statement. tionsse#ified ?ith A//or D%AU/Tal+ to all databases. ;se of =ormat 2 oens onl+ the database,s- gi4en in the

    C00EC! statement.7connection8string7is the latform se#ifi# ath to the database. f this arameter is omitted the #onne#tion string gi4enin the SE! (!((SE statement ?hi#h de#lared #bhan#leis used.

    #bhab#leis a database handle de#lared in a re4ious SE! (!((SE statement.

    !he US%+ and PASS+Darameters ro4ide the user name and ass?ord to be used to #onne#t to the databasemanager. f these arameters are omitted@ the ones gi4en in the SE! (!((SE statement ?ill be used.

    !he CAC)%arameter sets the number of database ages that #an be held in memor+ ,#a#hed-. (dusting this numberu?ard ?ill generall+ imro4e erforman#e ?hile adusting it do?n?ard ?ill generall+ degrade erforman#e. !heminimum 4alue for this arameter is "' ?hile the default and ma8imum 4alues are deendent on the database managerAs#onfiguration and the a4ailabilit+ of s+stem resour#es.

    %am*les

    Conne#t to all databases de#lared ?ith SE! (!((SE statements@ using the user name and ass?ord from the SE!(!((SE statement

    EXEC SQL SET DATABASE TL = '9,:;

  • 8/11/2019 Embedded Sq l

    13/55

    Embedded SQL Guide for RM/Cobol 13

    2.. Closing a !atabase

    :hen the ali#ation is finished ?ith a database@ the database should be #losed. ( database #an be #losed using theSC00EC! statement or the RELE(SE #lause of the CMM! and RLL(C7 statements. efore #losing adatabase +ou must CMM! or RLL(C7 all transa#tions affe#ting the databases,s- to be #losed. Closing a databasedoes the follo?ing

    Closes oen database files.

    Releases s+stem resour#es used b+ the database #onne#tion.

    is#onne#ts from the database manager.

    2..1. !5SC3EC"

    DISCONNECT ALL DEA+LT %&8a>%"# %&8a>%"#F ...F

    ;se of A//or D%AU/T#loses all oen databases.

    #bhan#leis the handle of a re4iousl+ oened database. ou #an se#if+ multile handles to #lose multile databases.

    %am*les

    Close all oen databases.

    EXEC SQL DISCONNECT ALL

    Close se#ifi# databases.

    EXEC SQL DISCONNECT TL I*

  • 8/11/2019 Embedded Sq l

    14/55

    1" Embedded SQL Guide for RM/Cobol

    . 0sing "ransactions

    (ll SQL data definition and data maniulation statements ta5e la#e ?ithin the #onte8t of a transa#tion. ( transa#tiondefines a unit of ?or5 that either su##eeds or fails as a unit. !ransa#tions are managed through the use of the SE!!R(0S(C!0@ CMM! and RLL(C7 statements.

    !ransa#tion management statements define the beginning and end of a transa#tion. !he+ also #ontrol its beha4iour and

    intera#tion ?ith other simultaneousl+ running transa#tions that share a##ess to the same data. !here are t?o t+e oftransa#tions in =irebird the default transa#tion ,SCB!R(0S- and named transa#tions.

    !he default transa#tion is used ?hen a statement ?hi#h reFuires a transa#tion is en#ountered ?ithout a re#eding SE!!R(0S(C!0 statement. efault beha4iour is defined for the default transa#tion but it #an be o4erridden b+ starting thedefault transa#tion using SE! !R(0S(C!0 and se#if+ing alternati4e beha4iour as arameters. n the absen#e of theg*re 9manual#ommand line arameter a default transa#tion ?ill be started automati#all+ ?hen needed and #ommitted ?henthe database is #losed.

    0amed transa#tions are al?a+s started using SE! !R(0S(C!0 statements. !hese statements ro4ide uniFue names forea#h transa#tion and usuall+ in#lude arameters that se#if+ the transa#tionAs beha4iour.

    .1. "ransaction eha6iour

    !ransa#tions #ontrol a##ess to data b+ simultaneousl+ e8e#uting ali#ations. !here are se4eral arameters ?hi#h definee8a#tl+ ho? the transa#tion beha4es ?hen multile ali#ations attemt to a##ess the same data at the same time. !hesebeha4iours fall into three grous a##ess mode@ isolation le4el and lo#5 resolution. (##ess mode determines ?hether thetransa#tion #an read or read and ?rite data. solation le4el determines ho? the transa#tions 4ie?s re#ords #ommitted b+other simultaneous transa#tions. Lo#5 resolution determines ?hether or not the transa#tion ?aits for resour#es lo#5ed b+other simultaneous transa#tions.

    f a transa#tion is started ?ithout se#if+ing an+ beha4iour arameters@ it is started ?ith the follo?ing default beha4iour

    READ WRITE WAIT ISOLATION LE2EL SNAPSHOT

    .1.1. 'ccess Mode

    (##ess mode is #ontrolled b+ the +%AD /,and +%AD +T%arameters in the SE! !R(0S(C!0 statement.+%AD /,allo?s the transa#tion to sele#t data from a table but it #annot insert@ udate or delete table data.

    f +our ali#ation is onl+ going to read data it is good ra#ti#e the start +our transa#tion using the +%AD /,roert+.!his ?ill ensure that +our ali#ation has the least ossible ima#t on other@ #on#urrentl+ e8e#uting transa#tions.

    .1.2. Loc7 Resolution

    ( transa#tion #an #hoose to ?ait for resour#es lo#5ed b+ another transa#tion to be released or it #an #hoose to failimmediatel+ if a lo#5 is dete#ted. !his beha4iour is #ontrolled b+ the lo#5 resolution arameters ATand AT.

    f +ou #hoose AT:the transa#tion ?ill ?ait until lo#5ed resour#es are released and ?ill then tr+ to rea#Fuire the lo#5. f+ou #hoose AT:the transa#tion ?ill fail ?ith a lo#5 #onfli#t error immediatel+ ?hen a lo#5 is dete#ted. f a ATtransa#tion fails@ it is +our resonsibilit+ to rollba#5 the transa#tion and tr+ again or gi4e u and reort the error.

    .1.. 5solation Le6el

    solation le4el determines ho? +our ali#ation 4ie?s #hanges made b+ other@ #on#urrentl+ e8e#uting transa#tions. !hereare three main isolation le4els SAPS)T@ SAPS)T TA"/% STA"/T,and +%AD C''TT%D.

    SAPS)Tisolation ro4ides a 4ie? of the database at the moment the transa#tion starts. our transa#tion ?ill bere4ented from seeing #hanges made b+ other transa#tions. !his isolation le4el is also 5no?n as reeatable read be#ause+ou #an read the same re#ord multile times and be assured that +ou ?ill al?a+s see the same 4ersion of the re#ord.

    SAPS)T TA"/% STA"/T,isolation ro4ides the same 4ie? of the database as SAPS)T?hile@ at the sametime@ re4enting other transa#tions from ma5ing #hanges to tables that +our transa#tions is reading and udating. thertransa#tions are allo?ed to read data from tables that +our transa#tion is reading and udating.

    +%AD C''TT%Disolation allo?s +our transa#tion to read the most re#ent 4ersion of a ro? #ommitted b+ other a#ti4etransa#tions. !here are t?o further otions #ontrolling the beha4iour of +%AD C''TT%Dtransa#tions+%C+D8;%+Sand +%C+D8;%+S. :hen +%C+D8;%+Sis se#ified +our transa#tion readsthe most re#entl+ #ommitted 4ersion of a ro? e4en if there is a ne?er@ un#ommitted 4ersion resent in the database. :hen

  • 8/11/2019 Embedded Sq l

    15/55

    Embedded SQL Guide for RM/Cobol 1'

    +%C+D8;%+Sis se#ified and a ne?er@ un#ommitted 4ersion of a ro? is resent +our transa#tion ?ill ?aituntil that 4ersion is #ommitted if the ATarameter is se#ified. t ?ill immediatel+ reort a deadlo#5 error if a ne?er@un#ommitted 4ersion is resent and the ATarameter is se#ified.

    .2. Starting a "ransaction

    efore an+ data #an be a##essed from an oen database a transa#tion must be started. n the absen#e of the g*re 9manual#ommand line argument@ transa#tions ?ill be started automati#all+ ?hene4er an SQL statement ?hi#h reFuires a transa#tionis e8e#uted. f the g*re 9manual#ommand line argument ?as se#ified or if +ou ?ant to e8li#itl+ start a transa#tion +ouuse the SE! !R(0S(C!0 statement.

    .2.1. SE" "R'S'C"53

    SET TRANSACTION NA*E 7a>sa;7?>_>a#F READ WRITE READ ONLMF WAIT NO WAITF ISOLATION LE2ELF SNAPSHOT TABLE STABILITMF READ CO**IT NOF RECORD_2ERSIONFF RESER2IN /#s#6?>J_;"as#KF +SIN %&8a>%"# %&8a>%"#F ...F

    /#s#6?>J_;"as#K = 7a&"# 7a&"#F ... OR SHARED PROTECTEDF READ WRITEF /#s#6?>J_;"as#KF ...

    !he A'%#lause se#ifies a name for the transa#tion. transaction8nameis a host 4ariable that must be defined as9C S*,1- ;S(GE 0(R,"-. transaction8namemust be initialiKed to Kero before it is first referen#ed in a SE!!R(0S(C!0 statement. transaction8name#an be used in subseFuent SQL statements to for#e them to use thenamed transa#tion rather than the default.

    !he +%AD +T%#lause indi#ates that the transa#tion #an read and ?rite tables. !his is the default.

    !he +%AD /,#lause indi#ates that the transa#tion #an onl+ read tables.

    !he AT#lause indi#ates that the transa#tion ?ill ?ait for a##ess if it en#ounters a lo#5 #onfli#t ?ith anothertransa#tion. !his is the default.

    !he AT#lause indi#ates that the transa#tion ?ill return an error immediatel+ if it en#ounters a lo#5 #onfli#t ?ithanother transa#tion.

    !he S/AT /%;%/#lause se#ifies the beha4iour of this transa#tion ?hen attemting to a##ess the same tablesas other simultaneous transa#tions. !he ?ords S/AT /%;%/themsel4es are otional. SAPS)Tis thedefault setting. See the re#eding se#tion for a more #omlete dis#ussion of isolation le4els.

    !he +%S%+;#lause enables a transa#tion to register its desired le4el of a##ess for se#ified tables ?hen thetransa#tion starts instead of ?hen the transa#tion attemts its oerations on that table.

    P+T%CT%D +T%allo?s the #urrent transa#tion to ?rite to the table and blo#5s all other ?rites.

    P+T%CT%D +%ADdisallo?s ?riting to the table b+ an+ transa#tion@ in#luding the #urrent one.

    S)A+%D +T%allo?s an+ SAPS)TreadB?rite or +%AD C''TT%DreadB?rite transa#tion to udatero?s in the table as long as no transa#tion reFuests e8#lusi4e use.

    S)A+%D +%ADallo?s an+ readB?rite transa#tion to udate the table.

    !he US#lause limits the number of databases that the transa#tion #an a##ess.

    %am*les

    Start a read@ ?rite transa#tion that #an read onl+ the most re#entl+ #ommitted 4ersion of ro?s and ?ill?ait for lo#5 to be released before #ontinuing.

    EXEC SQL SET TRANSACTION READ WRITE WAIT READ CO**ITTED NO RECORD_2ERSION

    Start a transa#tion ?hi#h ?ill be the onl+ transa#tion allo?ed to udate the L(S table.

  • 8/11/2019 Embedded Sq l

    16/55

    16 Embedded SQL Guide for RM/Cobol

    EXEC SQL SET TRANSACTION READ WRITE WAIT SNAPSHOT RESER2IN LOADS OR PROTECTED WRITE

    .. Sa6ing 8our Changes

    :hen a transa#tionAs tas5s are #omlete the transa#tion must be ended to set the database to a #onsistent state and to ma5ean+ #hanges made b+ the transa#tion ermanent. Su##essful transa#tions are ended b+ the CMM! statement.

    !he CMM! statement

    :rites all udates to the database.

    Ma5es the transa#tionAs udates 4isible to other transa#tions.

    Closes oen #ursors@ unless the +%TA#lause is gi4en.

    ..1. C3MM5"

    CO**IT WORGF TRANSACTION 7a>sa;7?>_>a#F RELEASEF RETAIN SNAPSHOTFF

    +#lause #ommits the #hanges and retains the #urrent transa#tion #onte8t. !his has the effe#tof lea4ing #urrentl+ oen #ursors oen rather than #losing them. e a?are the use of the +%TA#lause lea4es thetransa#tion in an a#ti4e state. Lea4ing a +%AD +T%transa#tion oen for long eriods of time ?ill ha4e a negati4eima#t on s+stem erforman#e. E4er+ transa#tion must e4entuall+ be #losed b+ a CMM! or RLL(C7 statement?ithout a RE!(0 #lause.

    %am*les

    Commit a transa#tion and #lose all oen #ursors.

    EXEC SQL CO**IT

    Commit a transa#tion lea4ing all #ursors oen.

    EXEC SQL CO**IT RETAIN

    .#. !iscarding 8our Changes

    :hen an error is en#ountered during transa#tion ro#essing and +ou ?ant to dis#ard +our #hanges and return the database tothe state it had rior to the start of the transa#tion +ou use the RLL(C7 statement.

    !he RLL(C7 statement

    is#ards all #hanges made to the database sin#e the transa#tion ?as started.

    Closes all oen #ursors.

    .#.1. R3LL'C9

    ROLLBACG WORGF TRANSACTION 7a>sa;7?>_>a#F RELEASEF RETAIN SNAPSHOTFF

    WORK?s a> !7?>a" 9% s#% $ ;!a7?&?"?7 9?78 78# #"a7?>a" %a7a&as#s98?;8 #?# ?7.

    !he T+ASACT#lause #auses the transa#tion named transaction8nameto be rolled ba#5. f this #lause isomitted the default transa#tion is rolled ba#5.

    !he +%/%AS%#lause dis#onne#ts the ali#ation from the database after the rollba#5 is #omlete. !his #lause is onl+a4ailable for #omatibilit+ ?ith re4ious 4ersions on nterbase. !o #lose a database use the SC00EC! statement.

  • 8/11/2019 Embedded Sq l

    17/55

    Embedded SQL Guide for RM/Cobol 1&

    !he +%TA =SAPS)T>#lause rolls ba#5 the #hanges and retains the #urrent transa#tion #onte8t. !his has theeffe#t of lea4ing #urrentl+ oen #ursors oen rather than #losing them. e a?are the use of the +%TA#lause lea4esthe transa#tion in an a#ti4e state. Lea4ing a +%AD +T%transa#tion oen for long eriods of time ?ill ha4e anegati4e ima#t on s+stem erforman#e. E4er+ transa#tion must e4entuall+ be #losed b+ a CMM! or RLL(C7statement ?ithout a RE!(0 #lause.

    %am*les

    Rollba#5 the default transa#tion.EXEC SQL ROLLBACG

    Rollba#5 the transa#tion named !R(0S2.EXEC SQL ROLLBACG TRANSACTION TRANS,

  • 8/11/2019 Embedded Sq l

    18/55

    1) Embedded SQL Guide for RM/Cobol

    #. 'ccessing the !ata

    !he maorit+ of SQL statements in an embedded ali#ation are de4oted to reading or modif+ing e8isting data or addingne? data to the database. !his #hater des#ribes the t+es of data re#ogniKed b+ =irebird and ho? to retrie4e@ modif+@ addor delete data using the follo?ing SQL statements

    SELEC! statements read or retrie4e e8isting data from a database.

    0SER! statements ?rite ne? ro?s of data to a table.

    ;9(!E statements modif+ e8isting ro?s of data in a table.

    ELE!E statements delete e8isting ro?s of data from a table.

    !his #hater ?ill des#ribe the basi#s of using these statements to retrie4e and udate data. ( #omlete dis#ussion of SQL isoutside the s#oe of this manual. =or more information see the nterbase Language Referen#e b+ orland or !he =irebirdoo5 b+ $elen orrie.

    #.1. Su44orted !ata ",4es

    =irebird suorts thirteen fundamental data t+es ?hi#h are des#ribed in the follo?ing table.

  • 8/11/2019 Embedded Sq l

    19/55

    Embedded SQL Guide for RM/Cobol 1*

    Data Type Size Range/Precision Description

    G0! 6" bits 2B63to 263B 1 Signed 6" bit integer. nl+a4ailable in diale#t 3 databases.

    L %ariable 0one

    lob segment siKe is limited to327

    +nami#all+ siKable data t+efor holding grahi#s@ sound@ et#.

    C$(R,n- n #hara#ters 1 to 32@&6& b+tes

    Chara#ter set #hara#ter siKedetermines the number of#hara#ters that #an fit in 327

    =i8ed length te8t string

    (!E 6" bits 1 Pan 1 C to 2* =eb 32&6) CE n diale#t 3 databases this t+eholds a date onl+. n diale#t 1databases this t+e is eFui4alentto !MES!(M9.

    ECM(L,re#ision@ s#ale- 16@ 32 or 6"bits

    re#ision N 1 to 1) digits. Columnmust be able to store at leastthis

    man+ digits.

    s#ale N 1 to 1) digits. Se#ifies thenumber of de#imal la#es. Mustbe less than or eFual to re#ision.

    0umeri# data t+e ?ith scaledigits to the right of the de#imal

    oint.

    E8amle ECM(L,1@3-holds numbers a##uratel+ in thefollo?ing format .sss

    ;LE 9RECS0 6" bits 2.22'81B3) to 1.&*&813) EEE double re#ision floatingoint number ?ith ma8imum 1'digits re#ision. ;se ?henrange of number to be stored isnot 5no? in ad4an#e.

    =L(! 32 bits 1.1&'81B3)to 3."*2813) EEE single re#ision floatingoint number ?ith ma8imum &digits re#ision. ;se ?hen

    range of number to be stored isnot 5no? in ad4an#e.

    0!EGER 32 bits B2@1"&@")3@6") to 2@1"&@")3@6"& Signed 32 bit integer.

    0;MERC,re#ision@ s#ale- 16@ 32 or 6"bits

    re#ision N 1 to 1) digits. Columnmust be able to store eactl?thisman+ digits.

    s#ale N 1 to 1) digits. Se#ifies thenumber of de#imal la#es. Mustbe less than or eFual to re#ision.

    0umeri# data t+e ?ith scaledigits to the right of the de#imaloint.

    E8amle ECM(L,1@3-holds numbers a##uratel+ in thefollo?ing format .sss

    SM(LL0! 16 bits B32@&6) to 32@&6& Signed 16 bit integer

    !ME 6" bits (M to 23'*'*.**** 9M !ime of da+. 0ot a4ailable in

    diale#t 1 databases.

    !MES!(M9 6" bits 1 Pan 1 C to 2* =eb32&6) 23'*'*.**** CE

    ate and time of da+. 0ota4ailable in diale#t 1 databases@use (!E instead.

    %(RC$(R,n- n #hara#ters 1 to 32@&6& b+tes

    Chara#ter set #hara#ter siKedetermines the number of#hara#ters that #an fit in 327

    %ariable length te8t string

    Table 1 Firebird Data Types

    :hen reading data from the database or ?riting data to the database@ g*real?a+s mo4es +our ali#ationAs data through

  • 8/11/2019 Embedded Sq l

    20/55

    2 Embedded SQL Guide for RM/Cobol

    temorar+ 4ariables that are #reated b+ g*reand are guaranteed to be the roer siKe and t+e to hold the data. !hesetemorar+ 4ariables are then mo4ed to and from +our host 4ariables b+ g*reusing the Cobol M%E 4erb. !his means that@in general@ +ou #an define +our 4ariables to be ?hate4er siKe and format +ou desire as long as host 4ariables for numeri#fields #an be e8e#ted to #orre#tl+ re#ei4e 4alues from and send 4alues to numeri# data items a##ording to the rules of theCobol M%E 4erb.

    !he e8#etion to this rule is date fields. ate fields ?ill be mo4ed into +our host 4ariables in t?o different ?a+s a##ordingto the setting of the g*re 9#fm#ommand line argument. f the 9#fmargument is omitted +our host 4ariable ?ill re#ei4e ara?@ 6" bit date field in =irebird internal format. our ali#ation ?ill then ha4e to use the isc8enco#e8#ateandisc8#eco#e8#atefun#tions to translate the date to and from Cobol format. f the 9#fmargument is se#ified then the date?ill be mo4ed to and from +our host 4ariable a##ording to the format string gi4en to the 9#fmargument. !he format string#ontrols the formatting of dates a##ording to the resen#e of format #hara#ters in the string. ??or ????indi#ates theosition of the +ear@ mmthe month@ ##the da+@ hhthe hour@ nnthe minutes and ssthe se#onds. =or e8amle@ 9#fm????mm##hhnnss?ould #ause =irebird to format a DAT%#olumn as a four digit +ear@ t?o digit month@ t?o digit da+ ofthe month@ t?o digit hour@ t?o digit minutes and t?o digit se#onds.

    #.2. SQL E:4ressions

    (ll SQL data maniulation statements suort SQL e8ressions. E8ressions are used for #omaring and e4aluating#olumns@ #onstants and host 4ariables to rodu#e a single 4alue.

    =or e8amle@ the :$ERE #lause is used to se#if+ a sear#h #ondition that determines if a ro? Fualifies for retrie4al orudate. !he sear#h #ondition is an SQL e8ression. :hen an e8ression is used as a sear#h #ondition it e4aluates to a 4alueof !rue or =alse.

    E8ressions #an also be used to #al#ulate 4alues that ?ill be inserted or udated into a #olumn. :hen inserting or udatinga numeri# 4alue the e8ression is usuall+ arithmeti#@ su#h as multil+ing one number b+ another. :hen inserting orudating a string 4alue the e8ression #an #on#atenate t?o strings to rodu#e a single@ ne? string.

  • 8/11/2019 Embedded Sq l

    21/55

    Embedded SQL Guide for RM/Cobol 21

    Element Description

    Column names Columns from se#ified tables.

    $ost 4ariables 9rogram 4ariables #ontaining #hangeable 4alues. $ost 4ariables must be re#eded b+ a #olon ,-.

    Constants $ard #oded numbers or strings. i.e. 123"' or Astring 4alueA.

    Con#atenation oerator @ used to #on#atenate t?o strings.

    (rithmeti# oerators @ B@ and /

    Logi#al oerators !he 5e+?ords 0!@ (0 and R.

    Comarison oerators T@ U@ TN@ UN@ N and TU. ther@ more se#ialiKed #omarison oerators in#lude (LL@ (0@E!:EE0@ C0!(00G@ E(!E@ C;RRE0!>RLE@ C;RRE0!>SESS0@C;RRE0!>!ME@ C;RRE0!>!MES!(M9@ C;RRE0!>!R(0S(C!0@C;RRE0!>;SER and ;SER.

    Table 2Elements of SQL Expressions

    #.2.1. Precedence of 34erators

    9re#eden#e determines the order in ?hi#h oerators are e4aluated in an e8ression. erators are groued into four maint+es ?hi#h are e4aluated using the follo?ing re#eden#e #on#atenation@ arithmeti#@ #omarison and logi#al. :hen ane8ression #ontains se4eral oerators of the same t+e@ those oerators are e4aluated from left to right unless there is a#onfli#t ?here t?o oerators of the same t+e affe#t the same 4alues. :hen there is a #onfli#t@ oerator re#eden#e ?ithinthe t+e determines the order of e4aluation.

    #.2.2. String Concatenation

    !he #on#atenation oerator@ @ enables a single #hara#ter string to be built from t?o or more #hara#ter strings. Chara#terstrings #an be #onstants or 4alues retrie4ed from a #olumn.

    %am*le

    01 WS-TEXT PIC X(0).

    ...

    EXEC SQL SELECT LAST_NA*E ' ' IRST_NA*E INTO WS-TEXT RO* ACCO+NTS

    #.2.. 'rithmetic 34erators

    =irebird suorts the follo?ing arithmeti# oerators

  • 8/11/2019 Embedded Sq l

    22/55

    22 Embedded SQL Guide for RM/Cobol

    Multili#ation i4ision /(ddition Subtra#tion B

    (rithmeti# e8ressions are e4aluated left to right@ e8#et ?hen ambiguities arise. n these #ases@ =irebird e4aluatesmultili#ation and di4ision first follo?ed b+ addition and subtra#tion.

    %am*le

    1

    !his +ields the result 33.

    #.2.#. Com4arison 34erators

    Comarison oerators test a se#ifi# relationshi bet?een a 4alue to the left of the oerator and a 4alue or range of 4alues tothe right of the oerator. %alues #omared must e4aluate to the same data t+e unless the C(S!,- fun#tion is used totranslate one data t+e to a different one for #omarison. E4er+ test rodu#es a result that #an be either !rue or =alse.

    =irebird suorts the follo?ing #omarison oerators

    EFualit+ N

    neFualit+ TUGreater than UGreater than or eFual to UNLess than TLess than or eFual to TN

    =irebird also suorts some more se#ialiKed #omarison oerators. !hese are

    E!:EE0C0!(00G0L7ES 0;LLS!(R!0G :!$(LL(0 or SMEE

  • 8/11/2019 Embedded Sq l

    23/55

    Embedded SQL Guide for RM/Cobol 23

    !he follo?ing #ursor de#laration retrie4es all load numbers ?here the shierAs name #ontainsIVE$RSJ.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE LD_SHIP_NA*E CONTAININ 'EHRS'

    #.2.#.. 5

    tests to see if a 4alue eFuals at least one 4alue in a list of 4alues. ( list is either a set of 4alues searated b+ #ommas anden#losed b+ arentheses or the results of a subFuer+. !he #omlete s+nta8 for the oerator is

    /6a"#K NOTF IN (/6a"#1K /6a"#,F ...)

    OR

    /6a"#K NOTF IN (/sK)

    %am*le

    !he follo?ing #ursor retrie4es the shier names for loads 111@ 112 and 113.

    EXEC SQL

    DECLARE C1 C+RSOR OR SELECT LD_SHIP_NA*E RO* LOADS WHERE LD_LOAD_N+*BER IN (100101 10010, 100103)

    !he follo?ing #ursor retrie4es the shier names for all loads ?hose Ki #ode is 1*"62.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_SHIP_NA*E RO* LOADS WHERE LD_LOAD_N+*BER IN (SELECT LD_LOAD_N+*BER RO* LOADS WHERE LD_SHIP_IP = 1,)

    #.2.#.#. L59E

    /

  • 8/11/2019 Embedded Sq l

    24/55

    2" Embedded SQL Guide for RM/Cobol

    /6a"#K IS NOTF N+LL

    E8amle!he follo?ing #ursor retrie4es all loads ?hi#h ha4e no 4alue in the ro number #olumn.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE LD_PRO_N+*BER IS N+LL

    #.2.#.(. S"'R"5G ;5"$

    STA+T T)tests a 4alue to see if it begins ?ith a #ase sensiti4e string. !he #omlete s+nta8 of the STA+TT)oerator is

    /6a"#K NOTF STARTIN WITH /s7?>JK

    %am*le

    !he follo?ing #ursor retrie4es all loads ?hose shierAs name begins ?ith I3MJ.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE LD_SHIP_NA*E STARTIN WITH '3*'

    #.2.#.). 'LL

    A//tests that a #ondition is true ?hen #omared to e4er+ 4alue in a list returned b+ a subFuer+. !he #omlete s+nta8 of theA//oerator is

    /6a"#K /;!a?s>_!#a7K ALL (/sK)

    %am*le

    !he follo?ing #ursor retrie4es all loads ?here the total re4enue is greater than all loads ?hose shier Ki #ode begins ?ithI1*"J.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE LD_TTL_RE2EN+E K ALL (SELECT LD_TTL_RE2EN+E RO* LOADS WHERE LD_SHIP_IP STARTIN WITH '1')

    #.2.#.*. '8 or S3ME

    A,or S'%tests that a #ondition is true ?hen #omared to an+ 4alue in a list returned b+ a subFuer+. !he #omletes+nta8 for the A,oerator is

    /6a"#K /;!a?s>_!#a7K ANM SO*E (/sK)

    %am*le

    !he follo?ing #ursor retrie4es the dri4erAs first and last names for an+ dri4er #urrentl+ assigned to loads ?hose shierAs Ki#ode begins ?ith I1*"J.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT OPDR2_LAST_NA*E OPDR2_IRST_NA*E RO* OP_DRI2ERS WHERE OPDR2_ID = ANM (SELECT LD_DRI2ER1 RO* LOADS WHERE LD_SHIP_IP STARTIN WITH '1')

    #.2.#.+. E

  • 8/11/2019 Embedded Sq l

    25/55

    Embedded SQL Guide for RM/Cobol 2'

    !he follo?ing #ursor retrie4es all loads ?here the shierAs state does not e8ist in the state #ode table.EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE NOT EXISTS (SELECT RO* CT_STATE WHERE CTST_CODE = LD_SHIP_STATE)

    #.2.#.1. S5G0L'R

    SU/A+tests that there is exactlyone Fualif+ing ro? meeting the #riteria for the sear#h #ondition gi4en b+ a subFuer+.!he #omlete s+nta8 for the SU/A+oerator is

    NOTF SIN+LAR (/sK)

    %am*le

    !he follo?ing #ursor sele#ts all loads ?hi#h ha4e one line item.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LD_LOAD_N+*BER RO* LOADS WHERE SIN+LAR (SELECT RO* LD_STOP_ITE*S WHERE LDS_LOAD_N+*BER = LD_LOAD_N+*BER)

    #.2.&. Logical 34erators

    =irebird ro4ides three logi#al oerators T@ ADand +.

    Te4aluates to the negati4e of the #ondition to ?hi#h it is alied and has the highest re#eden#e.ADe4aluates to !rue if both of the #onditions to ?hi#h it alies are !rue. t e4aluates to =alse other?ise. t hasthe ne8t highest re#eden#e afterT.

    +e4aluates to !rue if either of the #onditions to ?hi#h is alies is !rue. t e4aluates to =alse other?ise. t has thesame re#eden#e as AD.

    %am*le

    NOT COL+*N1 = COL+*N,

    E4aluates to !rue if CL;M01 is not eFual to CL;M02.

    COL+*N1 = COL+*N, AND COL+*N3 = COL+*N

    E4aluates to !rue if both CL;M01 eFuals CL;M02 and CL;M03 eFuals CL;M0".

    COL+*N1 = COL+*N, OR COL+*N3 = COL+*N

    E4aluates to !rue if either CL;M01 eFuals CL;M02 or CL;M03 eFuals CL;M0".

    #.2.(. 0LLs in E:4ressions

    0;LL 4alues #an be Fuite a #on#etual #hallenge for those ?ho ha4e re4iousl+ ?or5ed in en4ironments@ su#h as Cobol@that donAt ha4e 0;LL 4alues. n SQL@ an+ data item ?ill be stored ?ith a 0;LL indi#ator if no 4alue is e4er ro4ided for itin a ML statement or through a default. ( 0;LL is not eFui4alent to a blan5 te8t #olumn or a Kero numeri# #olumn.0;LL 4alues are treated Fuite differentl+ in e8ressions than blan5 or Kero 4alues. Comarisons that en#ounter 0;LL oneither the left or right side of the oerator al?a+s follo? SQL rules of logi# and e4aluate the result of the #omarison as0;LL and return =alse.

    0;LL is not a 4alue@ so it #annot be eFual to an+thing. =or e8amle@ an e8ression su#h as

    WHERE (COL1 = N+LL)

    ?ill return an error be#ause the eFualit+ oerator is not 4alue for 0;LLs. !he #orre#t e8ression to test for 0;LLs is

    WHERE (COL1 IS N+LL)

    !?o 0;LLs are not eFual to ea#h other. e a?are of the #ase ?here an e8ression must resol4e to

    WHERE (/>""_6a"#K = />""_6a"#K)

    be#ause =alse is al?a+s the result ?hen t?o 0;LLs are #omared.

  • 8/11/2019 Embedded Sq l

    26/55

    26 Embedded SQL Guide for RM/Cobol

    n an e8ression ?here a #olumn identifier Istands inJ for the #urrent 4alue of a data item@ a 0;LL oerand in a #al#ulation?ill rodu#e 0;LL as the result of the #al#ulation. =or e8amle@ the follo?ing

    +PDATE TABLEA SET COL = COL COL5

    ?ill set CL" to 0;LL if CL' is 0;LL.

    n aggregate e8ressions using oerators li5e S;M,-@ (%G,-@ and C;0!,- ro?s #ontaining 0;LL are ignored.

    Semmanti#all+@ if an e8ression returns 0;LL@ it is neither false nor true. $o?e4er@ in SQL #omarisons resol4e as eithertrue or false@ a #omarison that does not e4aluate to true is false. !his #an tri +ou u if +ou are using 0! in e8ressionsthat in4ol4e 0;LLs be#ause

    NOT /;>%?7?> #6a"a7?>J 7 $a"s#K #6a"a7#s 7 7#

    but

    NOT /;>%?7?> #6a"a7?>J 7 N+LLK #6a"a7#s 7 N+LL

    %am*le

    NOT (COL+*NA = COL+*NB)

    f both CL;M0( and CL;M0 ha4e 4alues and the+ are not eFual@ the inner e8ression e4aluates to false. !hee8ression 0! ,false- returns true.

    $o?e4er@ if either of the #olumns is 0;LL@ the inner e8ression e4aluates to 0;LL. !he e8ression 0! ,0;LL-e4aluates to 0;LL and returns 0;LL.

    #.2.). Com4uted Columns

    SQL is not limited to returning the 4alues of #olumns as the result of a Fuer+@ it #an also return the 4alue of e8ressions.utut #olumns ?hi#h are #reated using e8ressions are referred to as #omuted #olumns. !he 4alue of a #omuted #olumnis al?a+s read onl+ sin#e it is not a stored 4alue and@ as su#h@ #annot be udated to a ne? 4alue. (n+ e8ression that returnsa single 4alue #an be used to se#if+ a #omuted #olumn.

    !o enable +ou to ro4ide run time names for #omuted #olumns =irebird suorts the SQL #olumn aliasing standard@ ?hi#hallo?s an+ #olumn to be outut using an alias. =or e8amle@ the follo?ing

    SELECT COL+*N, '' COL+*N3 AS CO*P+TED_COL+*N RO* TABLE

    returns a #olumn #on#atenating t?o other #olumn 4alues searated b+ a #omma and names it CM9;!E>CL;M0.

    #.2.*. uilt in =unctions

    =irebird #omes ?ith a minimal set of internall+ imlemented SQL fun#tions. t is also ossible to e8tend =irebird ?ith user?ritten@ e8ternal fun#tions #alled ;=s ,;ser efined =un#tions-.

  • 8/11/2019 Embedded Sq l

    27/55

    Embedded SQL Guide for RM/Cobol 2&

    Function Type Description

    C(S!,- Con4ersion Con4erts a #olumn from one data t+e to another.

    E

    S;S!R0G,- String Retrie4es an+ seFuen#e of #hara#ters from a string.

    ;99ER,- String Con4erts a string to all uer #ase #hara#ters.

    GE0>,- General Returns the 4alue from a generator.

    (%G,- (ggregating Cal#ulates the a4erage of a set of 4alues.

    C;0!,- (ggregating Returns the number of ro?s that satisf+ a Fuer+As sear#h #ondition.

    M(

  • 8/11/2019 Embedded Sq l

    28/55

    2) Embedded SQL Guide for RM/Cobol

    #.2.*.. S0S"R5G

    !he SU"ST+fun#tion returns a string of #onse#uti4e #hara#ters from another string. !he s+nta8 of the SU"ST+is

    S+BSTRIN(/6a"#K RO* /s7a7!sK OR /"#>J78KF)

    SU"ST+returns #hara#ters from T4alueU beginning ?ith the #hara#ter at TstartosU. f the otional +TlengthU#lause is gi4en the fun#tion ?ill return the lesser of TlengthU b+tes or the number of b+tes to the end of T4alueU. f the +#lause is omitted the fun#tion returns the number of b+tes from TstartosU to the end of T4alueU. !he first #hara#ter ofT4alueU is osition 1.

    %am*le

    !he follo?ing fun#tion #all ?ill return all #hara#ters from #hara#ter osition " to the end of CL;M0.

    S+BSTRIN(COL+*N RO* )

    !he follo?ing fun#tion #all ?ill return u to ' #hara#ters from CL;M0 starting at osition ".

    S+BSTRIN(COL+*N RO* OR 50)

    #.2.*.#. 0PPER

    !he UPP%+fun#tion #on4erts a string 4alue to all uer #ase #hara#ters. !he s+nta8 for UPP%+is

    +PPER(/6a"#K)

    %am*le

    !he follo?ing fun#tion #all returns I!$S S ( !ES!J.

    +PPER('T8?s ?s a 7#s7')

    #.2.*.&. GE>5!

    !he %8Dfun#tion #al#ulates and returns a 4alue from a generator. Generators are a means of generating a series ofnumbers ?hi#h are ideall+ suited to use as autoin#rementing 5e+s. !he s+nta8 of the %8Dfun#tion is

    EN_ID(/J#>#a7K /?>;##>7K)

    %8Dreturns the last 4alue of TgeneratorU lus the 4alue of Tin#rementU. t then udates TgeneratorU to the 4alue ustreturned.

    %am*le

    f the generator named IM+GeneratorJ has a 4alue of " then the follo?ing fun#tion #all ?ould return 6 and set the 4alue ofIM+GeneratorJ to 6.

    EN_ID('*#>#a7' ,)

    #.2.*.(. '%G

    !he A;fun#tion returns the a4erage of the 4alues of a single #olumn returned b+ a Fuer+. !he s+nta8 of the A;fun#tion is

    A2(/;">K)

    %am*le

    !he follo?ing sele#t statement returns the a4erage re4enue of all loads

    SELECT A2(LD_TTL_RE2EN+E) RO* LOADS

    #.2.*.). C30"

    !he CUTfun#tion returns the number of ro?s that satisf+ a Fuer+As sear#h #ondition. !he s+nta8 of the CUTfun#tion is

    CO+NT( ALLF /;">K DISTINCT /;">K)

    @B returns the number of ro?s in the result set@ in#luding 0;LL 4alues.

  • 8/11/2019 Embedded Sq l

    29/55

    Embedded SQL Guide for RM/Cobol 2*

    A//returns the number of nonB0;LL 4alues in T#olumnU

    DSTCTreturns the number of uniFue@ nonB0;LL 4alues in a #olumn

    %am*le

    !he follo?ing sele#t statement returns the number of ro?s in the loads table.

    SELECT CO+NT() RO* LOADS

    #.2.*.*. M'K)

    %am*le

    !he follo?ing sele#t statement returns the minimum re4enue of all loads.

    SELECT *IN(LD_TTL_RE2EN+E) RO* LOADS

    #.2.*.1. S0M

    !he SU'fun#tion returns the total of a set of numeri# 4alues. !he s+nta8 of the SU'fun#tion is

    S+*(/;">K)

    %am*le

    !he follo?ing sele#t statement returns the total re4enue for all loads.

    SELECT S+*(LD_TTL_RE2EN+E) RO* LOADS

    #.2.*.11. C'SE

    !he CAS%fun#tion returns a 4alue determined b+ the out#ome of e4aluating a grou of mutuall+ e8#lusi4e #onditions. !hes+nta8 of the CAS%fun#tion is

    CASE /6a"#1K /#!7_;"as#K WHEN N+LL /6a"#,K /;>%?7?>1K THEN /#s"71K N+LL WHEN ... THEN /#s"7,K N+LL WHEN ... THEN /#s"7>K N+LLF ... ELSE /#s"7> 1K N+LLFEND

    )% ... T)%are the 5e+?ords in ea#h #ondition / result #lause. (t least one #ondition / result #lause is reFuired.

    %/S%re#edes an otional Ilast resortJ #lause@ to be returned if none of the #onditions in the re#eding #lauses is met.

    &alue1is the identifier of the #olumn 4alue that is to be e4aluated. t #an be omitted@ in ?hi#h #ase ea#h )%#lause must be a #ondition that referen#es the same #olumn identifier.

    &alue2is the 4alue that is mat#hed against &alue1. t is either a literal or an e8ression that e4aluates to a data t+ethat is #omatible ?ith &alue1As data t+e.

    con#ition1is a #onditional e8ression ?hi#h must be used ?hen &alue1is omitted. n this #ase@ both &alue1and &alue2must be #ontained in con#ition1.

    result1is the 4alue that ?ill be returned if &alue1mat#hes &alue2.

  • 8/11/2019 Embedded Sq l

    30/55

    3 Embedded SQL Guide for RM/Cobol

    %am*le

    !he follo?ing sele#t statement ?ill return an English language des#rition of the unit t+es of all units in the 9ER(!0Stable.

    SELECT CASE OP_+NIT_TMPE WHEN 1 THEN 'Ta;7'

    WHEN , THEN 'Ta?"#' WHEN 5 THEN 'D?6#' ELSE '+>:>9> 7!#' END RO* OPERATIONS

    !he follo?ing sele#t statement also returns an English language des#rition of the unit t+es of all unitsin the 9ER(!0S table.

    SELECT CASEWHEN OP_+NIT_TMPE = 1 THEN 'Ta;7'

    WHEN OP_+NIT_TMPE = , THEN 'Ta?"#' WHEN OP_+NIT_TMPE = 5 THEN 'D?6#' ELSE '+>:>9> 7!#' END RO* OPERATIONS

    #.2.*.12. C3'LESCE

    !he CA/%SC%fun#tion e4aluates a series of e8ressions. !he 4alue of the first e8ression to return a nonBnull 4alue isreturned. !he s+nta8 of the CA/%SC%fun#tion is

    COALESCE(/6a"#1K /6a"#,K ...F)

    E8amle!he follo?ing sele#t statement returns either a loadAs ro number or the string A0ot billedA if no ro number e8ists.

    SELECT COALESCE(LD_PRO_N+*BER 'N7 &?""#%') RO* LOADS

    #.2.*.1. 0LL5=

    !he U//fun#tion returns either the 4alue of its first argument or 0;LL if the 4alue of the first argument mat#hes the4alue of the se#ond argument. !he s+nta8 of the U//fun#tion is

    N+LLI(/6a"#1K /6a"#,K)

    %am*le

    !he follo?ing udate statement sets the 4alue L>!!L>RE%E0;E to 0;LL if it eFuals Kero.

    +PDATE LOADS SET LD_TTL_RE2EN+E = N+LLI(LD_TTL_RE2EN+E 0)

    #.. Retrie6ing !ata

    (ll data stored in =irebird tables is retrie4ed in onl+ one ?a+@ b+ Fuer+ing it using a SELEC! statement. ( Fuer+ defines alogi#al #olle#tion of data items arranged in order from left to right in one or more #olumns 5no?n as a set. !he data itemsma+ #ome from a single table or multile tables. ( Fuer+ ma+ #onsist of a single ro? or multile ro?s. !he ro?s #an be in

    no arti#ular order or the+ #an be returned as a sorted set.

    #..1. "he SELEC" statement

    SELECT TRANSACTION 7a>sa;7?>_>a#F IRST ()F SGIP (>)F DISTINCT ALLF /6a"K /6a"K ...F INTO 6a 6a ...FF RO* 7a&"# 6?#9 s7#%_!;#%# INNERF LET RIHT +LL O+TERFF UOIN 7a&"# 6?#9 s7#%_!;#%# ON /V?>_;>%?7?>K UOIN ...FF WHERE /s#a;8_;>%?7?>KF RO+P BM ;" ;" ...FF

  • 8/11/2019 Embedded Sq l

    31/55

    Embedded SQL Guide for RM/Cobol 31

    HA2IN /s#a;8_;>%?7?>KF +NION /s#"#;7_#@!#ss?>KF PLAN /!"a>_#@!#ss?>KF ORDER BM /%#_"?s7KF OR +PDATEF O ;" ;" ...F WITH LOCGF

    /6a"K = #@!#ss?> AS a"?asF

    /V?>_;>%?7?>K = a ;>%?7?>a" #@!#ss?> #"a7?>J ;">s $ 78# 7a&"# 7 V?>#% 7 78# as7# 7a&"#. 2a"#s $ 78# 9s 98?;8 a7;8 78# ;>%?7?>s9?"" ?>;"%#% ?> 78# #s"7 s#7.

    /s#a;8_;>%?7?>) = a ;>%?7?>a" #@!#ss?> s!#;?$?>J 98?;8 9s a# 7 ?>;"%#% $ 78# as7# 7a&"#.

    /s#"#;7?>_;>%?7?>K = a s s!#;?$?>J a%%?7?>a" 9s 7 a!!#>%#% 778# #s"7 s#7.

    /!"a>_#@!#ss?>K = a ;"as# 98?;8 7#""s 78# %a7a&as# a>aJ# 98?;8 ?>%?;#ss8"% s#% 7 #6a"a7# 78# #. T8?s ;"as# ?s a#" s#% a>% ?s >7%?s;ss#% ?> 78?s a>a".

    /%#_"?s7K = ;" ?>7#J# ASCENDINF DESCENDINFF /%#_"?s7KF

    f +ou #anAt ma5e mu#h sense out of the formal definition of the SELEC! statement@ donAt ?orr+. Ea#h #lause ?ill bedis#ussed in detail in the follo?ing se#tions.

    #..2. amed "ransactions

    f +our ali#ation is ma5ing use of named transa#tions@ +ou #an tell the database manager ?hi#h transa#tion to use to#ontrol the SELEC! statement b+ in#luding the otional T+ASACT #lause. !he T+ASACT5e+?ord issiml+ follo?ed b+ a transa#tion name that has been de#lared in a re4ious SE! !R(0S(C!0 statement.

    #... Set Qualifiers

    !he otional set Fualifiers +ST@ S

  • 8/11/2019 Embedded Sq l

    32/55

    32 Embedded SQL Guide for RM/Cobol

    SELEC! =RM L(S!he follo?ing #ursor returns all #olumns from the L(S table as ?ell as the tra#tor id from the 9ER(!0S table.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT LOADS. OPERATIONS.OP_+NIT_ID RO* LOADS

    LET UOIN OPERATIONS ON OP_ID = LD_TRACTOR

    !he follo?ing #ursor returns the +ear@ month and da+ from the L>S!(!;S>(!E #olumn as searate #olumns aliased asS!(!>E(R@ S!(!>M0!$ and S!(!>( rese#ti4el+.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT EXTRACT(MEAR RO* LD_STAT+S_DATE) AS STAT_MEAR EXTRACT(*ONTH RO* LD_STAT+S_DATE) AS STAT_*ONTH EXTRACT(DAM RO* LD_STAT+S_DATE) AS STAT_DAM RO* LOADS

    #..&. S4ecif,ing $ost %ariables for Returned Columns

    ( SELEC! statement that returns a single ro? ,singleton SELEC!- returns data to a list of host 4ariables se#ified b+ the

    T#lause. Ea#h host 4ariable in the T#lause must be re#eded b+ a #olon ,- and searated from the re#eding host4ariable b+ a #omma. !he number@ order and data t+e of the host 4ariables must #orresond to the number@ order and datat+e of the #olumns retrie4ed. ther?ise@ o4erflo?@ data #on4ersion or #omile errors ma+ result.

    %am*le

    !he follo?ing sele#t statement retrie4es the load number@ status and status date into three host 4ariables.

    EXEC SQL SELECT LD_LOAD_N+*BER LD_STAT+S LD_STAT+S_DATE INTO WS-LOAD-N+*BER WS-STAT+S WS-STAT+S-DATE RO* LOADS WHERE LD_LOAD_N+*BER = 1,35

    #..(. !ata Source

    !he +'#lause se#ifies the sour#e of the data@ ?hi#h ma+ be a table@ a 4ie? or a stored ro#edure that has oututarguments. f the statement in4ol4es oining t?o or more stru#tures@ the +'#lause se#ifies the leftmost stru#ture.ther tables are added to the se#ifi#ation b+ ?a+ on su##eeding G#lauses.

    t is also ossible to oin multile tables using the SQLB)* imli#it inner oin s+nta8. !his in4ol4es listing the tables to beoined on the +'#lause@ searated b+ #ommas. !his method of oining tables is dere#ated and should be a4oided infa4our of the e8li#it Gs+nta8.

    %am*le

    !he follo?ing #ursor returns all ro?s from the L(S table.E

  • 8/11/2019 Embedded Sq l

    33/55

    Embedded SQL Guide for RM/Cobol 33

    WHERE OP_ID = LD_TRACTOR

    #..). Search Conditions

    !he )%+%#lause se#ifies the sear#h #onditions ?hi#h limit the number of ro?s returned. Sear#h #onditions m+ be asimle mat#h #ondition on a single #olumn or a #omle8 e8ression in4ol4ing the AD@ +and Toerators@ t+e#asting@ fun#tion #alls and more. Sear#h #onditions #an #ontains referen#es to host 4ariables ?hi#h #an be used to se#if+4alues in the e8ression at run time. $ost 4ariables must be re#eded b+ a #olon ,-.

    E8amle!he follo?ing #ursor returns all #olumns from the L(S table for ro?s ?hose status date is on or bet?een t?o usersulied 4alues.

    EXEC SQL DECLARE C1 C+RSOR OR SELECT RO* LOADS WHERE LD_STAT+S_DATE BETWEEN WS-LOW-DATE AND WS-HIH-DATE

    !he abo4e e8amle #ould be restated as follo?s

    EXEC SQL DECLARE C1 C+RSOR OR

    SELECT RO* LOADS WHERE LD_STAT+S_DATE K= WS-LOW-DATE AND LD_STAT+S_DATE /= WS-HIH-DATE

    #..*. Grou4ing 3ut4ut

    !he outut from the SELEC! statement #an be otionall+ be artitioned into one or more grous that summariKe the sets ofdata returned at ea#h le4el. !his is a##omlished using the +UP #lause. !hese grouings often in#lude aggregatinge8ressions ?hi#h ?or5 on multile 4alues@ su#h as totals@ a4erages@ ro? #ounts and minimum / ma8imum 4alues. (groued sele#t returns one ro? for ea#h grou 4alue. =or e8amle@ the result set 1*2@ 1*3@ 1*3@ 1*"@ 1*" ?ould return onero? for ea#h of 1*2@ 1*3 and 1*".

    TIP:t is usuall+ ne#essar+ to in#lude an RER #lause in SELEC! statements in ?hi#h +ou ?ant to grou the outut.!his is due to the fa#t that result sets are unordered unless +ou se#if+ the RER #lause. :hile +UP ",?illgrou the outut in this #ase +ou ?ill get multile o##urren#es of the same grou 4alue if it o##urs soradi#all+ throughout

    the result set. =or e8amle@ the result set 1*"@ 1*2@ 1*2@ 1*" ... ?ould return ro?s for 1*"@ 1*2 and 1*".

    %am*le

    !he follo?ing #ursor returns the total and a4erage re4enue for all loads summariKed b+ the first three digits of the Ki #ode.

    EXEC SQL DECLARE C1 C+RSOR OR

    SELECT S+BSTRIN(LD_SHIP_IP RO* 1 OR 3) S+*(LD_TTL_RE2EN+E) A2(LD_TTL_RE2EN+E) RO* LOADS RO+P BM S+BSTRIN(LD_HIP_IP RO* 1 OR 3) ORDER BM S+BSTRIN(LD_SHIP_IP RO* 1 OR 3)

    #..+. Limiting Grou4s Returned!he )A;#lause ma+ be used in #onun#tion ?ith the +UP ",#lause to in#lude or e8#lude grous similar to the?a+ the )%+%#lause limits outut.

    E8amle!he re4ious e8amle #an be modified to limit the outut to grous ?here the total re4enue is greaterthan Kero.ES$9>V9 =RM 1 =R 3-@ S;M,L>!!L>RE%E0;E-@

  • 8/11/2019 Embedded Sq l

    34/55

    3" Embedded SQL Guide for RM/Cobol

    (%G,L>!!L>RE%E0;E- =RM L(S GR;9 S;S!R0G,L>V$9>V9 =RM 1 =R 3- $(%0G S;M,L>!!L>RE%E0;E- U RER S;S!R0G,L>S$9>V9 =RM 1 =R 3-

    #..1. Combining Queries

    Result sets from t?o or more Fueries #an be #ombined into one result set using the U#lause. Ea#h #olumn in theFueries to be #ombined must agree in order@ data t+e and siKe ?ith all of the other Fueries. + default a Uresult setsuresses duli#ates. !o retain the duli#ates@ in#lude the A//5e+?ord.

    E8amle!he follo?ing #ursor returns all loads ?hose shier Ki #ode is 1*"62 or 1*"63. !here are easier ?a+s

    to do this@ this ust ser4ers as an e8amle of the U#lause.ES$9>V9 N A1*"62A ;00 SELEC! . =RM L(S :$ERE .L>S$9>V9 N A1*"63A

    #..11. 3rdering 3ut4ut

    + default@ the SELEC! statement returns ro?s unordered. !his is true e4en if the sear#h #ondition is su#h that the Fuer+#an be satisfied using an inde8.

    !he +D%+ ",#lause allo?s +ou to se#if+ an ordering on the result set. !he +D%+ ",5e+?ords are follo?ed b+ a

    list of #olumns@ b+ ?hi#h the result set ?ill be ordered. !hese #olumns do not need to aear in the outut se#ifi#ation nordo the+ need to aear in an inde8. !he result set ?ill be sorted if ne#essar+.

    !he full s+nta8 of the +D%+ ", #lause is

    ORDER BM ;" /#@!#ss?>K %#J## ASC DESCF N+LLS IRST N+LLS LASTF ...F

    colis the name of a #olumn.

    e*ressionis an+ nonB#onditional e8ression

    #egreeis a number reresenting the osition of a 4alue in the SELEC! statementAs list of returned 4alues. 1 is the first4alue.

    ASCindi#ates that the ordering is the be as#ending for the #olumn@ e8ression or degree.

    D%SCindi#ates that the ordering is the be des#ending for the #olumn@ e8ression or degree.U//S +STH/ASTindi#ates that U//4alues are to #ome first/last in the ordering. !his feature is a4ailable from=irebird 1.'3. for?ard.

    %am*le

    !he follo?ing #ursor returns the all loads@ sorted b+ the shierAs aointment date.

    EXEC SQL SELECT RO* LOADS ORDER BM LD_SHIP_APPT_LOW

  • 8/11/2019 Embedded Sq l

    35/55

    Embedded SQL Guide for RM/Cobol 3'

    #..12. Controlling Ro? Loc7ing

    :ith =irebird@ lo#5ing is go4erned b+ the relati4e ages of transa#tions and the re#ords managed b+ =irebirdAs 4ersioningengine. (ll lo#5ing alies at the ro? le4el@ e8#et ?hen a transa#tion is oerating in S0(9S$! S!(L! isolation or?ith a table reser4ation restri#tion that blo#5s ?rite a##ess.

    !he timing of a lo#5 on a ro? in normal read ?rite a#ti4it+ is otimisti#@ no lo#5ing is in for#e on an+ ro? until the moment

    it is a#tuall+ reFuired. ;ntil an udate of the ro? is osted to the ser4er@ the ro? is free to be I?onJ b+ an+ read ?ritetransa#tion.

    9essimisti#@ or reemti4e@ lo#5ing #an be alied to sets of ro?s or to entire tables. !he table lo#5ing otions ha4e alread+been introdu#ed in the #hater dis#ussing transa#tion management. 9essimisti#@ ro? le4el lo#5ing is managed b+ use of the+ UPDAT% and T) /C

  • 8/11/2019 Embedded Sq l

    36/55

    36 Embedded SQL Guide for RM/Cobol

    CO**IT

    #..1. Selecting a Single Ro?

    (n oeration that retrie4es a single ro? of data is #alled asin$leton select. !o sele#t a single ro? from a table or to retrie4ean aggregate 4alue li5e CUTEFor A;EFuse the follo?ing SELEC! statement s+nta8.

    SELECT ;" ;" ...F INTO 6a 6a ...F RO* 7a&"# WHERE /s#a;8_;>%?7?>K

    !he mandator+ 0! #lause se#ifies the host 4ariables ?here retrie4ed data is #oied for use in the rogram. Ea#h host4ariableAs name must be re#eded b+ a #olon ,-. =or ea#h #olumn retrie4ed there must be on host 4ariable of a#orresonding data t+e. Columns are retrie4ed in the order the+ are listed in the SELEC! #lause and are #oied into host4ariables in the order the 4ariables are listed in the 0! #lause.

    !he :$ERE #lause must se#if+ a sear#h #ondition that guarantees the onl+ one ro? is retrie4ed@ other?ise the SELEC!fails.

    #..1#. Selecting Multi4le Ro?s

    Man+ Fueries se#if+ sear#h #onditions that retrie4e more than one ro?. Sin#e host 4ariables #an onl+ hold a single #olumn4alue at a time@ a Fuer+ that returns multile ro?s must build a temorar+ table #alled a result set. Ro?s are e8tra#ted fromthe result@ one at time@ in seFuential order. !he database manager 5ees tra#5 of the ne8t ro? to ro#ess from the result setb+ establishing a ointer to it@ #alled a cursor.

    !o retrie4e multile ro?s into a result set@ establish a #ursor into the table and ro#ess the indi4idual ro?s in the table@ SQLro4ides the follo?ing seFuen#e of statements

    ECL(RE C;RSR establishes a name for the #ursor and se#ifies the Fuer+ to erform.

    9E0 e8e#utes the Fuer+@ builds the result set and ositions the #ursor at the start of the set.

    =E!C$ retrie4es a single ro? from the result set int host 4ariables.

    CLSE releases s+stem resour#e ?hen all ro?s are retrie4ed.

    #..1#.1. !eclaring a Cursor

    !o de#lare a #ursor and se#if+ ro?s of data to retrie4e@ use the D%C/A+% CU+S+statement. D%C/A+% CU+S+is a nonBe8e#utable statement ?hi#h reares s+stem resour#es for the #ursor but does not a#tuall+ erform the Fuer+. !hes+nta8 for D%C/A+% CU+S+is

    EXEC SQL DECLARE ;s_>a# C+RSOR OR SELECT ...

    cursor8nameis the name of the #ursor ?hi#h is used in subseFuent P%@ %TC)and C/S%statements.

    !he SELEC! statement inside the D%C/A+% CU+S+statement is the same as a singleton sele#t e8#et it #annot in#ludean T#lause.

    #..1#.2. 34ening a Cursor

    efore data sele#ted b+ a #ursor #an be a##essed@ the #ursor must be oened ?ith the P%statement. P%a#ti4ates the#ursor and builds the result set. !he s+nta8 of the P%statement is

    EXEC SQL OPEN ;s_>a#

    cursor8nameis the name of the #ursor as de#lared in a re4ious D%C/A+% CU+S+statement.

    :hen =irebird oens the #ursor it is ositioned to the first ro? of the result set.

    #..1#.. =etching Ro?s from a Cursor

    n#e a #ursor is oened@ ro?s #an be retrie4ed from the result set using the %TC)statement. %TC)

  • 8/11/2019 Embedded Sq l

    37/55

    Embedded SQL Guide for RM/Cobol 3&

    Retrie4es the ne8t a4ailable ro? from the result set.Coies the #olumns for that ro? into the host 4ariables se#ified in the T#lause of the%TC)statement.

    (d4an#es the #ursor to the ne8t a4ailable ro? or sets SI/CD%to 1 to indi#ate that the #ursor is at the end of theresult set.

    !he s+nta8 of the %TC)statement is

    EXEC SQL ETCH ;s_>a# INTO 6a INDICATORF ?>%?;a7F 6a INDICATORF ?>%?;a7F ...F

    cursor8nameis the name of the #ursor as de#lared in a re4ious D%C/A+% CU+S+statement.

    &aris the name of a host 4ariable ?hi#h ?ill re#ei4e the 4alue of the #orresonding #olumn

    in#icatoris the name of a host 4ariable that ?ill re#ei4e the 0;LL status flag for the #olumn.

    E4er+ %TC)statement should be tested to see if the end of the result set is rea#hed. ou do this b+ testing theSI/CD%4ariable. ( 4alue of 1 indi#ates that the end of the result has been rea#hed. ( 4alue of less than Keroindi#ates that an error ?as en#ountered. ( 4alue of Kero indi#ates that a ro? ?as su##essfull+ fet#hed.

    (n+ #olumn #an ha4e a 0;LL 4alue@ e8#et those defined ?ith the 0! 0;LL or ;0Q;E integrit+ #onstraints. !odetermine if the 4alue returned for a #olumn is 0;LL@ follo? ea#h 4ariable named in the T#lause ?ith the otionalDCAT+5e+?ord and the name of a 9C S* 4ariable@ #alled the indicator %ariable?here =irebird ?ill store the 0;LLstatus flag for the #olumn. ( 4alue of B1 indi#ates that the #olumn is 0;LL. ( 4alue of Kero indi#ates that the #olumn is0! 0;LL.

    t is onl+ ossible to read for?ard through a #ursor. !o re4isit re4iousl+ fet#hed ro?s@ #lose the #ursor and reoen it.

    #..1#.#. Closing a Cursor

    :hen +ou are done ?ith a #ursor it should be #losed to free u s+stem resour#es. !o #lose a #ursor use the C/S%statement. !he s+nta8 of the C/S%statement is

    EXEC SQL CLOSE ;s_>a#

    cursor8nameis the name of the #ursor as de#lared in a re4ious D%C/A+% CU+S+statement.

    #.#. 5nserting !ata

    0e? ro?s of data are added to one table at a time ?ith the S%+Tstatement. S%+Tassigns 4alues to #olumns listedbet?een the first set of arentheses. Columns not listed are gi4en a 0;LL 4alue. !he S%+Tstatement allo?s datainsertion from t?o different sour#es a list of host 4ariables or a SELEC! statement that retrie4es 4alues from one table toadd to another.

    #.#.1. "he 5SER" Statement

    ormat 1

    INSERT TRANSACTION 7a>sa;7?>_>a#INTO 7a&"#_>a# (;" ;" ...F)2AL+ES (/6a"#K ?>%?;a7F /6a"#K ?>%?;a7F ...F)

    ormat 2

    INSERT TRANSACTION 7a>sa;7?>_>a#INTO 7a&"#_>a# (;" ;" ...F)SELECT ...

    ;se ormat 1to insert a ne? ro? using 4alues from +our ali#ation.

    ;se ormat 2to insert a ne? ro? using 4alues retrie4ed from another table or tables. !his methods adds one ne? ro?for ea#h ro? returned b+ the SELEC! statement.

    transaction8nameis the name of a transa#tion de#lared b+ a re4ious SE! !R(0S(C!0 statement.

  • 8/11/2019 Embedded Sq l

    38/55

    3) Embedded SQL Guide for RM/Cobol

    table8nameis the name of the table to re#ei4e the ne? ro?.

    colis the name of a #olumn ?hi#h is to re#ei4e a ne? 4alue.

    &alueis an e8ression gi4ing a ne? 4alue. t ma+ be an+ e8ression that returns a 4alue #omatible ?ith the data t+eof the #orresonding #olumn.

    in#icatoris a otional host 4ariable #ontaining the 0;LL status flag of the #orresonding #olumn. ( 4alue of B1indi#ates that the #olumn is 0;LL@ Kero indi#ates 0! 0;LL.

    E8amle!he follo?ing S%+Tstatement adds one ne? dri4er ,9>;0!>!9E N '- to the 9ER(!0Stable.E@ 9>;0!>@ 9>;0!>!9E- %(L;ES ,:SB@ :SB;0!B@ '-!he follo?ing S%+Tstatement adds a series of ne? ro?s to the 9ER(!0S table from a temorar+ table holdingro?s to be imorted.

    EXEC SQL INSERT INTO OPERATIONS (OP_ID OP_+NIT_ID OP_+NIT_TMPE) SELECT TE*P_ID TE*P_+NIT_ID TE*P_+NIT_TMPE RO* TE*P_TABLE

    #.&. 04dating !ata

    !o #hange 4alues for e8isting ro?s of data in a table@ use the UPDAT%statement. UPDAT%#hanges the 4alues of #olumnsse#ified in the S%T#lause. Columns not aearing in the S%T#lause are not #hanged. ( singleUPDAT%statement #anmodif+ an+ number of ro?s in a table.

    #.&.1. "he 0P!'"E statement

    +PDATE TRANSACTION 7a>sa;7?>_>a# 7a&"#_>a#

    SET ;"=/6a"#K ;"=/6a"#K ...FWHERE /s#a;8_;>%?7?>K WHERE C+RRENT O ;s_>a#F

    transaction8nameis the name of a transa#tion de#lared in a re4ious SE! !R(0S(C!0 statement.

    table8nameis the name of the table to be modified.

    colis the name of a #olumn to be modified.

    &alueis an e8ression gi4ing the ne? 4alue. t ma+ an+ e8ression that returns a 4alue #omatible ?ith the data t+eof the #orresonding #olumn.

    search8con#itionis a #onditional e8ression ?hi#h determines ?hi#h ro?,s- of the table are to be modified.

    cursor8nameis the name of a #ursor de#lared in a re4ious ECL(RE C;RSR statement. !he most re#entl+ fet#hed

    ro? from this #ursor ?ill be modified if this #lause is used.f neither search8con#ition or cursor8nameis gi4en then the UPDAT%statement ?ill affe#t e4er+ ro? in the table.

    %am*le

    !he follo?ing UPDAT%statement ?ill #hange the total re4enue for load 123"'6 to X***..

    EXEC SQL +PDATE LOADS SET LD_TTL_RE2EN+E = .00 WHERE LD_LOAD_N+*BER = 1,35

    !he follo?ing UPDAT%statement ?ill udate the load last read b+ #ursor C1.

    EXEC SQL

  • 8/11/2019 Embedded Sq l

    39/55

    Embedded SQL Guide for RM/Cobol 3*

    +PDATE LOADS SET LD_TTL_RE2EN+E = .00 WHERE C+RRENT O C1

    !he follo?ing UPDAT%statement ?ill in#rease the total re4enue b+ 1W for all loads.E!!L>RE%E0;E N L>!!L>RE%E0;E 1.1

    #.(. !eleting !ata

    !o remo4e ro?s of data from a table@ use the D%/%T%statement. ( single D%/%T%statement #an be used to remo4e an+number of ro?s from a table.

    #.(.1. "he !ELE"E Statement

    DELETE TRANSACTION 7a>sa;7?>_>a#RO* 7a&"#_>a#WHERE /s#a;8_;>%?7?>K WHERE C+RRENT O ;s_>a#F

    transaction8nameis the name of a transa#tion de#lared in a re4ious SE! !R(0S(C!0 statement.

    table8nameis the name of the table to be modified.

    search8con#itionis a #onditional e8ression ?hi#h determines ?hi#h ro?,s- of the table are to be deleted.

    cursor8nameis the name of a #ursor de#lared in a re4ious ECL(RE C;RSR statement. !he most re#entl+ fet#hedro? from this #ursor ?ill be deleted if this #lause is used.

    f neither search8con#ition or cursor8nameis gi4en then the D%/%T%statement ?ill remo4e all ro?s from thetable.

    %am*le

    !he follo?ing D%/%T%statement ?ill remo4e load 123"'6 from the L(S table.

    EXEC SQL DELETE RO* LOADS WHERE LD_LOAD_N+*BER = 1,35

    !he follo?ing D%/%T%statement ?ill remo4e the last ro? fet#hed b+ #ursor C1.EXEC SQL DELETE RO* LOADS WHERE C+RRENT O C1

    !he follo?ing D%/%T%statement ?ill remo4e all ro?s from the L(S table.

    EXEC SQL DELETE RO* LOADS

  • 8/11/2019 Embedded Sq l

    40/55

    " Embedded SQL Guide for RM/Cobol

    &. 'ccessing lob !ata

    ( lob is a d+nami#all+ siKable data t+e that has no se#ified siKe and en#oding. ou #an use a lob to store largeamounts of data of 4arious t+es@ in#luding

    itmaed images

    Sound and 4ideo!e8t

    e#ause lobs are large 4ariabl+ siKed obe#t =irebird stores them as a series of segments. !hese segments are inde8ed b+ ahandle that =irebird generates ?hen +ou #reate the lob. !his handle is 5no?n as the lob and is a 6" bit 4alue#ontaining a #ombination of the table and lob identifiers.

    !he lob is stored in a #olumn in the table ro?. !he lob oints to the first segment of the lob. ou #an retrie4ethe lob b+ e8e#uting a SELEC! statement that se#ifies the lob as a target. (s follo?s

    EXEC SQL SELECT OP_LOADS RO* OPERATIONS INTO WS-LOADS-ID WHERE OP_+NIT_ID = 'TLR1,3'

    :hen +ou #reate a lob #olumn in a table@ +ou se#if+ the e8e#ted siKe of the lob segments for that #olumn. !he defaultsegment length is ) b+tes. =or most ra#ti#al uroses the segment siKe is irrele4ant. !he e8#etion to this is embeddedSQL ali#ations. !he embedded SQL re#omiler@ g*re@ uses the segment siKe de#lared for the #olumn to determine thesiKe of a temorar+ buffer that is allo#ated to hold the lob segments as the+ are transferred to and from +our ali#ation.!he siKe of the buffer #an be o4erridden b+ using the 'A5'U'8S%'%T#lause of the ECL(RE C;RSRstatement. n an+ #ase@ +ou do not ?ant to tr+ to read or ?rite more than the segment siKe in one oeration as +ou ?illo4erflo? the temorar+ buffer and the results ?ill be unredi#table. !he ma8imum allo?ed segment siKe is 32@&6& b+tes.

    &.1. Retrie6ing lob !ata

    Retrie4ing a lob in4ol4es t?o stes retrie4ing the lob and retrie4ing the lob itself. !he lob is retrie4ed b+using a standard singleton sele#t or b+ using a standard #ursor. !he lob data is retrie4ed using a lob #ursor.

    &.1.1. Retrie6ing the lob 5!

    ou #ould retrie4e the lob using a singleton sele#t as follo?s

    01 WS-BLOB-ID PIC S(1) +SAE BINARM()...

    EXEC SQL SELECT OP_LOADS INTO WS-BLOB-ID RO* OPERATIONS WHERE OP_+NIT_ID = 'TLR1,3'

    r +ou #ould retrie4e the lob using a #ursor and fet#hing it as follo?s

    01 WS-BLOB-ID PIC S(1) +SAE BINARM()....

    EXEC SQL DECLARE C1 C+RSOR OR SELECT OP_LOADS RO* OPERATIONS .EXEC SQL OPEN C1 . PEROR* +NTIL SQLCODE = 100 EXEC SQL ETCH C1 INTO WS-BLOB-ID ... END-PEROR*. EXEC SQL CLOSE C1 .

  • 8/11/2019 Embedded Sq l

    41/55

    Embedded SQL Guide for RM/Cobol "1

    &.1.2. Retrie6ing the lob !ata

    (s mentioned re4iousl+@ lob data is retrie4ed using a lob #ursor. !his in4ol4es se4eral stes de#laring a L RE(#ursor@ oening the #ursor@ fet#hing the data and #losing the #ursor.

    &.1.2.1. !eclaring RE'! L3 Cursors

    DECLARE ;s_>a# C+RSOR OR READ BLOB ;" RO* 7a&"# ILTER RO* s&7!#F TO s&7!#F *AXI*+*_SE*ENT "#>J78

    cursor8nameis the name of the #ursor ?hi#h ?ill be used in subseFuent 9E0@ =E!C$ and CLSE statements.

    colis the name of the lob #olumn.

    tableis the name of the table #ontaining the lob.

    /T%+ ...se#ifies an otional lob filter ?hi#h is used to translate a lob from one subt+e to another. lob filtersare outside the s#oe of this manual.

    lengthse#ifies the siKe of the temorar+ buffer used to transfer the lob data to and from the ali#ation. o not tr+ to

    read or ?rite more than lengthb+tes in a single oeration or unredi#table results ?ill o##ur.%am*le

    !he follo?ing #ursor retrie4es the lob for the 9>L(S #olumn from the 9ER(!0S table.

    EXEC SQL DECLARE C1 C+RSOR OR READ BLOB OP_LOADS RO* OPERATIONS

    &.1.2.2. 34ening RE'! L3 Cursors

    OPEN ;s_>a# +SIN 6a

    cursor8nameis the name of a #ursor re4iousl+ de#lared in a ECL(RE C;RSR statement.

    &aris a host 4ariable #ontaining the lob .

    %am*le

    !he follo?ing #ode sniet de#lares and oens a read blob #ursor.

    EXEC SQL DECLARE C1 C+RSOR OR READ BLOB OP_LOADS RO* OPERATIONS

    EXEC SQL OPEN C1 +SIN WS-BLOB-ID

    &.1.2.. =etching lob !ata

    ETCH ;s_>a#INTO 6a INDICATORF s#J#>7_"#>J78F

    cursor8nameis the name of a #ursor de#lared in a re4ious ECL(RE C;RSR statement.

    &aris the name of the host 4ariable that is to re#ei4e the lob data.

    segment8lengthre#ei4es the number of b+tes fet#hed. !his ma+ be less then the lobAs segment siKe ?hen fet#hing thelast segment of a lob.

    %TC)returns to SQLCE 4alues of interest

    1 indi#ates that there are no more lob segments to retrie4e.

    11 indi#ates that the segment ?as larger that the segment buffer ro4ided b+ &ar.

    %am*le

    !he follo?ing #ode sniet de#lares a lob #ursor@ oens it and fet#hes all segments of the lob. =et#hing of the lob

  • 8/11/2019 Embedded Sq l

    42/55

    "2 Embedded SQL Guide for RM/Cobol

    itself is omitted in the interests of #larit+.

    01 WS-B+ER PIC X(1000).01 WS-LENTH PIC ().01 WS-BLOB-ID PIC S(1) BINARM()....#7;8 78# B"& ID

    ...EXEC SQL DECLARE C1 C+RSOR OR READ BLOB OP_LOADS RO* OPERATIONS *AXI*+*_SE*ENT 1000 .EXEC SQL OPEN C1 +SIN WS-BLOB-ID . PEROR* +NTIL SQLCODE = 100 EXEC SQL ETCH C1 INTO WS-B+ER WS-LENTH ... END-PEROR*.EXEC SQL CLOSE C1 .

    &.1.2.#. Closing RE'! L3 Cursors

    Read blob #ursors are #losed in the same ?a+ as an+ other #ursor@ using the CLSE statement.

    &.2. 04dating lob !ata

    :hile it is ossible to retrie4e lob data from a table and insert lob data into a table@ it is not ossible to dire#tl+ udate alob nor to delete one. ( lob is udated b+ inserting a ne? lob and setting the lob to the 4alue of the ne? lobAs. !his deletes the old lob and rela#es its ?ith the ne? one. ( lob is deleted in one of t?o ?a+s b+ deleting thero? ?hi#h o?ns the lob or b+ setting the lob to 0;LL. nserting a ne? lob in4ol4es t?o stes inserting the lobusing a lob insert #ursor and udating the table ?ith the ne? lob .

    &.2.1. 5nserting lob !ata

    &.2.1.1. !eclaring L3 5SER" Cursors

    DECLARE ;s_>a# C+RSOR OR INSERT BLOB ;" INTO 7a&"# ILTER RO* s&7!#F TO s&7!#F *AXI*+*_SE*ENT "#>J78

    cursor8nameis the name of the #ursor ?hi#h ?ill be used in subseFuent 9E0@ 0SER! and CLSE statements.

    colis the name of the lob #olumn

    tableis the name of the table #ontaining the lob

    /T%+ ...se#ifies an otional lob filter ?hi#h is used to translate a lob from one subt+e to another. lob filtersare outside the s#oe of this manual.

    lengthse#ifies the siKe of the temorar+ buffer used to transfer the lob data to and from the ali#ation. o not tr+ toread or ?rite more than lengthb+tes in a single oeration or unredi#table results ?ill o##ur.

    %am*le

    !he follo?ing de#lares a #ursor that #an be used to insert a ne? lob into the 9ER(!0S table.

    EXEC SQL DECLARE C1 C+RSOR OR INSERT BLOB OP_LOADS INTO OPERATIONS

    &.2.1.2. 34ening L3 5SER" Cursors

    OPEN ;s_>a# INTO 6a

  • 8/11/2019 Embedded Sq l

    43/55

    Embedded SQL Guide for RM/Cobol "3

    cursor8nameis the name of a #ursor de#lared in a re4ious ECL(RE C;RSR statement.

    &aris the name of a host 4ariable ?hi#h ?ill re#ei4e the ne? lob .

    %am*le

    !he follo?ing #ode sniet de#lares a L 0SER! #ursor and oens it.

    EXEC SQL DECLARE C1 C+RSOR OR INSERT BLOB OP_LOADS INTO OPERATIONSEXEC SQL OPEN C1 INTO WS-BLOB-ID

    &.2.1.. 5nserting lob !ata

    INSERT C+RSOR ;s_>a#2AL+ES (&$$# INDICATORF s#J#>7_"#>J78)

    cursor8nameis the name of a #ursor de#lared in a re4ious ECL(RE C;RSR statement.

    bufferis a host 4ariable #ontaining the data to be ?ritten to the lob.

    segment8lengthis a host 4ariable holding the number of b+tes of data in buffer.

    Ea#h e8e#ution of the S%+