05 — Functions (281)

Business Logic Functions Reference

All 281 scalar and table-valued functions across 11 categories. Functions exist in both Functions/ and UserDefinedFunctions/ directories (duplicates). TIP and TIPMIS prefixed variants are system-specific copies for the TIP/MIS data pipeline.

281
Total Functions
11
Categories
200+
Uses of fnLRDateToRealDate
01 Date Conversion Functions

Handle Lloyd's Register's proprietary NVARCHAR date formats. All ABSD_ dates are stored as NVARCHAR (not SQL date types).

fnLRDateToRealDate(@LRDATE varchar 8) → DATETIME Core — used 200+ times

Core LR date converter. Converts LR 8-digit or 6-digit format to SQL DATETIME.

  • Month '00' → treated as January (01); Month '99' → treated as December (12)
  • Day '00' → treated as 1st of month; Day '99' → last day of month
  • Validates day values for 30-day months (April, June, September, November)
  • Returns NULL for year '0000' or '9999'
fnLRDateToRealDate2022(@LRDATE varchar 8) → DATE Enhanced — post-2022 standard

Enhanced version with proper leap year handling. Detects invalid days >31 and rolls to previous month. Handles February 28/29 correctly. Returns DATE type (not DATETIME). Use for post-2022 data quality standards.

FunctionReturnsPurpose
fnLRDateToRealDateDATETIMECore LR date converter (most widely used)
fnLRDateToRealDate2DATETIMEIdentical with minor implementation diff (assigns to local var first)
fnLRDateToRealDate2022DATEEnhanced with leap year handling — post-2022 standard
fnRealDateToLRDatevarchar(8)Reverse: SQL DATE → LR YYYYMMDD format
fnLRDateToSeawebDatevarchar(24)Seaweb display format: YYYY-MM-DD, optional HTML NOBR wrap
fnAPSLRDateToAltDatevarchar(24)APS compatibility: replaces 00/99 month with 01
fnAPSAltDateQualifiervarchar(8)Returns 'A'=Approximate or 'B'=Bad for date quality marking
fnLRDateToBackfillDueDateDATETIMEBackfill deadline: new vessels (P/O/U/F/E status) get year-end deadline
fnDateIsInvalidbitValidates DDMMYY format (1=invalid, 0=valid)
fnToDateFromDDMMYYDATETIMEDD/MM/YY → DATETIME, NULL on failure (TRY/CATCH)
02 Point-in-Time Ownership Queries

Answer "who owned/managed vessel X on date Y?" by querying history tables.

fnGetRegOwnerAtDate(@LRNO char 7, @DATEIN nvarchar 8) → varchar 7

Returns registered owner code effective at @DATEIN:

SELECT TOP 1 H01_OWNER_CODE FROM ABSD_HIOW WHERE LRNO = @LRNO AND H01_EFD < @DATEIN ORDER BY H01_EFD DESC

Returns owner code from most recent record before query date. Used in casualty views to identify ownership at time of incident.

fnOwnerhierarchy(@LRNO varchar 7) → TABLE (OWCODE varchar 7) Table-valued

Returns complete ownership tree. Queries ABSD_SHIP_SEARCH for OWNERCODE, GBOCODE, TECHMANCODE, SHIPMANAGERCODE, DOCCODE, OPERATORCODE, BBC_CODE. Recursively traverses ABSD_OWXR for "BO" (beneficial owner) relationships — follows chain 2 levels deep.

