Search code examples
sqlsql-servert-sqltrimcharacter-trimming

Trim "-" from data returned from SQL Server


I have a query that in SQL Server that returns data like this:

1234-A
2345-BB
3456-C
5678-CC
4567-AA              
6789-B
01234-A
26857-ZZ                         

This is what I need it display:

A
B
C
C
A
B
A
Z
  

I need to get the first letter behind the '-'. How do I get this to display?


Solution

  • Try this:

    DECLARE @MyTable TABLE (MyCol VARCHAR(255));
    INSERT @MyTable (MyCol)
    VALUES ('1234-A'),('2345-BB'),('3456-C'),('5678-CC'),
           ('4567-AA'),('6789-B'),('01234-A'),('26857-ZZ');
    
    SELECT SUBSTRING(MyCol, CHARINDEX('-', MyCol, 1) + 1, 1)
    FROM @MyTable;
    

    CHARINDEX finds where the '-' in the column value is.
    SUBSTRING starts at that index + 1 and returns, in this case, 1 character.