12
CREATE TABLE #tmpTbl (m VARCHAR(100))  
INSERT INTO #tmpTbl VALUES
 (',[Undergraduate1]')    
,(',[Undergraduate10]')   
,(',[Undergraduate11]')   
;
GO

select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
         SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m)) as b from #tmpTbl


drop table #tmpTbl

Hi given the above tmptable and select statement, the result will be as follow.

           a            |      b
-------------------------------------------------------
    ,[Undergraduate     |      1]
    ,[Undergraduate     |      10]
    ,[Undergraduate     |      11]

However i want it to be like this.

           a            |      b
-------------------------------------------------------
    ,[Undergraduate     |      1
    ,[Undergraduate     |      10
    ,[Undergraduate     |      11

How can i achieve that? i tried alot of combination with PATINDEX, LEFT, RIGHT, SUBSTRING,LEN. but cant get right of the ] in column B

sqluser
  • 5,502
  • 7
  • 36
  • 50
Devora
  • 357
  • 4
  • 14

4 Answers4

8

you can use replace to remove the ]. Dodgy, but it achieves what you want

select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
     REPLACE(SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m)),']','') as b from #tmpTbl

alternative: reverse the string, substring to remove 1st char, reverse back

select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
         REVERSE(SUBSTRING(REVERSE(SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m))),2,LEN(M))) as b from #tmpTbl
Nick Kavadias
  • 7,542
  • 2
  • 37
  • 46
3

You can use REPLACE to replace ] with ''

select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
         REPLACE(SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m)), ']', '') as b from #tmpTbl
sqluser
  • 5,502
  • 7
  • 36
  • 50
3

I'm inclined to use stuff() for this purpose:

select replace(stuff(m, 1, patindex(m, '%[0-9]%'), ''), ']', '')
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

Here is an alternative approach that will strip any text and just leave the numbers behind.

SELECT LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1) 
FROM (
    SELECT subsrt = SUBSTRING(m, pos, LEN(m))
    FROM (
        SELECT m, pos = PATINDEX('%[0-9]%', m)
        FROM #tmpTbl
    ) d
) t
Dave Barker
  • 6,303
  • 2
  • 24
  • 25