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
嗨,鉴于上面的 tmptable 和 select 语句,结果将如下所示。
a | b
-------------------------------------------------------
,[Undergraduate | 1]
,[Undergraduate | 10]
,[Undergraduate | 11]
但是我希望它是这样的。
a | b
-------------------------------------------------------
,[Undergraduate | 1
,[Undergraduate | 10
,[Undergraduate | 11
我怎样才能做到这一点? 我尝试了很多与 PATINDEX、LEFT、RIGHT、SUBSTRING、LEN 的组合。 但无法获得 B 列中 ] 的右侧
您可以使用
替换来删除]。狡猾,但它实现了你想要的
select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
REPLACE(SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m)),']','') as b from #tmpTbl
替代方法:反转字符串,子字符串删除第一个字符,反转回来
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
您可以使用
REPLACE
将]
替换为''
select LEFT(m, PATINDEX('%[0-9]%', m)-1) as a,
REPLACE(SUBSTRING(m, PATINDEX('%[0-9]%', m), LEN(m)), ']', '') as b from #tmpTbl
我倾向于为此目的使用stuff()
:
select replace(stuff(m, 1, patindex(m, '%[0-9]%'), ''), ']', '')
这是一种替代方法,它将剥离任何文本并留下数字。
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