Dynamic SQL using CHARINDEX

Recently I was called upon to create a new field from an existing field.  The specifications called for the new field to be composed of any data between two dashes.  The dashes could be at any positional value and the data between the dashes was not a consistent length.  

The existing field contained data similar to:
  •  ABC-12345-AB1
  • AB-13456-123
  • 123-12347-X
  • ABC-123562-CB
  • 1-1234-1

To accomplish this task,  I used CHARINDEX and SUBSTRING

Below is the final statement:

DECLARE @find varchar(30)

SET @find = ‘A-1234-1’


NEW_FIELD = CAST(SUBSTRING(@find,(CHARINDEX(‘-‘,@find,1)+1),((CHARINDEX(‘-‘,@find,(CHARINDEX(‘-‘,@find,1)+1))-(CHARINDEX(‘-‘,@find,1)))-1)) as VARCHAR(30))


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: