如何在SQL中拆分字符串并显示该值

时间:2015-10-09 13:05:59

标签: sql sql-server sql-server-2008

我有一个列(Col A),其值如下:

ThisValue=The Value;DateFrom=01/01/01;Regulated=No;

我想只选择The Value(来自Col A)并将其显示在子查询中。

到目前为止,我已尝试使用REPLACE,但很难让它在select语句中工作。

2 个答案:

答案 0 :(得分:0)

使用SUBSTRINGCHARINDEX

<强> QUERY

declare @str as varchar(50)

set @str = 'ThisValue=The Value;DateFrom=01/01/01;Regulated=No;'

select substring(@str,charindex('=',@str,1)+1,
       ((charindex(';',@str,1))-(charindex('=',@str,1))-1));

SQL Fiddle

答案 1 :(得分:0)

为了做到这一点,你需要一个分离器。我最喜欢的是Jeff Moden在这里找到的那​​个。 http://www.sqlservercentral.com/articles/Tally+Table/72993/

有些人不喜欢那个,因为它有varchar限制(8000)。我从来没有需要在那么长的时间内解析任何分隔的字符串,所以对我来说一直很好。

要深入了解具有多种不同选项的分割器,您可以查看本文。 http://sqlperformance.com/2012/07/t-sql-queries/split-strings

declare @Something varchar(100) = 'ThisValue=The Value;DateFrom=01/01/01;Regulated=No;'

select max(case when y.ItemNumber = 1 then y.Item end) as DataName
    , max(case when y.ItemNumber = 2 then y.Item end) as DataValue
from dbo.DelimitedSplit8K(@Something, ';') x
cross apply dbo.DelimitedSplit8K(x.Item, '=') y
where x.Item > '' --This eliminates the trailing semicolon
group by x.ItemNumber
order by x.ItemNumber