0

I have found statements that delete everything after a certain character. How do i delete everything after a word even though the length after that word may vary.

11000 PLACIDA RD BLDG 15 UNIT 1504
17200 ACAPULCO RD BLDG 1

I want to delete everything after BLDG

Siyual
  • 16,415
  • 8
  • 44
  • 58
ObiWanCannoli
  • 43
  • 1
  • 1
  • 8

2 Answers2

2

You can use CHARINDEX to find the position of a string inside another string:

CHARINDEX('BLDG', ColumnName)

Then use LEFT to only take everything up to that point:

SELECT LEFT(ColumnName, CHARINDEX('BLDG', ColumnName))
FROM Table

And finally, since you want to include the BLDG text, you need to add 3 to the position (i.e. length of the string-1):

SELECT LEFT(ColumnName, CHARINDEX('BLDG', ColumnName)+3)
FROM Table

If you want to also delete the BLDG word, then subtract 1 instead:

SELECT LEFT(ColumnName, CHARINDEX('BLDG', ColumnName)-1)
FROM Table
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

This worked for me.

CREATE TABLE #DeleteString ( AddressB4 VARCHAR(255) );

INSERT  INTO #DeleteString
        ( AddressB4 )
VALUES  ( '11000 PLACIDA RD BLDG 15 UNIT 1504'  -- AddressB4 - varchar(255)
          ),
        ( '17200 ACAPULCO RD BLDG 1'  -- AddressB4 - varchar(255)
          );
DECLARE @SearchStrng VARCHAR(255)= 'BLDG';
SELECT  REPLACE(AddressB4,
                SUBSTRING(AddressB4,
                          CHARINDEX(@SearchStrng, AddressB4)
                          + LEN(@SearchStrng), LEN(AddressB4)), '') AS FilteredAddress
FROM    #DeleteString;

Here are my results

Drishya1
  • 254
  • 2
  • 4