2015-03-02 146 views
-1

有人可以建议一种方式,我可以从SQL Server表中的(&0459&/&0460&)*100这样的字符串中提取04590460在SQL Server字符串中提取字符串之间的字符串

我应该能够拉出两个字符串夹在两个字符之间。

在此先感谢。

+0

&&也是一个三明治字符串。你会如何避免这种情况? – 2015-03-02 13:25:24

+0

一旦你决定使用什么规则,你可以使用PatIndex和SubString。 – 2015-03-02 15:21:41

回答

1

如果你一定总是有两对&符号的,你可以提取两个字符串这样

declare @s varchar(max) = '(&0459&/&0460&)*100' 

declare @first int = charindex('&', @s) 
declare @second int = charindex('&', @s, @first+1) 
declare @third int = charindex('&', @s, @second+1) 
declare @fourth int = charindex('&', @s, @third+1) 

select substring(@s, @first+1, @[email protected]) 
select substring(@s, @third+1, @[email protected]) 
1

该解决方案将虎视眈眈“&”之间

;WITH CTE AS 
(
    SELECT t.c.value('.', 'VARCHAR(2000)') v, 
    rn = row_number() over (order by (select 1))-1 
    FROM (
     SELECT x = CAST('<t>' + 
       REPLACE('(&0459&/&0460&)*100', '&', '</t><t>') + '</t>' AS XML) 
    ) a 
    CROSS APPLY x.nodes('/t') t(c) 
) 
SELECT v FROM CTE 
WHERE rn in (1,3) 

结果第1和3TH值:

0459 
0460 
+0

嗨,感谢您的建议,我也在尝试您的答案,但它有点复杂。 – VivekDev 2015-03-03 04:55:50