Pull values to the Left of a dash

Evan Stroum 21 Reputation points
2021-05-25T02:32:50.59+00:00

I am trying to pull from a field called "Location" that includes a number of varying lengths after a dash. I only want to pull the value of the field before the dash. My expression below worked with the LTRIM to pull values after the dash but is not working for values before. What is wrong with the below statement?

COALESCE(RTRIM(SUBSTRING(Location,CHARINDEX('-',Location,1)+1

LEN(Location)-CHARINDEX('-',Location,1))),Location)

SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
3,061 questions
Microsoft 365 and Office Excel For business Windows
Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-05-25T03:33:03.35+00:00
    SELECT COALESCE(SUBSTRING(Location,0,  
    CHARINDEX('-',Location)),Location)  
    FROM #t  
      
    

    Output:
    99276-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-05-25T02:57:56.577+00:00

    Hi @Evan Stroum

    Please refer to:

    CREATE TABLE #t(Location char(55))  
    INSERT INTO #t VALUES('Newport Plant - 10601 - L48 Production'),  
                         ('Sandpoint - 13501 - AK Shore QA')  
      
    SELECT LEFT(Location,CHARINDEX('-',Location)-1)  
    FROM #t  
    

    Output:
    99274-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Evan Stroum 21 Reputation points
    2021-05-25T03:00:52.977+00:00

    I should have clarified that I have thousands of fields I need the values for to the left of the dash.


  3. Evan Stroum 21 Reputation points
    2021-05-25T03:03:29.46+00:00

    I am also relegated to what functions Dayforce uses for SQL. 99275-image.png


  4. Evan Stroum 21 Reputation points
    2021-05-25T03:23:59.587+00:00

    It's a custom field editor for SQL within Dayforce. 99352-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.