0

I have a table CARM with fields (columns) ID and AREA_DESC.

In the AREA_DESC field, I have some values that show as follow:

AREA_DESC
--------------
Felisberto-001
Ana
Mark-02
Maria
--------------

What I would like to do, is to display these values in this way:

AREA_DESC
--------------
Felisberto
Ana
Mark
Maria
--------------

As you may notices, I would like to only display the string prior to the dash - only. In other words, I would like to drop the dash - and numbers after the dash -

This is the query I have tried so far:

SELECT ID, AREA_DESC ,SUBSTRING(AREA_DESC,0,CHARINDEX('-', AREA_DESC)) as area 
FROM CARM
acarlstein
  • 1,799
  • 2
  • 13
  • 21
  • ... and what's the problem? What you describe, is that the obtained or the desired result? – Dominique Apr 24 '19 at 13:28
  • Possible duplicate of [substring in sql server 2008](https://stackoverflow.com/questions/20878304/substring-in-sql-server-2008) – Zack Apr 24 '19 at 15:08

2 Answers2

1

The simplest method is to add a '-' for the charindex():

SELECT ID, AREA_DESC,
       LEFT(AREA_DESC, CHARINDEX('-', AREA_DESC + '-')) as area
FROM CARM;

Notice that this also uses LEFT() it saves an argument in the string operation.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can use left() instead with addition of '-' at the end of string:

select ID, AREA_DESC, left(AREA_DESC, charindex('-', AREA_DESC + '-'))
from CARM;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52