Home > Software design >  SQL query to return first word after -
SQL query to return first word after -

Time:08-31

I have a field where I need to pull the first word after "- " character example: Input= 853 - RACEWAY SALES. Output = RACEWAY

I am using:

SELECT 
   CASE 
     WHEN [Warehouse name] LIKE '853 - RACEWAY SALES' 
        THEN SUBSTRING(
                [Warehouse name], 
                CHARINDEX('-', [Warehouse name]), 
                CHARINDEX('', [Warehouse name]) - CHARINDEX('-', [Warehouse name])   Len('')
             ) 
   END AS A

This is throwing me an error.

CodePudding user response:

A possible answer is :

WITH T AS
(
SELECT '853 - RACEWAY SALES'  AS STRING
)
SELECT LEFT(RIGHT(STRING, LEN(STRING) - CHARINDEX('-', STRING) - 1), CHARINDEX(' ', RIGHT(STRING, LEN(STRING) - CHARINDEX('-', STRING) - 1)) - 1)
FROM T

CodePudding user response:

Please try this:

select PARSENAME(REPLACE( PARSENAME(REPLACE('853 - RACEWAY SALES', '-', '.'), 1) , ' ' ,'.'),2)
  • Related