0

I want the first letters of sku from left up to the second -. But in output I don't want that second - to show up.

My input table is

Input table

Query:

SELECT SUBSTRING(SKU, charindex('-',SKU),  len(SKU) - charindex('-',SKU)) 
FROM tblname

My excepted output is

desired o/p

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
sachit
  • 13
  • 5
  • What "dialect" of SQL is this for? MS SqlServer? Oracle? Postgres? .... string manipulation could require some product specific function or trick... – p.marino Jul 14 '16 at 09:37
  • I have no access to a SQL Server instance so I cannot propose a complete solution - only advice. You can either write a _function_ to do this for you (possibly more efficient than trying to do all as part of a select) or - as someone else suggested, use _reverse_ to transform the problem in "I need to find the last instance of '-' in my string to isolate the SKU" to the far more tractable "I need to find the first instance of '-'" see: http://stackoverflow.com/questions/1024978/find-index-of-last-occurrence-of-a-sub-string-using-t-sql – p.marino Jul 14 '16 at 09:53

2 Answers2

0

Try this...

    SELECT 
    SUBSTRING(SKU,0, CHARINDEX('-',SKU,(charindex('-',SKU)+1))+1) from tablename

Hopes this helps...

Sankar
  • 6,182
  • 2
  • 23
  • 43
  • you should post the result so that we can better understand what the problem is. – p.marino Jul 14 '16 at 09:51
  • @sachit Updated... is that you want? – Sankar Jul 14 '16 at 09:58
  • 2
    @sachit - I saw that you posted your _expected_ output, and this is good and important to better define your problem. But I was referring to the output produced by Sankar Raj's answer. Saying only "it is not working" will not help him refining his answer. – p.marino Jul 14 '16 at 11:18
0
SELECT  REVERSE(RIGHT(REVERSE('Hello-World-1'), 
                      LEN('Hello-World-1') - CHARINDEX('-',
                                                       REVERSE('Hello-World-1'))))

If you want to include the dash...

SELECT  REVERSE(RIGHT(REVERSE('Hello-World-1'), 1 + 
                      LEN('Hello-World-1') - CHARINDEX('-',
                                                       REVERSE('Hello-World-1'))))
Jesse Petronio
  • 643
  • 4
  • 9