Reputation: 357
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
Upvotes: 12
Views: 306
Reputation: 6437
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
Upvotes: 2
Reputation: 7338
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
Upvotes: 8
Reputation: 1269773
I'm inclined to use stuff()
for this purpose:
select replace(stuff(m, 1, patindex(m, '%[0-9]%'), ''), ']', '')
Upvotes: 3
Reputation: 5672
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
Upvotes: 3