1. 程式人生 > >SQL字串擷取

SQL字串擷取

今天哥們問了我一個這樣的問題,用sql語句擷取“abcd1234<guid>abe</guid>” 這個裡面的abe經過測試終於搞定,現記錄如下

select SUBSTRING('abcd1234<guid>abe</guid>',
(select (PATINDEX('%<guid>%','abcd1234<guid>abe</guid>')+6) as firstindex),
(select ((select PATINDEX('%</guid>%','abcd1234<guid>abe</guid>'))-(select (PATINDEX('%<guid>%','abcd1234<guid>abe</guid>')+6))) as lastindex))

說下思路,

1,提取<guid>的索引使用select (PATINDEX('%<guid>%','abcd1234<guid>abe</guid>'),這時獲取的只是<的索引,所以要加6得到1的索引

2,提取中間字字元的長度,這裡重點說下,我們可以用</guid>中的<索引減去<guid>中>索引 ,也就是

(select (
(select PATINDEX('%</guid>%','abcd1234<guid>abe</guid>'))-(select (PATINDEX('%<guid>%','abcd1234<guid>abe</guid>')+6)

3,用substring進行提取,(字串,開始位置,提取長度)