sy required sql changes for ase15 v.1 073009 wp

Upload: santosh

Post on 07-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    1/22

    RequiredSQLCodeChangesWhen

    MigratingToASE15

    TECHNICAL WHITE PAPER

    www.sybase.com

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    2/22

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    3/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009i

    Contents

    Introduction............................................................................................................................................... 1Fetchingfromacursorwhilemodifyingtheunderlyingtables................................................................ 2

    Solution..................................................................................................................................................................3Insensitivecursorvs.semi_sensitivecursors........................................................................................................3'Groupby'without'Orderby'................................................................................................................... 4OAMbasedbuiltinsystemfunctions(e.g.rowcnt()).............................................................................. 6Pre15partitionedtables.......................................................................................................................... 7ObjectIDinpageheader........................................................................................................................... 8DirectSQLqueriesjoiningsysdevices+sysusages.................................................................................. 10255ByteidentifiersinASE15................................................................................................................. 12Determiningsessionownershipof#temporarytables........................................................................... 13Miscellaneous.......................................................................................................................................... 15

    RunningUpdateStatisticsinASE15....................................................................................................................15Optimisticrecompilation&sp_recompile...........................................................................................................15

    ReferenceDocuments............................................................................................................................. 16

    AuthorRobVerschoor [email protected]

    RevisionHistoryVersion1.0 May2009

    Version1.1 July2009

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    4/22

    ii Using'CompatibilityMode'InASE15.0.3ESD#1ForASE15MigrationVersion1.1 July2009

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    5/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July20091

    Introduction

    ThiswhitepaperdescribeschangesthatmayneedtobemadetoexistingSQLcodewhenmigratingfromASE12.5

    toASE15toensuretheSQLcodecontinuestofunctioncorrectly.

    Ingeneral,therewillbelittleornoneedtomodifyanyexistingSQLcodeinbusinessapplicationswhenmigrating

    toASE15.Nevertheless,insomespecificcases,asdescribedinthisdocument,particularSQLconstructsmayneed

    tobechangedtoensuretheSQLcodecontinuestofunctionthesameasinASE12.5.Mostofthesecasesare

    unlikelytooccurinbusinessapplications,butwilltypicallybefoundinotherareassuchasDBAtoolsor

    maintenancescripts.

    However,thisdocumentdescribestwoexceptionsoffunctionalbehaviourchangeofexistingSQLcode,which

    mightindeedbeusedinbusinessapplications:

    - aparticulartypeofcursor,combinedwithveryspecificapplicationbehaviourpatterns:seepage2- queriesusingagroup byclausewithoutanorder byclause,butneverthelessrelyontheimplicitly

    definedresultsetorderinginASEpre15.0:seepage4

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    6/22

    2RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    Fetchingfromacursorwhilemodifyingtheunderlyingtables

    Sybasehasidentifiedascenariowherebyaparticularsequenceofeventsmaycauseanapplicationtobehave

    functionallydifferentinASE15thanin12.5. Thiscouldpotentiallyaffectbusinessapplications.

    Forthisscenariotopotentiallyoccur,atleastallofthefollowingmustbetrue:

    Theclientapplicationisfetchingfromacursor. Thequeryplanforthecursor'sselectstatementinvolvesaworktableinASE12.5,forexampleasa

    resultofadistinct, group by,order byorunionoperationinthequery.

    Whiletheapplicationisfetchingrowsfromthecursor, rowsintheunderlyingtablesarebeingmodifiedbyanotherapplication(orbythesameapplicationonadifferentconnection);theaffectedrowswouldbe

    reflectedintheresultsetifthecursorwouldbeopenedandevaluatedagain.

    Ifalloftheseconditionsapply,thenthepossibilityexiststhattheapplicationcouldfetchdifferentresultsfromthe

    cursorinASE15thanitdoesin12.5.Notethatitisnotguaranteedthatthisinterferencewillindeedoccur this

    dependsontheactualtimingofthedifferentactions.

    Ironically,thisproblem assumingitoccurs iscausedbyasideeffectofaqueryprocessingenhancementinASE15

    whichinterfereswithapplicationbehaviourinanunexpectedway.

    Thefollowingishappeningin12.5:

    InASE12.5,distinct, group by,order byorunion inthequerycanleadtoaqueryplanwithaworktable,wherebytheresultsetrowsareallbufferedintheworktablebeforethefirstrowcanbe

    fetched.Whenfetchingrowsfromthecursor,theyareactuallyfetchedfromtheworktablewhichatthat

    pointalreadyholdsthefullresultset.

    When,atthesametimeasthefetchinggoesonin12.5,rowsintheunderlyingdatabasetablesaremodifiedbyanotherapplication,thenthesechangeswillnotbereflectedintherowsbeingfetchedfrom

    thecursor:allresultsetrowsarealreadybufferedintheworktable,sochangestodatarowsinthe

    underlyingtablewillnotaffectthecursor'scurrentresultsetanymore.

    Thissequenceisschematicallyshownbelow:

    Session1 Session2

    declare my_curs cursor

    for

    select distinct col1, col2

    from my_tab

    -- assuming > 1 row found:

    open my_curs

    fetch my_curs

    delete my_tab

    -- the result of the following fetch could be affected by the

    delete in session 2

    fetch my_curs

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    7/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July20093

    -- ASE 12.5: this last fetch will return 1 row

    -- ASE 15: this last fetch may or may not return a row

    Now,whenmigratingthisscenariotoASE15,thissamequerywithdistinct, group by, order byor

    union islikelynottouseaworktableatall:ASE15useshashbasedalgorithmsforevaluatingtheseconstructs,

    andtheserequirenoworktableatall.Consequently,inASE15thiscursorisnotbufferingallresultsetrowsina

    worktable,butgraduallyscanningovertheunderlyingbasetablesasrowsarebeingfetchedfromthecursor.In

    thissituation,whenanotherapplicationmodifiesrowsinthosesamedatabasetables,thiscouldleadtodifferent

    resultsbeingreturnedbythecursor,becausethecursormaystillaccessthemodifiedrowsaspartofitsongoing

    scan.

    SolutionThesolutionforthisprobleminASE15isoneofthefollowing:

    Modifythecursordeclarationtoincludethekeyword'insensitive',e.g.:declare my_curs insensitive cursor

    forselect distinct col1, col2

    from my_tab

    Sybaserecommendsthissolution.

    Ifitisnotpossibletomodifythecursordeclaration,thentraceflag457canbeenabled.ThiswillcauseASEtousethe12.5methodofprocessingthedistinct, group by, order byorunion.Notethat

    thiscouldnegativelyaffectperformance.Traceflag457takesimmediateeffect,andappliesserverwide.

    Tousetraceflag457,itisrequiredtorunASEversion15.0.2ESD#6orlater.

    Insensitivecursorvs.semi_sensitivecursorsASE15hasbeenextendeditssupportforcursorsbyallowingthesetobedeclaredeitherasaninsensitive

    cursororasemi_sensitive cursor.

    Foraninsensitivecursor,changestodataintheunderlyingtablesafterthecursorhasbeenopened,willnotbe

    visibleintheresultset,astheresultsetwillbebufferedinaworktable.Thisisessentiallymatchingthedescription

    ofthe12.5problemscenarioabove withthedifferencethatwhenacursorisdeclaredasinsensitive,a

    worktablewillbeusedevenwithoutadistinct, group by, order byorunion inthequery.

    Incontrast,asemi_sensitive cursorwillnotbuffertheresultsetinaworktablepriortothefirstfetch

    operation,andchangestotheunderlyingtablesmaythereforeaffecttheresultset,asdescribedabove.

    InASE12.5,thedefaultbehaviourcorrespondstoinsensitivewhileinASE15,thedefaultis

    semi_sensitive.Forthisreason,thescenarioabovecouldpotentiallyleadtodifferentresults.Forthisreason,

    declaringacursorexplicitlyasinsensitivewillavoidthisproblem.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    8/22

    4RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    'Groupby'without'Orderby'

    Asyouarenodoubtaware,theANSISQLstandardspecifiesthattheorderofrowsintheresultsetofaSQLquery

    isundefinedunlessanorder byclauseisspecified. InpracticeinASEhowever,theresultsetorderwasoften

    predictableandindeedreliableevenwithoutanorder by clause,asitfollowedlogicallyfromthechoiceof

    indexesinthequeryplan.

    However,overtheyears,newfeatureswereintroducedthatmadethisimplicitresultsetorderingevermore

    unpredictable.Suchfeaturesincludeparallelqueryprocessing(ASE11.5)andDOLrowforwarding(ASE11.9).

    InASE15,thereisyetanothercasewheretheresultsetorderwaspreviouslypredictablewithoutanorder by,

    butthiscannolongerbereliedon.Thisconcernsthecaseofaquerywithagroup byclausebutnoorder by.

    Inpre15,theorderoftheresultingrowswouldbeguaranteedtobeinthesortingorderofthecolumnsspecified

    inthegroup byclause;thiswasasideeffectofthe ratherclassic sortingmethodforthegroup by.

    Pre15: notethatresultsareinalphabeticalorderfor'type':

    1> select count(*), type

    2> from sysobjects group by type

    3> gotype

    ----------- ----

    1 D

    55 P

    52 S

    19 U

    4 V

    ThishaschangedinASE15.AmongthemanyqueryprocessingenhancementsinASE15aremoremodernsorting

    algorithmsbasedonhashingtechniques.Thesesortingmethodsarefasterthantheclassicsortingofpre15,but

    theresultsetisnolongerautomaticallyinthesortorderofthegroup bycolumns.

    ASE15.0:notetherowsarenolongeralphabeticallyorderedon'type':

    1> select count(*), type

    2> from sysobjects group by type

    3> go

    type

    ----------- ----

    1 V

    55 S

    3 U

    12 P

    Unfortunately,itappearedthatsomecustomershadbeeninadvertentlyrelyingontheguaranteedresultsetorder

    foragroup bywithoutorder by. Toofferashorttermsolution,traceflag450wasintroducedinversion15.0

    ESD#2:whenthistraceflagisenabled,ASEwillreverttothelessperforming,pre15sortingalgorithmforgroup

    by sorting,thusrestoringtheexpectedresultsetordering.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    9/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July20095

    Ofcourse,therealsolutionistomakesurethatorder byisspecifiedforeveryquerywheretheresultset

    orderingmatters.

    Thisissuecouldpotentiallyoccurinbusinessapplications,ifimplicitresultsetorderinghasbeenreliedupon.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    10/22

    6RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    OAMbasedbuiltinsystemfunctions(e.g.rowcnt())

    OneofthemajorenhancementsinASE15issupportforsemanticallypartitionedtables.Thisrequiredsomelow

    levelchangesinASEwhicharerelevantevenwhensemanticpartitioningisnotevenusedinASE15.

    OneofthesechangeshastodowiththebuiltinsystemfunctionsretrievinginformationfromtheOAMpage,such

    asrowcnt().Thesefunctionsalwayshadtobecalledwitheitherthedoampgorioampgcolumnfromthe

    sysindexestable.

    Sincethesefunctionsonlyprovideinformationaboutthesizeoftablesandindexes,itisquiteunlikelythatthey

    wouldbepartofbusinesslogic.Instead,thefunctionsaretypicallyonlyfoundinDBAtools,suchasscriptsto

    reportonspaceusageandrowcountsofthelargesttables.

    InASE15,thesebuiltinsystemfunctionsshouldbechangedtoverysimilarnamedequivalents,asshownbelow.

    Thenewfunctionsalsohaveaslightlydifferentinterface,butfortunately,thingshavegottensimplertousesince

    specifyingthedoampg/ioampgcolumnsarenolongerrequired.Instead,itissufficienttospecifytheIDvalues

    forthedatabase,object,indexorpartition.

    ThefollowinglistshowsthefunctionsinASE12.xandthecorrespondingnewfunctionsinASE15:

    Pre15: rowcnt ( doampg)

    ASE15: row_count ( dbid, objid[,ptnid] )

    Pre15: data_pgs( objid, { doampg| ioampg} )

    ASE15: data_pages ( dbid, objid[, indid[,ptnid]] )

    Pre15: ptn_data_pgs ( objid,ptnid)

    ASE15: data_pages ( dbid, objid[, indid[,ptnid]] )

    Pre15: reserved_pgs ( objid, { doampg| ioampg} )

    ASE15: reserved_pages ( dbid, objid[, indid[,ptnid]] )

    Pre15: used_pgs ( objid, doampg, ioampg)

    ASE15: used_pages ( dbid, objid[, indid[,ptnid]] )

    Itshouldbenotedthatthepre15functionsstillexistinASE15,buttheywillnowalwaysreturnavalueofzero.

    Thismeansthat,inprinciple,existingSQLcodecallingthepre15functionswillkeeprunning,butresultsare

    unlikelytobecorrect.Maintainingthepre15functionsalsointroducestheriskofdividingbyzero,forexample

    whencalculatingnumberofrowsperpagewiththesefunctions;thiswouldleadtoaruntimeerror,abortingSQL

    execution.

    Inaddition,foreveryinvocationofthepre15functionsawarninglikethefollowingwillbegenerated,thusmaking

    itunlikelythatthepre15functionswillgounnoticed:

    The built-in function 'rowcnt' has been deprecated. Use the new built-

    in function 'row_count' instead.Deprecated function returns value of 0.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    11/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July20097

    Pre15partitionedtables

    Partitionedtableswerefirstintroducedinversion11.0ofASE(whichwasatthattimestillnamed"SybaseSQL

    Server"). InASE15,thispartitioningmethodisnowknownas"roundrobin"partitioning,withcorrespondingnew

    syntax.However,thecorrespondingpre15syntaxisstillsupported,withoneexceptionasdescribedbelow.

    NotethatroundrobinpartitioningisnotsubjecttolicensingtheASE_PARTITIONSoption:thisfunctionality

    remainsincludedinthecoreASEproduct.

    AspartofupgradingadatabasetoASE15,anypre15partitionedtableswillautomaticallybeunpartitioned.IfSQL

    querieshavebeenwrittenspecificallyforusingparallelpartitionscanbasedprocessinginpre15,andthis

    behaviourshouldbemaintained,thenthesetablesshouldberepartitionedandrebalancedaftertheupgrade.

    Querieswillkeepworkingcorrectly,butwithoutrepartitioning,performancemaybelessthanexpected.

    Havingsaidthat,especiallyforqueriesthatreliedonparallelpartitionscans,ASE15maywellbeoffering

    fundamentallyfasterprocessingmethodsintheformofhashjoins,hashbasedsortingandotherenhanced

    internalalgorithms.Beforerepartitioningthepre15tables,itisrecommendedtoinvestigatewhetherthenew

    ASE15featuresyieldbetterperformance.Indeed,variouscustomershavereportedthatASE15performedbetter

    inserialmodethanASE12.5inparallelmode.

    Returningtothepre15syntaxforpartitionedtables:withoneexception,allpre15syntaxisstillvalid.Theexceptionisthefollowingstatement:

    alter table my_table unpartition

    Contrarytopre15,thisstatementwillnolongerworkifthetableinquestionhasanyindexes.

    ThenewimplementationofpartitionsinASE15requiresthatallindexesbedroppedbeforeanychangestothe

    partitioningschemecanbemade.Incontrast,thiscommandworkedfineinpre15withoutwithoutexisting

    indexes.

    Therefore,anyexistingSQLcodeperformingsuchanunpartitioningoperationwillneedtobemodifiedtodrop

    indexesfirst,andrecreatethemafterwards.

    Thiscommandisveryunlikelytooccurinbusinessapplicationlogic,butwilltypicallybefoundonlyinmaintenance

    scriptsortoolsfordefragmentingorrecreating/rebalancingpartitionedtables.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    12/22

    8RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    ObjectIDinpageheader

    Anothersideeffectofthelowlevelchangesthatwererequiredforimplementedpartitioning,isthefactthatthe

    pageheadersnolongercontaintheobjectIDinASE15.Instead,thepartitionIDisnowstoredinthelocation

    wheretheobjectIDusedtoreside.

    Obviously,thisisextremelyunlikelytoimpactanybusinessapplications:itwillaffectonlythoseDBAswithan

    interestinstaringatpageheadersofdataandindexpages,andtheirhomegrowntools.Thisappliesonlywhen

    usingdbcc pagetodisplaypagedetails.

    Pre15:

    PAGE HEADER:

    Page header for page 0x214D1000

    pageno=617 nextpg=0 prevpg=0 objid=1010786989 timestamp=0000 00000c30

    nextrno=0 level=0 indid=0 freeoff=32 minlen=6

    page status bits: 0x81 (0x0080 (PG_FIXED), 0x0001 (PG_DATA))

    ASE15:

    PAGE HEADER:

    Page header for page 0x22996800

    pageno=857 nextpg=0 prevpg=0ptnid=1229687001 timestamp=0000 000038d3

    nextrno=0 level=0 indid=0 freeoff=32 minlen=6

    page status bits: 0x81 (0x0080 (PG_FIXED), 0x0001 (PG_DATA))

    Now,itmayseemasifitisnolongerpossibleinASE15todeterminetheobjectforwhichagivenpagewas

    allocated,butthisassumptionwouldbeincorrect:sinceapartitionalwaysbelongstooneandonlyobject,the

    objectIDcanalwaysbederivedfromthepartitionID.

    Thiscanbedonewiththefollowingquery:

    select object_name(id)

    from syspartitions

    where partitionid = 1229687001

    Alternatively,andmoreconveniently,asof15.0.1,theobjectIDcanbederivedfromthepartitionIDwiththenew

    builtinfunctionpartition_object_id():

    select object_name ( partition_object_id ( 1229687001 ))

    Notethat,forunpartitionedtables,theobjectIDwilloftenbeidenticaltothepartitionID,thoughthisshould

    neverbereliedupon.

    ItmaysoundlikeacontradictionintermsthatanunpartitionedtablehasapartitionID.However,inASE15,every

    tableconsistsofatleastonepartition,specifically,oneroundrobinpartition.Itmaynotbeformallycorrecttocall

    suchatable"unpartitioned",butforallpracticalpurposes,itis.Alternatively,read"notexplicitlypartitioned"

    insteadof"unpartitioned".

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    13/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July20099

    Lastly,incaseyouwerewondering:itwouldindeedhavebeenmoreconvenienttojustaddthepartitionIDtothe

    pageheader,nexttotheobjectID,insteadofreplacingtheobjectID.However,thiswasnotpossibleforthesimple

    reasonthatthepageheaderwasfull:therequiredadditional4bytesweresimplynotavailable.Extendingthepage

    headerwasnotpossiblesincethiswouldhavemeantthatsomebyteshadtobetakenawayfromthedataareaon

    thepage whichisnotpossibleifthepagecontainsarowofthemaximumpossiblelength.

    Forthesereasons,theobjectIDwasreplacedwiththepartitionID.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    14/22

    10RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    DirectSQLqueriesjoiningsysdevices+sysusages

    PriortoASE15,itwasnoteasyforaDBAtogetspaceusageinformationaboutaparticulardatabasedevice.

    Twocommonexamplesare:howmuchunallocatedspaceisstillavailableonadatabasedevice,andwhich

    databaseshaveallocatedspaceonit?

    Inpre15versionsofASE,thesimplestwaytoanswerthesequestionsrequiredusingSybaseCentral.Alternatively,

    asindeedmanyDBAsdid,youcouldwriteyourownqueriesagainstthesystemtablessysdevicesand

    sysusagestoobtaintherequiredinformation.

    Forsuchaquery,whichwouldbejoiningsysdeviceswithsysusages,thejoinconditionalwayslooked

    somewhatunusual,with=operatorsasshownbelow(forrelationalpurists,thisisa"thetajoin").Thiswas

    duetointernalstructureofapagenumberwherebythehighest8bitsplayedaspecialrole,reflectingtheunique

    vdevnoasspecifiedindisk init.

    InASE15,changesweremadetotheinternalpagenumberconstructionasaresultofvastlyexpandingthe

    maximumsizeofanASEserver.Asaresult,anewcolumnvdevnowasaddedtobothsysdevicesand

    sysusages.Forqueriesjoiningthesetwotables,thingsactuallygotmuchsimplerasaresult,sinceasingle

    equijoinpredicateonvdevnoisnowsufficient:

    Pre15:

    select u.lstart, d.name

    from sysusages u, sysdevices d

    where u.vstart >= d.low -- join condition in pre-15

    and u.vstart sp_helpdevice

    2> go

    device_name physical_name description status

    cntrltype vdevno vpn_low vpn_high

    ----------- --------------------- -------------------------- --------------- ----------- ----------- -----------

    dev1 [...] physical disk, 900.00 MB, Free: 235.00 MB 16386

    0 2 0 460799

    []

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    15/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July200911

    Second,whencallingsp_helpdeviceforasingledatabasedeviceonly,itwillalsodisplayallallocated

    fragmentsonthedevice:

    1> sp_helpdevice dev1

    2> go

    device_name physical_name description status

    cntrltype vdevno vpn_low vpn_high

    ----------- --------------------- -------------------------- ------

    --------- ----------- ----------- -----------

    dev1 [...] physical disk, 900.00 MB, Free: 235.00 MB 16386

    0 2 0 460799

    (1 row affected)

    dbname size allocated vstart lstart

    ------ ------------ -------------------------- ----------- -----------

    z1 350.00 MB Sep 20 2005 8:01:56:346PM 0 0

    tempdb 4.00 MB Sep 27 2005 2:23:56:430PM 307200 2048

    demo3 250.00 MB Jan 5 2006 6:53:26:643PM 179200 0

    tempdb 6.00 MB Apr 4 2006 7:34:55:430PM 309248 4096

    demo 5.00 MB Jun 7 2006 1:02:09:543PM 312320 0demo2 50.00 MB Jun 7 2006 1:02:10:543PM 314880 0

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    16/22

    12RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    255ByteidentifiersinASE15

    OneofthemanychangesinASE15concernssupportforlongeridentifiers.Manyidentifiers,suchastablenames,

    columnnamesandstoredprocedurenames,cannowbeupto255byteslong,insteadof30bytesasinpre15.

    ThischangemayimpactSQLcodewhichdirectlyretrievessuchidentifiersfromtheASEsystemtables.Typically,

    thisdoesnotoccurinbusinessapplications,butismorelikelytobefoundinDBAtoolsandscripts.

    Foranexampleoftheimpact,considerasimplequerylikethis:

    select name, crdate

    from sysobjects

    where type = "U"

    order by name

    Inpre15,theresultsetwillconsistofatablewithtwocolumnswhicheasilyfitonan80characterwideoutput

    window:thenamecolumnis30characterswide,whilecrdatebydefaultresultsinacolumnof19characters

    wide.

    Now,inASE15,nameisreturnedasavalueof255characterswide.Theresultisthatthetwocolumnsnolonger

    fitonaline,butwraparoundafewtimes.Inotherwords:theformattingoftheoutputforsuchqueriesislikelyto

    become

    less

    tidy

    after

    upgrading

    to

    ASE

    15.

    Fortunately,variousremediesareavailable:

    Usethebuiltinfunctionsconvert()orleft()tolimitthenamestothefirst30charactersorso Usethesystemstoredproceduresp_autoformattoformatresults;sp_autoformattakesatable

    asinputandformatsthecolumnsonlyaswideasneededforthelongestactualvalueineachcolumn.

    Asanexample,tryrunningbothofthefollowing:

    select * from sysusers

    and:

    sp_autoformat sysusers

    SeetheASEdocumentationforfullusagedetailsofsp_autoformat.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    17/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July200913

    Determiningsessionownershipof#temporarytables

    Theextensionofidentifierlengthto255bytesinASE15alsoappliestotheinternalnamesofsessionspecific,non

    shareabletemporarytables(i.e.thosetableswhosenamesstartwith'#',suchas#t).ThisaffectsexistingSQL

    codewhichaccessesthoseinternalnamestodeterminethesessionowningaparticular#temptable.Thisis

    anotherexampleofSQLcodethatwilltypicallyonlyexistintools.

    First,somebackground.ConsideratablecreatedbythefollowingSQL:

    select *

    into #t

    from my_table

    Bydefinition,table#tisaccessibleonlybythesessionthatcreatedit. Internally,thetable'snameisnotjust#t,

    butrathersomethinglike#t___________00000210008240896 (in12.5);theinternalnamingcanbe

    observedbyqueryingsysobjectsinthesession'stemporarydatabase.

    Theinternalnamingof#temporarytableshasslightlychangedinASE15asaresultofintroducing255byte

    identifiernames.Inpre15,upto11underscorecharacterswereaddedtothe#temptable'snamesothatthe

    internalnamewouldalwaysbe30characterslong.Also,the#temptable'snameitselfcouldbenolongerthan13

    characters:anyadditionalcharacterswouldbeignored.ThisapproachhasbeendroppedinASE15(addinganother225underscoreswouldprobablyhavelooked

    awkward),andnounderscorepaddingisdoneanymore,andthemaximumlengthof13hasbeenextendedto238

    characters.Asaresult,theinternalnamefor#tinASE15wouldlooksomethinglike#t00000150003699485.

    Inpre15,SQLcodeaccessinginternal#temptable'snamescouldexpecttofindtheowner'ssessionID(spid)inthe

    fixedpositions1620;also,thenestinglevelatwhichthetablewascreatedwouldbeatpositions1415.For

    #t___________00000210008240896,thesessionowner'sspidis21,andthenestinglevelis0.The

    correspondingSQLquerywouldbe:

    select owner_spid= substring(, 16, 5),

    nestlevel= substring(, 14, 2)

    AsaresultofthechangesinASE15,thesevaluesarenolongerlocatedatfixedpositions,sotheSQLquerymust

    bechangedaccordinglyasfollows:

    select owner_spid= substring(right(,17), 3, 5),

    nestlevel= substring(right(,17), 1, 2)

    For#t01000150003699485,thislastquerywillcorrectlyidentifythatitisownedbysession15andcreatedat

    nestinglevel1.

    Notethatthereisnomeaningfulimpactonhow#temptableswork,seenonthelevelofregularSQL.Theabsence

    ofpaddingunderscoresdoeshowevetmeanthatsomespecific#temptablenamingthatleadstoSQLerrorsinpre

    15nowrunscorrectlyinASE15.However,thatcanhardlybecalledaproblem.

    Forexample,thefollowingtwosequenceswouldfailin12.xbutsucceedin15.0:

    create table #t (a int)

    create table #t__ (a int) SQLerrorin12.x:'#t'alreadyexists

    create table #t12345678901 (a int)

    create table #t123456789012 (a int) SQLerrorin12.x:'#t12345678901' alreadyexists

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    18/22

    14RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    19/22

    RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July200915

    Miscellaneous

    This section describes two aspects of SQL changes in ASE 15 whose impact is somewhatdifferent from the other cases in this document.

    RunningUpdate

    Statistics

    in

    ASE

    15

    InASE15,havingsufficientandaccuratestatisticsondatabasetablesismoreimportantthanitwasinpre15.

    Withoutproperstatistics,applicationperformancecouldsuffer,thoughthiswouldnotimpactcorrectfunctioning

    ofapplications.

    Formoreinformationaboutthebackgroundofthisrequirement,pleaserefertothewhitepaper"SybaseASE15BestPractices:QueryProcessing&Optimization"(URLonpage16).Whatthismeansinpracticeisthatitisrecommendedtorunupdate index statisticsratherthan

    update statistics. Consequently,DBAsmayneedtoupdatetheirmaintenancescriptsaccordingly.

    Whenrunningupdate index statistics onlargetables,itmaybealsobeneededtousethewith

    samplingclausetoavoidoverrunningtempdbortheprocedurecache,and/orspecifyinganexplicitstepcount

    withtheclauseusing nnn values.Again,seethewhitepapermentionedaboveformoredetails.

    Whileupdate statisticsistypicallyfoundinmaintenancescripts,inrarecasesthismightalsooccurinSQL

    codeinbusinessapplications. Ifthisoccurs,itistypicallywhenatemporarytablehasbeenpopulatedwithdata,

    andupdate statistics isrequiredtoensuretheproperqueryplanisselectedinsubsequentprocessing.In

    suchcases,itmaywellberequiredtochangethistoupdate index statistics aswell.Againthough,this

    wouldonlyhaveaperformanceeffectratherthanleadtoincorrectapplicationbehaviour.

    Optimisticrecompilation&sp_recompileOver the years, DBAs have routinely been running sp_recompile after running

    updatestatistics, to ensure that the new statistics will be considered for future queries.

    As of ASE 15, sp_recompile is no longer needed once statistics are updated, as the

    sp_recompile functionality is now implicitly included in updatestatistics. The same

    applied when creating a new index on a table: it is no longer needed to run sp_recompile.

    However, it is not needed to change any of the maintenance scripts where sp_recompile

    might occur, since executing sp_recompile in those cases is totally harmless.

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    20/22

    16RequiredSQLcodechangeswhenmigratingtoASE15

    Version1.1 July2009

    ReferenceDocuments

    Technicalwhitepaper"SybaseASE15BestPractices:QueryProcessing&Optimization":http://www.sybase.com/detail?id=1056243

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    21/22

  • 8/6/2019 SY Required SQL Changes for ASE15 v.1 073009 WP

    22/22

    CONTACTINFORMATION

    ForEurope,MiddleEast,

    orAfricainquiries:

    +(31)346582999

    ForAsiaPacificinquiries:

    +85225068900(HongKong)

    ForLatinAmericainquiries:

    +7707773131(Atlanta,GA)

    SYBASE,INC.

    WORLDWIDEHEADQUARTERS

    ONESYBASEDRIVE

    DUBLIN,CA945687902USA

    Tel:18008SYBASE

    www.sybase.com

    Copyright2009Sybase,Inc.Allrightsreserved.UnpublishedrightsreservedunderU.S.

    copyrightlaws.Sybase,andtheSybaselogoaretrademarksofSybase,Inc.oritssubsidiaries.

    Allothertrademarksarethepropertyoftheirrespectiveowners.indicatesregistrationinthe

    UnitedStates.Specificationsaresubjecttochangewithoutnotice. 2/09.