Tải bản đầy đủ - 0 (trang)
Hack 54. Use Regular Expressions in Access Queries

Hack 54. Use Regular Expressions in Access Queries

Tải bản đầy đủ - 0trang

Thishackassumesthemachineyouarerunninghasthelatestversion

ofMicrosoft'sScriptingEngineinstalled.Ifyouareunsure,visit

http://www.microsoft.com/scripting.



ThefollowingcodeusestheCreateObjectfunctionsothatyou

don'thavetochecktheReferenceeachtimethecodeisplacedin

anewdatabase:



PublicFunctionRegExp(strStringAsString,_

strRegExpAsString,OptionalbolIgnoreCaseAsBoolean

Boolean

DimreAsObject

Setre=CreateObject("vbscript.RegExp")

re.Pattern=strRegExp

re.IgnoreCase=bolIgnoreCase

Ifre.Test(strString)Then

RegExp=True

Else

RegExp=False

EndIf

EndFunction



Thefunctionhastworequiredparameters:thestringbeing

matchedagainstandthestringthatcontainstheregular

expression.Thethird,optionalparametertellsthefunction

whethertomatchtheregularexpressionwhileignoringthe

case;thedefaultwon'tignorethecase.



5.16.2.CreatinganExampleQuery



Asanexample,let'slookatverifyingpartnumbersbyfinding

thosethatdon'tmatchagivencriterion.Manytimes,youmight

receivedatafrommultiplepeopleandplatformsthatneedsto

becleanedbeforegoingintoamasterdatabase.Let'ssaythat

partnumbersforafactoryhavethefollowingcriteria:

TheymuststartwithacapitalPNoracapitalP.

Thenexttwopositionsmustbenumeric.

Thenextpositionmustbeacapitalletter(AZ).

Thenextthreetofourpositionsmustbenumeric.

Thenextfivetosixpositionsmustbecapitalletters(AZ).

Examplesofpartnumbersthatmeetthecriteriainclude

PN12W123ABCDEandP12W123ABCDE.Examplesthatdon't

meetthecriteriaincludePN12W13ABCDE(onlytwodigitsafter

theW)and12W123ABCDE(doesn'tstartwithPNorP).

Giventhesetofcriteriaforthepartnumber,here'stheregular

expression:





"^(PN|P)[0-9][0-9][A-Z][0-9]{3,4}[A-Z]{5,6}$"



Asmentionedearlier,theseregularexpressionscanbecome

quiteoverwhelminguntilyougetusedtothem.Ifyouaren't

familiarwiththem,Istronglyrecommendadditionalreadingto

learnthefullpoweroftheseexpressions.Tobetterunderstand

it,let'sbreakdownthisexpression:



^

Tellstheexpressiontostartatthebeginningofthestring



(PN|P)

SaystomatchthecharactersPNorP



[0-9][0-9]

Tellstheexpressiontomatchtwodigits,bothintherange0

through9



[A-Z]

SaystomatchasinglecharacterAthroughZ



[0-9]{3,4}

Saystomatchasingledigit0through9atleastthreetimes

andamaximumoffourtimes



[A-Z]{5,6}

SaystomatchasinglecharacterAthroughZatleastfive

timesandamaximumofsixtimes

Figure5-53showsthelayoutforaquerytofindpartnumbers

thatdon'tmatchourcriteria.



Figure5-53.CallingtheRegExpfunctionfroma

query



RunningthequeryinFigure5-53returnsthepartnumbersthat

donotmatchourgivencriteriasothatyoucanreviewthem

beforeplacingthemintoamasterdatabase.Althoughyoucan

dothiswithouttappingintothepowerofregularexpressions,it

requiresamuchmoreinvolvedsolution.



5.16.3.HackingtheHack

Asyoudiscoverthepowerofregularexpressions,youwillfind

themtobeveryrobustforallkindsoftextprocessing.Another

handytrickistousethemtoverifytextinputonaform.Todo

so,callthecustomRegExpfunctionfromtheBeforeUpdateeventof

thetextbox.Ifitreturnsfalse,settheCancelparametervariable

totrue,whichclearstheinputonthetextbox.

Youcanevenaddanadvancedfeaturetoyourapplication,

whichallowstheusertodosearchesbasedonherownregular

expressions!



SteveHuff



6.MultiuserIssues

Section6.1.Hacks5558

Hack55.TestforDuplication

Hack56.DistributeaSplitDatabasewithPredefinedTable

Links

Hack57.BuildaTime-OutFeature

Hack58.ImplementUniqueUsernames



6.1.Hacks5558

YoucandeployAccessdatabasesasstandaloneapplicationsas

wellasinsharedsystems.Althoughworkingwithashared

databaseprovidesmanybenefitsintermsofefficiency,issues

cancropupwithregardtousers'activitiesgettinginthewayof

eachother'sdata.Thischapterprovidesafewworkaroundsfor

integratingAccessinamultiuserenvironmentwhileensuring

datadoesn'tgettrampled."BuildaTime-OutFeature"[Hack

#57]catchesandcompletesidlerecordedits,therebyallowing

otherstomakechanges."TestforDuplication"[Hack#55]

showsawaytovalidatedatabeforeusersduplicateeach

other'sentries.Thechapteralsocoversadistributionmethod

[Hack#56]thatmakesiteasytogetasplitdatabasefrom

yourdevelopmentmachinetoyourclients,withthetablelinks

alreadymatchingthenetwork.



Hack55.TestforDuplication



Beforeyouinsertmultipleentriesintomastertablesina

busydata-entryenvironment,you'llneedacustom

validationprocesstoavoidduplicateddata.

Justbecauseadatabaseisdeployedontheserverdoesn't

meantheentireapplicationmustbeinthatservercopy.A

commonapproachistoputthedataintheserverdatabaseand

distributetheformstothelocalclientcomputers,insideanother

Accessfile.ThisisatypicalAccessversionofaclient/server

application.

BecausetheclientinstallationsareAccessdatabases,using

tablesintheclientdatabasesopensuppossibilities.Oneuseful

techniqueistohavenewdataentriesgointolocaltablesfirst,

andlatertobulk-insertthemintothemastertableortableson

theserver.

Theheartofthistechniqueisthatentryoperatorshavelocal

tablesthatmirrortheservertables.Theirformsareboundto

thelocaltablesandallentryisdonelocally.Attheendofthe

day,oratscheduledtimesthroughouttheday,aprocessruns

thattakesthedataoutofthelocaltablesandmovesittothe

servertables.

Hereiswheretheadvantagelies.Theinsertprocessgathers

theinputfromalltheentryoperators'clienttablesandtestsfor

duplicationbeforetheactualinsertintotheservertables.

Normally,suchaninterimvalidationwouldbeoverkillbecause

datausuallyisvalidateduponentry.However,thepointhere

isn'treallytovalidatedataintermsofcorrectcontent,but

rather,toseeifduplicaterecordswereenteredduringinput.



Thisiscertainlyapossibilityinabusycustomerservice,sales,

ortelemarketingoperation.Forexample,inanenvironment

wherephonecallscomein,itispossiblethatJaneplacesan

orderforsomethingand,anhourlater,herhusbandJoeplaces

anorderforthesameitem.Ifdifferentoperatorshandledthe

husbandandwife,noonewouldbethewiserthatthisisa

duplicateorder.Eventhetwocreatedrecordsmightnotbe

actualduplicatesbecausethefirstnameisdifferentineach

record.Butifacustom-designedvalidationprocessisused,

thesetworecordscanbeflaggedasduplicatesbecauseatleast

theaddressisthesameinbothrecords.

Youalsocantestfornearduplicationontheserver,sothisbegs

thequestion:whybotherwiththeseparatetable-entry

approach?Theanswerisperformance.Ifallentrygoesstraight

totheservertables,andthecustomduplicationprocessrunson

thelargertables,therecouldbesomeissueswithspeed.

Anotherissuetoconsiderishowfarbackintimetolookfor

duplicates.Withthelocalapproach,thetestcertainlyisdoneat

leastattheendoftheday,ifnotduringscheduledtimes

throughouttheday,allforthatday'sprocessing.Involvingolder

recordsintheservertablesisn'tnecessary.Anorderplaced

twiceinonedayisprobablyaduplicate.Anorderthat

resemblesoneplacedlastweekorlastmonthisprobablya

repeatorder.

AndreaMoss



Hack56.DistributeaSplitDatabasewith

PredefinedTableLinks



Ifyoufollowthisinterestingdistributiongameplan,

userswillnothavetolinktheirlocaldatabasefilestothe

datatablesonthesystem.

Thetechniqueknownasdatabasesplitting,whichinvolvesa

tables-onlyback-endAccessfileonanetworkshare,copiesof

front-endAccessfiles(withforms,reports,andsoon)oneach

user'sC:\drive,andtheuseoflinkedtables,hasbeenaround

forquitesometime.Thebenefitsofsuchclient/serverdatabase

configurationsarewidelyknownanddocumented.

However,itcanbeachallengetodealwithsplitdatabases

duringperiodsoffrequentupdates,especiallyduringthe

developmentphase.Forsomeusers,theirOfficeinstallation

doesn'tevenincludetheLinkedTableManager,sotheycanget

promptedfortheOfficeinstallationCDwhentheyattemptto

refreshandchangelinks.Otherusersmightsimplybe

uncomfortableorunfamiliarwithhowlinkedtableswork.

Frequentrelinking,especiallyforuserswhowereusedtojust

sharinganMDBfromonelocation,canbeproblematic.

Whenfrequentroundsofrevisionsarebeingsubmittedtoend

usersduringtheinitialprototypingstageofdevelopment,it

makessensetokeeptheprojectinonlyonefile.Butoncethe

datamodelissignedoff,it'stimetosplitthedatabase.Youcan

dothisintwoways:

Makeacopyofthedatabasesothatyouhavetwoidentical

copies.Inonecopy,deletethetables.Intheothercopy,



deleteeverythingbutthetables.

UsetheDatabaseSplitterutility(Tools Database

Utilities).ThisautomaticallycreatesanAccessfilewithjust

thetablesand,atthesametime,removesthetablesfrom

thedatabaserunningtheutility.

Thentheback-enddatabase(theonewiththetables)goesona

networkshare,whilethefront-enddatabaseisdistributedto

usersandisrunfromtheirPCs.Theproblemisthatthefrontenddatabasemustbelinkedtothetablesintheback-end

database.SimulatingtheselinksonyourdevelopmentPC

beforedistributingthefrontendisthepointhere.Ifyoucanset

thelinkssothattheyarethesameasthoseintheproduction

environment,userswillnothavetodealwithestablishingthe

linksthemselvesfromtheirPCs.

Inotherwords,youcandistributethefrontendprelinked.Allof

thisisbasedontheassumptionthatadrive-mappingstandard

isinplaceandthatalluserswillhaveanidenticalmappath.



6.3.1.CopyingtheNetworkDrivetoYour

DevelopmentMachine

TheSUBSTDOScommandisallyouneedtocopythenetwork

drivetoyourdevelopmentmachine.Onyourdevelopment

machine,youcanuseSUBSTtocreateamapthatmatchesthe

oneusersneed.

First,createadirectoryonyourcomputerthatmatchesthe

folderonthesharewheretheback-enddatabasewillgo.Ifthe

networkpathincludessubdirectories,createapaththat

matchesthatpathstructureonyourdevelopmentmachine.

ThesyntaxforusingSUBSTrequiresthenewdriveletterandthe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 54. Use Regular Expressions in Access Queries

Tải bản đầy đủ ngay(0 tr)

×