UFN_ADDRESS_GETADDRESSLINE

Returns the specified line of an address block.

Return

Return Type
nvarchar(150)

Parameters

Parameter Parameter Type Mode Description
@ADDRESSLINENUMBER int IN
@ADDRESSBLOCK nvarchar(150) IN

Definition

Copy


CREATE function dbo.[UFN_ADDRESS_GETADDRESSLINE]
(
  @ADDRESSLINENUMBER int,
  @ADDRESSBLOCK nvarchar(150)
)
returns nvarchar(150)
with execute as caller
as
begin
  declare @LINE int = 1;
  declare @POS int = 0;
  declare @NEXTPOS int = 0;

  --Replace any combination of char(13) and/or char(10) in @ADDRESSBLOCK with only char(10) characters so

  --that we can easily strip out individual line numbers down below.  If two of the same char(13) or char(10)

  --are used side-by-side, then treat it as a blank line by separating them with a space.

  set @ADDRESSBLOCK = replace(
                        replace(
                          replace(
                            replace(
                              @ADDRESSBLOCK,
                              char(13) + char(13),
                              char(13) + ' ' + char(13)
                            ),
                            char(10) + char(10),
                            char(10) + ' ' + char(10)
                          ), 
                          char(13),
                          char(10)
                        ),
                        char(10) + char(10),
                        char(10)
                      );

  while (@LINE <= @ADDRESSLINENUMBER)
  begin
    set @POS = @NEXTPOS + 1;
    set @NEXTPOS = charindex(char(10), @ADDRESSBLOCK, @POS);

    if @NEXTPOS = 0
      begin
        if @LINE < @ADDRESSLINENUMBER
          --Line number is greater than lines in the address, so return empty string...

          return '';
        else
          --Return the last line in the address...

          return ltrim(rtrim(substring(@ADDRESSBLOCK, @POS, 150)));
      end

    set @LINE += 1;
  end

  --Return the address line specified...

  return ltrim(rtrim(substring(@ADDRESSBLOCK, @POS, @NEXTPOS - @POS)));
end