sql字符串截取问题
字段名称:A字段A的值如下几种格式:DN350-DDDN150-1.0-DFDN350-1.0-DF-BDN350PN1.0DN100M20*170DN300-暂无区别想...
字段名称:A
字段A的值如下几种格式:
DN350-DD
DN150-1.0-DF
DN350-1.0-DF-B
DN350 PN1.0
DN100
M20*170
DN300-暂无区别
想要截取字段A横杠或者空格前面的字符串,如果没有横杠或者空格,就取字段A的值,请教下,要怎么写sql
是取第一个横杠和第一个空格之前的字符串 展开
字段A的值如下几种格式:
DN350-DD
DN150-1.0-DF
DN350-1.0-DF-B
DN350 PN1.0
DN100
M20*170
DN300-暂无区别
想要截取字段A横杠或者空格前面的字符串,如果没有横杠或者空格,就取字段A的值,请教下,要怎么写sql
是取第一个横杠和第一个空格之前的字符串 展开
2个回答
展开全部
取倒数第二个逗号和倒数第一个逗号的值是么?方法很多,举个例子:
with tmp(col) as(
select '123,3,3,56,77,233'
union all
select ',1,4,5,21,43,'
)
select reverse(substring(col,
CHARINDEX(',', col) + 1,
CHARINDEX(',', col, CHARINDEX(',', col) + 1) -
CHARINDEX(',', col) - 1))
from (select reverse(col) as col from tmp) t 如果只有一个逗号可以考虑CTE递归或者PLSQL:
with tmp(col) as(
select '77,233'
union all
select ',1,4,5,21,43,'
),
roy AS
(SELECT col =
CAST(LEFT(col, CHARINDEX(',', col + ',') - 1) AS NVARCHAR(100)), Split = CAST(STUFF(col + ',', 1, CHARINDEX(',', col + ','), '') AS NVARCHAR(100)) ,len(col)-len(REPLACE(col,',','')) as level
from tmp
UNION ALL
SELECT col = CAST(LEFT(Split, CHARINDEX(',', Split) - 1) AS NVARCHAR(100)),Split = CAST(STUFF(Split, 1, CHARINDEX(',', Split), '') AS NVARCHAR(100)),level-1
FROM Roy
WHERE split > '')
select col from roy where level =1
with tmp(col) as(
select '123,3,3,56,77,233'
union all
select ',1,4,5,21,43,'
)
select reverse(substring(col,
CHARINDEX(',', col) + 1,
CHARINDEX(',', col, CHARINDEX(',', col) + 1) -
CHARINDEX(',', col) - 1))
from (select reverse(col) as col from tmp) t 如果只有一个逗号可以考虑CTE递归或者PLSQL:
with tmp(col) as(
select '77,233'
union all
select ',1,4,5,21,43,'
),
roy AS
(SELECT col =
CAST(LEFT(col, CHARINDEX(',', col + ',') - 1) AS NVARCHAR(100)), Split = CAST(STUFF(col + ',', 1, CHARINDEX(',', col + ','), '') AS NVARCHAR(100)) ,len(col)-len(REPLACE(col,',','')) as level
from tmp
UNION ALL
SELECT col = CAST(LEFT(Split, CHARINDEX(',', Split) - 1) AS NVARCHAR(100)),Split = CAST(STUFF(Split, 1, CHARINDEX(',', Split), '') AS NVARCHAR(100)),level-1
FROM Roy
WHERE split > '')
select col from roy where level =1
追问
你好,是取第一个横杠和第一个空格之前的字符串
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用的什么数据库?
楼上那个胡诌八扯你也追问,一看就不知道哪复制的。
你把你上边结果也罗列一下。
楼上那个胡诌八扯你也追问,一看就不知道哪复制的。
你把你上边结果也罗列一下。
追问
数据库是sql2008 r,要的结果是这样的
DN350
DN150
DN350
DN350
DN100
M20*170
DN300
追答
创建表:
create table test
(str varchar(50))
insert into test values ('DN350-DD')
insert into test values ('DN150-1.0-DF')
insert into test values ('DN350-1.0-DF-B')
insert into test values ('DN350 PN1.0')
insert into test values ('DN100')
insert into test values ('M20*170')
insert into test values ('DN300-暂无区别')
执行:
select case when str like '%-%' then substring(str,1,CHARINDEX('-',str)-1) when str like '% %' then substring(str,1,CHARINDEX(' ',str)-1) else STR end from test
结果:
看看是这个意思不
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询