sql server中的另一个子串问题

时间:2010-10-02 11:42:48

标签: sql sql-server

以下是我数据库列中的数据:

“ABC; 123; TGH”
“DEF; 123456; TFG”

如何从上述数据中获取文字“123”“1234546”

3 个答案:

答案 0 :(得分:3)

或者使用ParseName技巧,因为要分割的项目少于4个。

;with T as
(
SELECT 'ABC;123; TGH' ColName
UNION ALL
SELECT 'DEF;123456; TFG'
)
SELECT
 PARSENAME(REPLACE(ColName,';','.'),2) as [result]
FROM T

答案 1 :(得分:2)

with t as
(
SELECT 'ABC;123; TGH' C UNION ALL
SELECT 'DEF;123456; TFG'
)
SELECT
 SUBSTRING(C,CHARINDEX(';', C)+1,CHARINDEX(';', C,CHARINDEX(';', C)+1)-CHARINDEX(';', C)-1)
FROM T

答案 2 :(得分:0)

这几乎就像微软在SQL Server中努力做到这一点一样。这是一种方法,其中每个子查询剥离一列并将余数交给外部查询:

select  First
,       substring(Remainder, 0, PATINDEX('%;%', Remainder)) as Second
,       right(Remainder, len(Remainder) - PATINDEX('%;%', Remainder)) Remainder
from    (
        select  substring(col1, 0, PATINDEX('%;%', col1)) as First
        ,       right(col1, len(col1) - PATINDEX('%;%', col1)) as Remainder
        from    (
                select  'ABC;123; TGH' as col1
                union all
                select  'DEF;123456; TFG'
                ) sub1
        ) sub2