FunctionSource TableDescription
fnGetRegOwnerAtDateABSD_HIOWRegistered owner at specified date
fnGetOperatorAtDateABSD_HIOPCommercial operator at specified date
fnGetShipmanagerAtDateABSD_HISMShip manager at specified date
fnGetGROUPOWNERAtDateABSD_HIGBOGroup/beneficial owner at specified date
fnGetDOCAtDateABSD_OVDOCDOC company at specified date (converts EffectiveDate to YYYYMMDD)
fnGetPreviousRegOwnerABSD_HIOWMost recent historical owner (immediately before current)
fnGetPreviousOperatorABSD_HIOPPrevious operator
fnGetPreviousShipManagerABSD_HISMPrevious ship manager
fnGetPreviousTechManagerABSD_TECH_MANPrevious technical manager
fnGetPreviousVesselNameABSD_OVNAImmediately previous vessel name (SEQNO <> '00')
fnCurrStatatDateABSD_HISTVessel status code at specific date
fnCurrStatatDateMasterABSD_HISTAdvanced: groups statuses, validates no intervening changes
fnOwnerhierarchyMultipleTable-valued: full ownership tree (OWNERCODE, GBOCODE, TECHMANCODE, etc.)
03 String Normalization Functions
FunctionDescriptionUse Case
fnTidyShipnameRemoves punctuation (.?'), collapses spaces, strips exceptions from shipnameexceptions table (cursor-based)Ship name pre-processing before matching
fnStripNameAggressive: Removes !;:[]+ {} & . , ? / _ - () '" and all spaces. Replaces "LTD"→"Limited"Maximum-aggressiveness matching
fnStripJunkModerate: Replaces special chars with spaces (not removal). Removes & entirely.General text cleanup preserving word boundaries
fnProperNameConversionIntelligent title-casing: Uppercase first letter per word (boundaries: space . - : ( / & ,). Special handling for Yacht, Ice, Class, Baltic, Bermuda, Arabian. Uses FPLNAMEEXCEPTIONS table.Publication-ready company name display
fnProperNameConversion_ShipnameShip-name title-casing + Roman numerals (II,III,IV,VI,VII,VIII,IX,XI,XX) + particles (of, de, del, du, d'U, L'A, L'E, d'I, 'B')Publication-ready vessel name display
fnReplaceSpecialCharactersCharacter set normalization via tblTranslateSpecialCharacters lookup. Preserves ASCII 32-126.Non-ASCII character substitution
fnStripSpanishCharsRemoves Spanish/French diacritics: á é í ñ ó ú ü à Ô and uppercase variants. Also « » ¿ ¡Latin-script name normalization
fnStripBVXMLJunkBureau Veritas XML payload cleaning: ü→u, õ→a, ö→o, etc. Removes &BV data feed import
fnCBTDStripCharsCBTD format: uppercase, removes spaces/periods/commas/parenthesesCBTD format normalization
fn_ComplimentaryTextTidyStripltrim/rtrim, collapse multiple spaces, replace ? with -General text cleanup
fnEndCommaStripRemoves trailing space or commaAddress/text cleanup
fnSBRNormaliseTable-valued: SBR normalization. Returns 50+ columns of vessel attributes from TblSBRPages (3 ships per page)Shipbuilder Registry data processing
04 Fuzzy Matching Functions
LevenshteinEditDistance(@s, @t nvarchar 4000, @max int) → INT

Core Levenshtein edit distance algorithm. Returns minimum edit operations (insert/delete/substitute) to transform @s into @t. Optimized with prefix/suffix trimming. Returns NULL if distance exceeds @max. The base algorithm for all name matching in the system.

HowSimilar(@s1, @s2 varchar 4000) → INT (0-100)

Company name similarity score. Preprocessing steps:

  1. Removes periods from both strings
  2. Removes common suffixes: SA, Ltd, co, srl, llc, ltda, bv, sa, gmbh, spa, inc, oy
  3. Removes " co " and " ltd " substrings
  4. Removes all spaces and "Company" word
  5. Returns (edit_distance / s1_length) * 100 — lower = more similar
FunctionDescription
LevenshteinEditDistanceCore Levenshtein algorithm. Base for all matching. @max parameter stops early if distance exceeds threshold.
edit_distanceAlternative core implementation using binary vector encoding. Nested loop iteration.
HowSimilarPreprocessed similarity score (0-100). Strips company suffixes before computing distance.
HowSimilarCleanDirect edit_distance percentage without preprocessing.
fnCompanyNameFuzzyFuzzy normalization: limited→ltd, company→co, incorporated→inc. Removes Scandinavian chars (Ø→o, Ö→o, Å→a).
AA_fn_phon_nysiisNYSIIS phonetic algorithm (8-char code). Calls xp_phon_nysiis extended stored procedure.
AA_fnUSCGFuzzyUSCG-compliant normalization using tblUSCGRefFuzzyRules* tables. Rule types: Company, Address, ShipType, Country, Name, General.
fnSBRPOSBuilderMatchGeographic builder selection: matches shipbuilder country against POS code. Priority: builder1 → builder2 → builder3.
fnTIPedit_distance / fnTIPMISedit_distanceTIP and TIP/MIS pipeline variants of edit distance. Identical algorithms.
05 Address Handling Functions
fnCoFullAddress(@OwCode varchar 7) → varchar 512

Complete company address builder. Queries ABSD_OWIN and ABSD_OWAD1 for multi-source address data. Format: Care-of company → Building → PO Box → Street → Postcode → Town → Country. Decodes town/country from ABSD_CBTO* and EDM.dbo.T_REF_COUNTRY. Returns pipe-delimited result (|| separator).

FunctionDescription
fnCoFullAddressComplete address builder. Queries ABSD_OWIN + ABSD_OWAD1. || separated.
fnFullBestAddressSingle "best" address from EDM.DBO.T_ENT_OWIN with LEFT JOINs to ABSD_CBTO1/2 and T_REF_COUNTRY. Prefers EDM over legacy.
fnCoMatchAddressAddress with CR/LF line breaks. Building, POB, Street, Postcode, Town, Country. Removes trailing commas.
fnCoMatchLineAddressWord-wrapped address with max-length enforcement. Calls all abbreviation functions. @Lineout to return specific line. | delimiter.
fnCoMatchAbbreviateAddressAddStreet→St, Road→Rd, Avenue→Av, Boulevard→Bvd, Place→Pl, Building→Bldg, Centre→Ctr, House→Ho, Square→Sq, Tower→Twr
fnCoMatchAbbreviateAddressBuildingFloor→Fl, Room→Rm, Centre→Ctr, House→Ho, Square→Sq, Tower→Twr; Spanish Apartado→apdo
fnCoMatchAbbreviateAddressCountryUnited States of America→USA; Democratic Republic of Congo→Dem Republic of Congo; special territories
fnCoMatchAbbreviateAddressTownProvince→Prov, Prefecture→Pref
fnCoMatchAbbreviateAddressPOBBoite Postale→BP, Caixa Postal→CP, Casella Postale→CP, P O Box→PO Box, Apartado→Apdo
fnAddressComm1Tel, Fax, Telex from vwRSGAddresscomm1. Format: ", Tel: XXX, Fax: XXX, Telex: XXX"
fnAddressComm2Email (type='E') and Web (type='F') from vwRSGAddressComm2.
06 Narrative Generation Functions

Build human-readable technical specification text from structured vessel data. Output is formatted prose suitable for publication.

fnAPSNarrativePrimeMoverGrouped(@LRNO, @High, @PrimeMoverGrouped) → varchar 7000 Most complex

Generates engine specification narrative. Engine types: 01=Diesel, 02=Steam turbine, 03=Turboelectric, 04=Steam reciprocating. Outputs: Design, Builder, Model (appends 'Tier 3' suffix where applicable), Cylinder arrangement, Bore × Stroke, MCR in kW and hp, RPM. Special handling for re-engined vessels and new engines with dates. Table-valued input allows pre-grouped engine data.

FunctionContentSource Tables
fnAPSNarrativePrimeMoverGroupedEngine specification narrative: type, builder, model, Tier 3, bore×stroke, MCR, RPMABSD_MAEM1/2/3, ABSD_HIGE
fnAPSNarrativeCapacitiesCapacity summary: passengers, crew, grain, bale, insulated, liquid, liquid gas, oil, ore, hopper, asphalt, ballast, TEUABSD_FUGE, ABSD_TANKER, ABSD_FURO1, ABSD_FUUN1/2
fnAPSNarrativeTankTank inventory: type, position, material, cargo segregations, heating coil materialvwd09_* tables, ABSD_FUST1, ABSD_TANKER
fnAPSNarrativeTankCoatingsTank coating specifications from ABSD_TANKER coating flagsABSD_TANKER
fnAPSNarrativeAuxEnginesGroupedAuxiliary engine specificationsABSD_HIGE
fnAPSNarrativeBoilersBoiler specificationsABSD_MABO
fnAPSNarrativeBunkersBunker fuel capacity narrativeABSD_FUUN1/2
fnAPSNarrativeConstructionHull and construction material/methodABSD_STSE, design tables
fnAPSNarrativeGearCargo gear (cranes, derricks) narrativeABSD_FULI1/2/3
fnAPSNarrativeHatchHatch configuration specificationsABSD_FUHA1/2
fnAPSNarrativeRampRo-Ro ramp specificationsABSD_FURO1/2
fnNarrativeTankerLegacy tanker specification narrativeABSD_TANKER
fnNarrativeSpecialistSpecialist vessel characteristics (DP, helipad, crane capacity)Multiple FUSF tables
07 Classification Functions
FunctionDescription
fnCLASSLISTComma-separated list of current classifications with status tags: (disc)=discontinued, (susp)=suspended, (cont)=continuous, (toc)=transfer of class. Queries ABSD_FOR_CLASS and ABSD_HILC.
fnCLASSLISTCURRENTOnly verified current classifications
fnCLASSIDLISTClassification identifier codes (not decoded names)
fnGetIMOClassIMO-assigned class code
fnClassPrimary/lead classification society code
fnGetClass1 / fnGetClass2First and second classification codes respectively
fnCBSTShiptypeCBS ship type lookup from CBST
fnSBRRegBookShiptypeShipbuilder Registry book ship type
08 Geographic / Coordinate Functions
fnConvertDegreesMinsToDecimal(@direction, @degrees, @minutes, @seconds) → decimal(18,15)

DMS to decimal degrees conversion. Formula: degrees + (minutes×60 + seconds) / 3600. Returns positive for N/E, negative for S/W. Returns 181 or 91 for invalid input (sentinel values). Used in port coordinate processing within CBPPROOT trigger.

fnMarsdenGrid(@LATDEG, @LATIND, @LONGDEG, @LONGIND) → VARCHAR 3

Marine meteorological Marsden grid calculation. Valid ranges: 70°N max, 60°S max, 179° longitude max. Quadrant base numbers: NW=1, NE=36, SW=300, SE=335. Divides by 10 and rounds down for 10°×10° grid cells. Formula: WSNUM + (LATDEG × 36) ± LONGDEG. Returns zero-padded 3-digit grid code.

FunctionDescription
fnConvertDegreesMinsToDecimalDMS → decimal degrees. Sentinel: 181 (long invalid) or 91 (lat invalid).
fnMarsdenGridMarsden grid code from lat/long. Used in port record CBPD.MARSDEN field.
fnDistanceCalcGreat-circle distance between two coordinate pairs (Haversine formula)
fnSISZoneCalculates Statistical Inventory of the Sea (SIS) zone from port coordinates
09 Validation Functions (Callsign, MMSI, etc.)
FunctionReturnsDescription
fnCallsignCheck(@Callsign, @Flag)bit (1=valid, 0=invalid)Validates callsign against flag country call sign prefix ranges in EDM.DBO.T_REF_COUNTRY_CALL_SIGN_RANGES. For SZI/FIJ/EGY/SUD flags: checks first 3 chars; all others: first 2 chars.
fnMMSICheck(@MMSI)bitValidates MMSI format (9 digits, first 3 = MID country code). Checks MID against valid Maritime Identification Digits table.
valStandard9Non99bitDate format validation: not '99' month sentinel, not '00' year. Used in CAGE1 trigger for STD/ENDD validation.
fnIsValidLRNO(@LRNO)bitValidates 7-character LR number format: digits only, not null.
fnOWCODEValid(@OWCODE)bitValidates 7-character owner code format.
10 Company / Owner Functions
FunctionDescription
fnGetCompanyShortName(@OWCODE)Returns SHNAME from ABSD_OWGE / EDM for the given owner code
fnGetCompanyCountry(@OWCODE)Returns NATY1 (primary nationality) for the company
fnGetCompanyISOCountry(@OWCODE)Returns ISO2 country code via CBCY join
fnOWGEGroupType(@OWCODE)Returns GROUP_OWGE value (A=Group, M=Management, B=Both)
fnGetOwnerShipCount(@OWCODE)Current fleet count from ABSD_OWST.IRP_OWNED
fnGetBeneficialOwner(@OWCODE)Traverses ABSD_OWXR for BO relationship — same logic as HIOW trigger dual certification path
11 Annotation / Audit Functions
FunctionDescription
fnGetEnglishFieldName(@TableName, @ColName)Translates coded column name (e.g., "B01_CALLSIGN") to human-readable label (e.g., "Call Sign"). Used by spAnnotateChange when writing tblChanges.
fnAnnotationSource(@SRCE)Decodes 9-char source system code to readable description
fnAnnotationLastChange(@LRNO)Returns formatted last-change timestamp string from J06_LNCHDATE + J06_LNCHTIME
fnGetFieldEnglishNameForExport(@table, @col)Export-version of English field name lookup with additional metadata
Key Functions Quick Reference
FunctionCategoryReturnsNotes
fnLRDateToRealDateDateDATETIMEUsed 200+ times. Core date converter.
fnLRDateToRealDate2022DateDATEEnhanced with leap years. New standard.
fnGetRegOwnerAtDateOwnershipvarchar(7)Registered owner on specific date.
fnOwnerhierarchyOwnershipTABLEComplete ownership tree per vessel.
LevenshteinEditDistanceFuzzyINTCore edit distance algorithm.
HowSimilarFuzzyINT (0-100)Company name similarity with preprocessing.
fnCoFullAddressAddressvarchar(512)Full address with EDM/ABSD source.
fnAPSNarrativePrimeMoverGroupedNarrativevarchar(7000)Engine specification narrative.
fnCallsignCheckValidationbitCalled by OVGE trigger for callsign validation.
fnMarsdenGridGeographicVARCHAR(3)Called by CBPPROOT trigger.
fnConvertDegreesMinsToDecimalGeographicdecimal(18,15)DMS → decimal. Called by CBPPROOT trigger.
fnProperNameConversionStringvarchar(1000)Title-case for company name publication.
fnCLASSLISTClassificationvarchar(70)Current classifications with status tags.
fnGetEnglishFieldNameAnnotationvarcharColumn code → readable label for audit log.
← Trigger Rules  ·  Documentation Hub  ·  Next: Procedures & Views →