当前位置: 代码迷 >> Sql Server >> 江湖救急怎么获取成对字符中间的字符串
  详细解决方案

江湖救急怎么获取成对字符中间的字符串

热度:9   发布时间:2016-04-24 10:02:11.0
江湖救急!如何获取成对字符中间的字符串

需要获取到【】中间的内容 如果一个值中有多个【】就新建一列显示

【A】
【B】【C】
【D】【E】【F】
最终要显示成
A
B
C
D
E
F
------解决方案--------------------
自己去搜索下SQL SERVER的拆分函数吧。你这个只能用拆分函数来做了。
------解决方案--------------------
1. 先用LIKE'%【%】%'排除掉不含【】的行。然后用patindex 分别标记 ‘【’,‘】’位置 SUBSTRING 截出来。但是这个只能截出到第一个。后面的多个[]显示成多行 没想到
------解决方案--------------------
感觉可以用变量循环做。进行截出。切出来第一个[]之后。在对之后的字符串进行patindex 操作。一直循环 知道patindex返回0
------解决方案--------------------
试试用递归查询,直接执行看看是不是这种效果

/* 假设你的表是YourTable */
with YourTable (proprosal) as
(
select '【A】asdfasdf' union all
select '  【B】hfds【C】' union all
select 'asdf【D】hhhh【E】jghjghjggjghjgjhgfjhfgjfghjfgjh【F】' union all
select 'ldjfglxcnldjfgldsjflgjdsl' union all
select '【G】【H】'
)

/* 使用递归来计算,实际运行时更换掉这里的YourTable为真实的表名 */
, T1 as
(
select proprosal
     , string = convert(varchar(max), substring(proprosal, charindex('【',proprosal, 1), charindex('】',proprosal, 1) -  charindex('【',proprosal, 1) + 1) )
     , startIndex = charindex('【',proprosal, 1)
     , endIndex = charindex('】',proprosal, 1)
from YourTable
where charindex('【',proprosal, 1) > 0
union all
select proprosal
     , string = convert(varchar(max), substring(proprosal, charindex('【',proprosal, endIndex+1), charindex('】',proprosal, endIndex+1) -  charindex('【',proprosal, endIndex+1) + 1) )
     , startIndex = charindex('【',proprosal, endIndex+1)
     , endIndex = charindex('】',proprosal, endIndex+1)
from T1
where charindex('【',proprosal, endIndex+1) > 0
)

select *
from T1

------解决方案--------------------
可以考虑分析函数,提供一个oracle的写法,参考
select REGEXP_SUBSTR('【A】【B】【C】【D】【E】【F】','【[^【+]】',1,level)
from dual
connect by level<REGEXP_COUNT('【A】【B】【C】【D】【E】【F】','【')+1

------解决方案--------------------
字符切割提取吧,对于多行,写个游标