How to extract substring in SQL Server
I have a field with something like okbogkbogkbokgbokgobkgobkofkgbokfgbo&name=fokdofkd&okfaos
I'd like to extract the name = value
from the data.
开发者_运维百科How can I do that using SQL Server 2008 in efficient way? thank you
Try this
;
With MyTable as
(
SELECT 'okbogkbogkbokgbokgobkgobkofkgbokfgbo&name=fokdofkd&okfaos' FullString
UNION
SELECT 'fkgbokfgbo&name=fokdofkd&okfaos' FullString
UNION
SELECT 'okbogkbogkbokgbok' FullString
),
PatternIndex as
(
Select
FullString + '&' FullString,
CharIndex ('&name=', FullString) + 1 LocationOfEqualSign,
CharIndex ('&', FullString, CharIndex ('&name=', FullString)+1) as NextBreak
from MyTable
),
SplitNameValue AS
(
Select
FullString,
CASE
WHEN NextBreak <> 0 THEN
SubString (FullString, LocationOfEqualSign, NextBreak-LocationOfEqualSign)
ELSE '' END
as NameValuePair
From PatternIndex
)
SELECT *
FROM SplitNameValue
Returns
FullString NameValuePair
--------------------------------------------------------- ---------------------------------------------------------
fkgbokfgbo&name=fokdofkd&okfaos name=fokdofkd
okbogkbogkbokgbok
okbogkbogkbokgbokgobkgobkofkgbokfgbo&name=fokdofkd&okfaos name=fokdofkd
(3 row(s) affected)
SELECT 'name=' + SUBSTRING(field, CHARINDEX('name=', field), CHARINDEX('&', SUBSTRING(field, CHARINDEX('name=' ,field))))
Something along the lines of...
select substring(ColumnName, charindex('name=',ColumnName,1),len(ColumnName))
This will work I think:
Declare @String varchar(100)
Set @String = 'okbogkbogkbokgbokgobkgobkofkgbokfgbo&name=fokdofkd&okfaos'
Select SubString(@String,CharIndex('name=',@String),len(@String))
This produces:
'name=fokdofkd&okfaos'
精彩评论